我有一个代码,应该使用Paramikosftp.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, port, username, 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
:或者,您可以使用pysftp's ^{} 在单个调用中上载目录
相关问题 更多 >
编程相关推荐