我有一个文本文件存在本地机器上,该文件是由每日运行在cron中的Python脚本生成的。
我想添加一些代码,将该文件通过SSH安全地发送到我的服务器上。
我想添加一些代码,将该文件通过SSH安全地发送到我的服务器上。
如果您想使用SSL证书,请尝试以下内容:
import subprocess
try:
# Set scp and ssh data.
connUser = 'john'
connHost = 'my.host.com'
connPath = '/home/john/'
connPrivateKey = '/home/user/myKey.pem'
# Use scp to send file from local to host.
scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])
except CalledProcessError:
print('ERROR: Connection to host failed!')
通过子进程调用scp
命令无法在脚本内接收进度报告。可以使用pexpect
来提取该信息:
import pipes
import re
import pexpect # $ pip install pexpect
def progress(locals):
# extract percents
print(int(re.search(br'(\d+)%$', locals['child'].after).group(1)))
command = "scp %s %s" % tuple(map(pipes.quote, [srcfile, destination]))
pexpect.run(command, events={r'\d+%': progress})
有点取巧,但以下方法应该可行 :)
import os
filePath = "/foo/bar/baz.py"
serverPath = "/blah/boo/boom.py"
os.system("scp "+filePath+" user@myserver.com:"+serverPath)