1

I'm attempting to use a subprocess to interact with some files through sftp. I can get it to connect and exec one command, but then the process dies. How can I maintain control over this process and keep moving around in sftp?


import os
import subprocess

serverFiles = 'sftp.servername.com'
userFiles = 'myusername'
keyfileFiles = 'C:\\key\\file\\path'


with subprocess.Popen(['sftp','-Q','-i',keyfileFiles,userFiles+'@'+serverFiles], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) as proc:
    (out, err) = proc.communicate(input='ls -l'.encode())
    print(out.decode())
    #process dies. cannot proc.stdin.write, cannot proc.communicate

My output shows me the welcome banner, then the ls from the top level folder, then the process is ended and any following commands error out with proc being closed.

meteorainer
  • 913
  • 8
  • 21
  • Can you use other python modules for SFTP like paramiko ? http://www.paramiko.org/ Also you can write a pexpect script for interactive commands on the shell ? I dont believe subprocess is the right module to use for interactive shell commands – cmidi Sep 25 '15 at 14:33
  • My first thought was to use paramiko as well, but there are a few restrictions blocking the way. Namely versioning and managerial aversion to external packages. Do you have a suggestion outside of subprocess? – meteorainer Sep 25 '15 at 15:05
  • I would have suggested pexpect https://pexpect.readthedocs.org/en/stable/ to create a expect script for interactive shell commands if pexpect is available – cmidi Sep 25 '15 at 15:23
  • @cmidi: `pexpect` won't work on Windows (no `pty`). OP could try [`winpexpect`](https://bitbucket.org/geertj/winpexpect/wiki/Home) though It doesn't seem to be maintained. – jfs Sep 25 '15 at 18:44
  • That's kind of what I've been finding. Super old libraries (like paramiko and pysftp) that have badly/not maintained dependencies. – meteorainer Sep 26 '15 at 02:15
  • `paramiko` is actively maintained. https://github.com/paramiko/paramiko – jfs Mar 12 '16 at 20:45

1 Answers1

0

I recommend using the Fabric library. It is designed for SSH and SFTP operations.

Here are a few resources that can show you how to use it:

  1. How do I copy a directory to a remote machine using Fabric?

  2. http://www.pythonforbeginners.com/systems-programming/how-to-use-fabric-in-python/

  3. Using Python Fabric without the command-line tool (fab)
  4. How to set target hosts in Fabric file
Community
  • 1
  • 1
Charlie Haley
  • 4,152
  • 4
  • 22
  • 36