Sftp in python by invoking unix-shell commands

command, python, sftp, unix

Solution

You should pipe your commands into `sftp`. Try something like this:

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()

But, in order to answer your question:

os.system("echo put %(dstfilename)s %locals()) >>sample.txt" // Seems this is syntatically not correct.

Of course it isn't. You want to pass a stringto os.system. So it has to look like

os.system(<string expression>)

with a `)` at the end.

The string expression consists of a string literal with an applied `%` formatting:

"string literal" % locals()

And the string literal contains the redirection for the shell:

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

And together:

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

. But as said, this is the worst solution I can imagine - better write directly to a temp file or even better pipe directly into the sub process.

Problem

How can we sftp a file from source host to a destinition server in python by invoking unix shell commands in python script using os.system...Please help ``` 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 ```

Original source