python - 用于 Python 中批量复制的持久 WinSCP 连接

标签 python copy winscp

我正在尝试将数千个文件复制到远程服务器。这些文件是在脚本中实时生成的。我在 Windows 系统上工作,需要将文件复制到 Linux 服务器(因此需要转义)。

我目前有:

import os
os.system("winscp.exe /console /command  \"option batch on\" \"option confirm off\" \"open user:pass@host\" \"put f1.txt /remote/dest/\"")

我正在使用 Python 生成文件,但需要一种方法来保持远程连接,以便我可以在生成每个文件时将其复制到服务器(而不是每次都创建一个新连接)。这样,我只需要更改看跌期权中的字段:

"put f2 /remote/dest"
"put f3 /remote/dest"

等等

最佳答案

我需要这样做并发现与此类似的代码运行良好:

from subprocess import Popen, PIPE

WINSCP = r'c:\<path to>\winscp.com'

class UploadFailed(Exception):
    pass

def upload_files(host, user, passwd, files):
    cmds = ['option batch abort', 'option confirm off']
    cmds.append('open sftp://{user}:{passwd}@{host}/'.format(host=host, user=user, passwd=passwd))
    cmds.append('put {} ./'.format(' '.join(files)))
    cmds.append('exit\n')
    with Popen(WINSCP, stdin=PIPE, stdout=PIPE, stderr=PIPE,
               universal_newlines=True) as winscp: #might need shell = True here
        stdout, stderr = winscp.communicate('\n'.join(cmds))
    if winscp.returncode:
        # WinSCP returns 0 for success, so upload failed
        raise UploadFailed

这是简化的(并使用 Python 3),但您明白了。

关于python - 用于 Python 中批量复制的持久 WinSCP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8197853/

相关文章:

python - 使用 python 使用 selenium 提交验证码

python - 两个相同比例的y轴

JQuery 解决方案将特定标题从一个项目复制到 div 中的另一个项目

winscp - 将 Atom.io 与 winscp 结合使用

python - 如何防止 pd.concat 在同名列后插入 `.1` ?

python - 如何在 macOS 上安装 dbus-python?

vbscript - 如何确定 VBScript 中的复制何时完成?

Android如何在android中检测Edittext的Copy事件

linux - 用 FileZilla 替换 WinSCP - 这可能吗?

import - 从 WinSCP 导出(迁移) session 并导入 FileZilla