from datetime import datetime
import pysftp
import fnmatch
import os
from stat import S_IMODE, S_ISDIR, S_ISREG
Hostname = "Hostname"
Username = "Username"
Password = "Password"
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=Hostname, username=Username, password=Password,
cnopts=cnopts) as sftp:
print("Connection successfully established ... ")
local_dir = r"D:\testing"
remote_dir = r'C:\Users\admin\Documents\personal'
for entry in sftp.listdir(remote_dir):
root, ext = os.path.splitext(entry)
for entry1 in sftp.listdir(local_dir):
root1, ext1 = os.path.splitext(entry1)
if root == root1:
if ext != ext1:
pass
elif root != root1:
remotepath = os.path.join(remote_dir, entry)
localpath = os.path.join(local_dir, entry)
sftp.get(remotepath, localpath, preserve_mtime=False)
我正在尝试将文件从 SFTP 服务器导出到本地。为此,我需要按服务器和本地文件夹中的文件名和文件扩展名来比较文件。
例如来自服务器的
abc.xlsx
、abc.csv
、adc.txt
以及
本地文件夹有 abc.xlsx
,那么我的脚本不应复制任何具有相同名称和相同扩展名或不同扩展名的文件。
这里我需要比较文件名和扩展名
os.listdir
作为本地路径。os.path.join
用于 SFTP 路径。这应该做:
localfiles = os.listdir(local_dir)
for rentry in sftp.listdir(remote_dir):
rroot, rext = os.path.splitext(rentry)
found = False
for lentry in localfiles:
lroot, lext = os.path.splitext(lentry)
if rroot == lroot:
found = True
break
if not found:
remotepath = remote_dir + "/" rentry
localpath = os.path.join(local_dir, rentry)
sftp.get(remotepath, localpath, preserve_mtime=False)
尽管现在,你不应该使用 pysftp,因为它已经死了。直接使用Paramiko代替。请参阅 pysftp 与 Paramiko。上面的代码也适用于 Paramiko 及其
SFTPClient.listdir
。
强制警告:不要设置
cnopts.hostkeys = None
,除非你不关心安全。有关正确的解决方案,请参阅使用 pysftp 验证主机密钥。