I've been working on this for a long time, and any help would be appreciated.
What I am trying to do here is ssh to a testing server, then cd .., and then print a list of the directories in that folder through python. This code is my best attempt:
def subprocess_cmd(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
    print "Test 1"
    proc_stdout = process.communicate()[0].strip()
    #proc_stdout= process.stdout.readlines() (Gives same outcome as communicate)
    #proc_stdout= process.stdout.read()  (Gives same outcome as communicate)
    print "Test 2"
    print proc_stdout
subprocess_cmd('ssh user@server -p 111;cd ..;ls')
For some reason this function always hangs at the "proc_stdout= "step. It never prints "Test 2" or returns a list of files. It works fine if I take out the ssh command though. What I expect to see in the terminal is something like this, but instead the terminal hangs, and I can't interact with it anymore:
dredbounds-computer: python file_name.py
Test 1
Test 2
FileA
FileB
FileC
Update: I modified the code and and put proc_stdout= process.stderr. communicate(). Here is my updated code:
def subprocess_cmd(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
    print "Test 1"
    proc_stderr= process.stderr. communicate()
    print "Test 2"
    print proc_stderr
    print "Test 3"
Running this I am getting the following error in the terminal:
dredbounds-computer: python terminal_test.py
Test 1
Traceback (most recent call last):
  File "file_name.py", line 26, in <module>
    subprocess_cmd('ssh user@server -p 111;cd ..;ls')
  File "terminal_test.py", line 21, in subprocess_cmd
    proc_stdout= process.stderr. communicate()
AttributeError: 'NoneType' object has no attribute 'communicate'
Does anyone know how I can fix this code, or another way of doing the same thing. Not sure why this is giving me a none type error. Is there something wrong with how I call my ssh command? I've entered the same commands manually in the terminal and it returns a list of directories, so it should work in theory. Any advice?
If you want just to list directory contents, you can send some command over SSH.
Bash:
ssh 192.168.122.24 ls /tmp
or if you want to use "cd" as in your question:
ssh 192.168.122.24 "cd /tmp; ls"
Python script example:
import subprocess
HOST = 'server'
PORT = '111'
USER = 'user'
CMD = 'cd /tmp; ls'
process = subprocess.Popen(['ssh', '{}@{}'.format(USER, HOST),
                            '-p', PORT, CMD], 
                           shell=False,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
result = process.stdout.readlines()
if not result:
    err = process.stderr.readlines()
    print('ERROR: {}'.format(err))
else:
    print(result)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With