Python中批量复制的持久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"
等等。
3 个回答
0
你需要在Python中启动一个持续运行的WinSCP子进程,并不断地将put
命令输入到它的标准输入中。
我没有Python的示例,但有一个等效的JScript示例:
https://winscp.net/eng/docs/guide_automation_advanced#inout
还有一个C#的示例:
https://winscp.net/eng/docs/guide_dotnet#input
不过,如果通过COM接口在Python中使用WinSCP的.NET库会简单得多:
https://winscp.net/eng/docs/library
2
你可以不使用外部程序(比如 winscp),而是用一个叫做 pyssh 的 Python SSH 库。
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写的),但你能明白我的意思。