3

我正在尝试将数千个文件复制到远程服务器。这些文件是在脚本中实时生成的。我在 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"

等等

4

3 回答 3

5

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

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),但你明白了。

于 2015-10-29T17:24:22.993 回答
2

除了使用外部程序(winscp),您还可以使用像pyssh这样的 python ssh-library 。

于 2011-11-19T22:33:45.040 回答
0

您必须在 Python 中启动持久的 WinSCP 子进程,并将put命令连续提供给其标准输入。

我没有 Python 示例,但有一个等效的 JScript 示例:
https
://winscp.net/eng/docs/guide_automation_advanced#inout 或 C# 示例:
https ://winscp.net/eng/docs/guide_dotnet#input

尽管通过 Python 的 COM 接口使用 WinSCP .NET 程序集会更容易:
https ://winscp.net/eng/docs/library

于 2014-06-13T08:20:38.613 回答