Foundations of Python Network Programming

(WallPaper) #1
Chapter 16 ■ telnet and SSh

313

Listing 16-7. Listing a Directory and Fetching Files with SFTP


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter16/sftp_get.py


Fetching files with SFTP


import argparse, functools, paramiko


class AllowAnythingPolicy(paramiko.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return


def main(hostname, username, filenames):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(AllowAnythingPolicy())
client.connect(hostname, username=username) # password='')


def print_status(filename, bytes_so_far, bytes_total):
percent = 100. * bytes_so_far / bytes_total
print('Transfer of %r is at %d/%d bytes (%.1f%%)' % (
filename, bytes_so_far, bytes_total, percent))


sftp = client.open_sftp()
for filename in filenames:
if filename.endswith('.copy'):
continue
callback = functools.partial(print_status, filename)
sftp.get(filename, filename + '.copy', callback=callback)
client.close()


if name == 'main':
parser = argparse.ArgumentParser(description='Copy files over SSH')
parser.add_argument('hostname', help='Remote machine name')
parser.add_argument('username', help='Username on the remote machine')
parser.add_argument('filename', nargs='+', help='Filenames to fetch')
args = parser.parse_args()
main(args.hostname, args.username, args.filename)


Note that although I made a big deal of talking about how each file that you open with SFTP uses its own
independent channel, the simple get() and put() convenience functions provided by paramiko, which are really
lightweight wrappers for an open() followed by a loop that reads and writes, do not attempt any asynchrony; instead,
they just block and wait until each whole file has arrived. This means that the foregoing script calmly transfers one file
at a time, producing output that looks something like this:


$ python sftp.py guinness brandon W-2.pdf miles.png
Transfer of 'W-2.pdf' is at 32768/115065 bytes (28.5%)
Transfer of 'W-2.pdf' is at 65536/115065 bytes (57.0%)
Transfer of 'W-2.pdf' is at 98304/115065 bytes (85.4%)
Transfer of 'W-2.pdf' is at 115065/115065 bytes (100.0%)
Transfer of 'W-2.pdf' is at 115065/115065 bytes (100.0%)
Transfer of 'miles.png' is at 15577/15577 bytes (100.0%)
Transfer of 'miles.png' is at 15577/15577 bytes (100.0%)

Free download pdf