如何通过使用os.system...Please帮助在python脚本中调用unix shell命令,将文件从源主机sftp到python目标服务器
I have tried the following code
dstfilename="hi.txt"
host="abc.com"
user="sa"
os.system("echo cd /tmp >sample.txt)
os.system("echo put %(dstfilename)s" %locals()) // line 2
os.system("echo bye >>sample.txt")
os.system("sftp -B /var/tmp/sample.txt %(user)s@%(host)s)
How to append this result of line to sample.txt?
os.system("echo put %(dstfilename)s %locals()) >>sample.txt" // Seems this is syntatically not correct.
cat>sample.txt //should look like this
cd /tmp
put /var/tmp/hi.txt
bye
Any help?
Thanks you发布于 2012-05-11 13:47:07
您应该将命令通过管道传输到sftp中。尝试如下所示:
import os
import subprocess
dstfilename="/var/tmp/hi.txt"
samplefilename="/var/tmp/sample.txt"
target="sa@abc.com"
sp = subprocess.Popen(['sftp', target], shell=False, stdin=subprocess.PIPE)
sp.stdin.write("cd /tmp\n")
sp.stdin.write("put %s\n" % dstfilename)
sp.stdin.write("bye\n")
[ do other stuff ]
sp.stdin.write("put %s\n" % otherfilename)
[ and finally ]
sp.stdin.write("bye\n")
sp.stdin.close()但是,为了回答你的问题:
os.system("echo put %(dstfilename)s %locals()) >>sample.txt" // Seems this is syntatically not correct.当然不是,你想把一个字符串传递给os.system。所以它必须看起来像
os.system(<string expression>)末尾有一个)。
字符串表达式由应用了%格式的字符串组成:
"string literal" % locals()字符串文字包含shell的重定向:
"echo put %(dstfilename)s >>sample.txt"合在一起:
os.system("echo put %(dstfilename)s >>sample.txt" % locals())。但如上所述,这是我能想象到的最糟糕的解决方案-最好直接写入临时文件,甚至更好地直接写入子进程。
发布于 2012-05-11 11:59:04
嗯,我认为你的问题的字面解决方案应该是这样的:
import os
dstfilename="/var/tmp/hi.txt"
samplefilename="/var/tmp/sample.txt"
host="abc.com"
user="sa"
with open(samplefilename, "w") as fd:
fd.write("cd /tmp\n")
fd.write("put %s\n" % dstfilename)
fd.write("bye\n")
os.system("sftp -B %s %s@%s" % (samplefilename, user, host))正如@larsks所说,使用合适的文件处理程序为您制作临时文件,我个人的偏好是不使用locals()进行字符串格式化。
但是,根据用例的不同,我不认为这是一种特别合适的方法-例如,如何输入sftp站点的密码?
我认为如果你看一下Paramiko中的SFTPClient,你会得到一个更健壮的解决方案,或者如果做不到,你可能需要像pexpect这样的东西来帮助进行自动化。
发布于 2016-08-17 14:26:58
如果您希望在任何sftp命令失败时返回非零代码,则应将命令写入文件,然后对其运行sftp批处理。通过这种方式,您可以检索返回代码以检查sftp命令是否失败。
下面是一个简单的例子:
import subprocess
host="abc.com"
user="sa"
user_host="%s@%s" % (user, host)
execute_sftp_commands(['put hi.txt', 'put myfile.txt'])
def execute_sftp_commands(sftp_command_list):
with open('batch.txt', 'w') as sftp_file:
for sftp_command in sftp_command_list:
sftp_file.write("%s\n" % sftp_command)
sftp_file.write('quit\n')
sftp_process = subprocess.Popen(['sftp', '-b', 'batch.txt', user_host], shell=False)
sftp_process.communicate()
if sftp_process.returncode != 0:
print("sftp failed on one or more commands: {0}".format(sftp_command_list))快速声明:我没有在shell中运行这段代码,所以可能会出现打字错误。如果是这样,给我发个评论,我会改正的。
https://stackoverflow.com/questions/10544824
复制相似问题