我为这个问题创建了一个 hacky 解决方法。它不是很聪明,并且可能在所有情况下都不稳定。因此,请小心使用。使用 pysftp 0.2.9 在 Python 3.x 上测试。
import os
import pysftp
# copy all folders (non-recursively) from from_dir (windows file system) to to_dir (linux file system)
def copy_files(host, user, pw, from_dir, to_dir):
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=host, username=user, password=pw, cnopts=cnopts) as sftp:
from_dir = os.path.normpath(from_dir)
to_dir = "/" + os.path.normpath(to_dir).replace("\\", "/").strip("/")
top_folder = os.path.split(to_dir)[1]
files = [file for file in os.listdir(from_dir) if os.path.isfile(os.path.join(from_dir, file))]
for file in files:
sftp.cwd(to_dir)
sftp.put(os.path.join(from_dir, file), os.path.join("./{}".format(top_folder), file))
sftp.execute(r'mv "{2}/{0}\{1}" "{2}/{1}"'.format(top_folder, file, to_dir))
# usage: always use full paths for all directories
copy_files("hostname", "username", "password", "D:/Folder/from_folder", "/root/Documents/to_folder")