如何解决使用 Python Paramiko 将所有文件从本地目录上传到 SFTP 服务器
我有一个代码,应该使用 Paramiko sftp.put
将一些 .csv 文件从本地文件夹传输到远程服务器。我已经尝试了很多代码,但没有一个有效,我需要帮助找到传输这些文件的正确方法,当我执行我的代码时,我收到以下错误:
runfile('C:/Users/rpa2224/Desktop/projpython/SFTPproject.py',wdir='C:/Users/rpa2224/Desktop/projpython')
C:/Users/rpa2224/Desktop/projpython/FilesCSV/ZEBASE-20200103.csv>>>/dev/ZEBASE-20200103.csv
C:/Users/rpa2224/Desktop/projpython/FilesCSV/ZEBASE-20200104.csv>>>/dev/ZEBASE-20200104.csv
Traceback (most recent call last):
File "C:\Users\rpa2224\Desktop\projpython\SFTPproject.py",line 92,in <module>
put_server_files(local_path,**server)
File "C:\Users\rpa2224\Desktop\projpython\SFTPproject.py",line 74,in put_server_files
sftp_con.put(file_local,file_remote)
File "C:\Users\rpa2224\Anaconda3\lib\site-packages\paramiko\sftp_client.py",line 757,in put
file_size = os.stat(localpath).st_size
FileNotFoundError: [WinError 2] System cannot find the file specified: 'C:/Users/rpa2224/Desktop/projpython/FilesCSV/ZEBASE-20200104.csv'
但是我的本地路径上有很多 .csv 文件,我不知道我做错了什么,请按照下面的代码进行操作:
import paramiko
import re
def put_server_files(local_path,host,port,username,remote_path,file_pattern):
privkey = "C:/path/to/my/private/key.pem"
ssh_con = paramiko.SSHClient()
private_key_path = privkey
ssh_con.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key = paramiko.RSAKey.from_private_key_file(private_key_path)
ssh_con.connect(host,None,key)
sftp_con = ssh_con.open_sftp()
all_files_in_path = sftp_con.listdir(path=local_path)
r = re.compile(file_pattern)
files = list(filter(r.match,all_files_in_path))
for file in files:
file_remote = remote_path + file
file_local = local_path + file
print(file_local + '>>>' + file_remote)
sftp_con.put(file_local,file_remote)
sftp_con.close()
ssh_con.close()
list_of_servers = [
{ 'host': 'myhost','port': 22,'username': 'myusername','remote_path': 'path/to/my/remote/','file_pattern': 'ZEBASE'}
]
local_path = r"path/to/my/local/directory"
for server in list_of_servers:
put_server_files(local_path,**server)
解决方法
如果您尝试从本地目录上传所有文件,则必须使用 os.listdir
,而不是 SFTPClient.listdir
:
all_files_in_path = os.listdir(local_path)
或者,您可以使用 pysftp's Connection.put_d
在一次调用中上传目录。
sftp.put_d(local_path,remote_path)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。