我想编写连接到我的大学SFTP服务器并通过练习下载最新文件的脚本。到目前为止,我已经从Paramiko示例中更改了一些代码,但是我不知道如何下载最新文件。
这是我的代码:
import functools
import paramiko
class AllowAnythingPolicy(paramiko.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return
adress = 'adress'
username = 'username'
password = 'password'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(AllowAnythingPolicy())
client.connect(adress, username= username, password=password)
def my_callback(filename, bytes_so_far, bytes_total):
print ('Transfer of %r is in progress' % filename)
sftp = client.open_sftp()
sftp.chdir('/directory/to/file')
for filename in sorted(sftp.listdir()):
if filename.startswith('Temat'):
callback_for_filename = functools.partial(my_callback, filename)
sftp.get(filename, filename, callback=callback_for_filename)
client.close()
使用SFTPClient.listdir_attr
而不是SFTPClient.listdir
来获得具有属性(包括文件时间戳记)的列表。
然后,找到具有最大.st_mtime
属性的文件条目。
代码如下:
latest = 0
latestfile = None
for fileattr in sftp.listdir_attr():
if fileattr.filename.startswith('Temat') and fileattr.st_mtime > latest:
latest = fileattr.st_mtime
latestfile = fileattr.filename
if latestfile is not None:
sftp.get(latestfile, latestfile)
有关更复杂的示例,请参见如何在Linux中获取包含感兴趣的特定文件的最新文件夹,并使用Python中的Paramiko下载该文件?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句