Python Hangs Over Ssh

Python hangs over ssh

Try ssh -t hostname python_script. By default, ssh doesn't allocate a pseudo-tty to interact with when it's given a program to run (although it does if you just do ssh hostname); -t tells it to do so.

ssh hangs when command invoked directly, but exits cleanly when run interactive

s = p.stderr.readline()

I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.

When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.

Terminal hangs after sshing via python subprocess

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)


Related Topics



Leave a reply



Submit