如何使用Paramiko从SFTP服务器下载最新文件?

9
我希望编写一个脚本,连接到我的大学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() 
2个回答

20
使用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下载该文件?

1
这对马丁来说非常有帮助。谢谢! - Furqan Rahamath
1
在网上搜索了几个小时后,这个答案完美地解决了我的问题,谢谢! - Àtishking

2
import paramiko
remote_path = '/tmp'

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=<IP>, username=<USER>, password=<PW>,allow_agent=False)
sftp_client = ssh_client.open_sftp()

sftp_client.chdir(remote_path)
for f in sorted(sftp_client.listdir_attr(), key=lambda k: k.st_mtime, reverse=True):
    sftp_client.get(f.filename, f.filename)
    break

sftp_client.close()
ssh_client.close()

这将使用密码(PW)作为用户(USER)连接到远程服务器(IP)并下载在<remote_path>下可用的最新文件。


2
虽然这段代码可能回答了问题,但提供关于它是如何解决问题的额外上下文信息会提高答案的长期价值。 - Sven Eberth
更新了,ftp_client仅是一个变量名,但已改为sftp_client以避免混淆。干杯! - Nikil Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接