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