通过调用unixshell命令在python中实现Sftp

2024-10-01 13:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python脚本中调用unixshell命令,将文件从源主机sftp到目标服务器操作系统……请帮忙

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

Tags: sampleechotxthostputoscdhi
3条回答

您应该将您的命令导入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()

但是,为了回答你的问题:

^{pr2}$

当然不是。你想传递一个字符串吗操作系统. 所以它必须看起来像

os.system(<string expression>)

结尾有一个)。在

字符串表达式由应用了%格式的字符串文本组成:

"string literal" % locals()

字符串文本包含shell的重定向:

"echo put %(dstfilename)s >>sample.txt"

一起:

os.system("echo put %(dstfilename)s >>sample.txt" % locals())

一。但正如前面所说,这是我能想到的最糟糕的解决方案——最好直接写入临时文件,或者直接通过管道导入子进程。在

如果希望在任何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(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中运行这个,所以可能会出现错误。如果是这样,请给我一个评论,我会改正的。在

好吧,我想你问题的字面意思应该是这样的:

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所说,使用适当的filehandler为您生成tmp文件,我个人的偏好是不使用locals()进行字符串格式化。在

然而,根据用例的不同,我不认为这是一个特别合适的方法-例如,如何输入sftp站点的密码?在

我想如果你看一下Paramiko中的SFTPClient,你会得到一个更健壮的解决方案,或者如果没有,你可能需要类似pexpect的东西来帮助进行自动化。在

相关问题 更多 >