使用Python Paramiko将所有文件从本地目录上载到SFTP服务器

2024-09-30 02:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码,应该使用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)

Tags: csvpathinserverremoteputlocalfiles
1条回答
网友
1楼 · 发布于 2024-09-30 02:26:59

如果您试图从本地目录上载所有文件,则必须使用os.listdir,而不是SFTPClient.listdir

all_files_in_path = os.listdir(local_path)

或者,您可以使用pysftp's ^{}在单个调用中上载目录

sftp.put_d(local_path, remote_path)

相关问题 更多 >

    热门问题