0

I have a script that writes a file to disk and then needs to upload it to a remote server using psftp.

based on some of answers I have seen on this site I have a basic idea of what I want to do but because:

  1. My code is written in Python 3.x

  2. My code uses a mix of strings and variables in the commands

I have not been successful.

here is my code ( after setting up the variables)

connection_string = "" +prog+ "-P "  +port+ "-pw " +passwd+ " " +user+"@"+host

p = subprocess.Popen(connection_string.split(),stdin=subprocess.PIPE, stdout=subprocess.PIPE,shell=True)

sftp_cmd = "put "+upload_file

encoded_cmd = str.encode(sftp_cmd)

p.stdin.write(encoded_cmd)
# I would have rather used p.stdin.write(b'sftp_cmd') to create a buffer from the string but that didn't seem to work either.

the code compiles but the file does not get uploaded

1) What am I doing wrong ? :-)

2) How can I see if a connection is made and what command actually goes through ?

3) Is this the best way to call psftp or perhapes I should write a batch file on the fly each time and use the "-b" flag to call it ?

Note. I cannot use any libraries that do not come with the standard Python distro in my code. So I have to use psftp.

referenced answers:

Can i control PSFTP from a Python script?

formatting strings for stdin.write() in python 3.x

TIA

Community
  • 1
  • 1
eramm
  • 191
  • 16
  • Any specific reason why other libraries like paramiko cannot be used? Also, you may like to have a look at pscp. – shantanoo May 13 '15 at 19:17
  • I can't use external libraries due to company restrictions. Scp seems to be blocked on the server (I have no control over it) – eramm May 14 '15 at 14:03
  • for now I wrote the commands to a file and used psftp -b but would still like to know how to do this in a more python way. – eramm May 14 '15 at 14:45
  • [Don't use a list argument and `shell=True` together](http://stackoverflow.com/q/15109665/4279) on POSIX systems. – jfs May 14 '15 at 18:34
  • don't: `klass.method(some_object)`, call `some_object.method()` instead e.g., `sftp_cmd.encode()`. – jfs May 14 '15 at 18:37

1 Answers1

0

Drop shell=True. If prog accept a command on its stdin and you want to get its output as a bytestring then you could use subprocess.check_output():

#!/usr/bin/env python3
from subprocess import check_output

output = check_output([prog, "-P", port, "-pw", passwd, user + "@" + host],
                      input=("put " + upload_file).encode()) # utf8 filename

It raises an exception if prog returns a non-zero exit status (It usually means an error).

jfs
  • 399,953
  • 195
  • 994
  • 1,670