Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ssh with Subprocess.popen

Hello All i'm stuck with a small problem. May be i'm missing something obvious but i'm unable to figure out the problem. I've GUI where i have a button named "erp" and if i press that it should do an ssh first to a machine named (host id name) 'ayaancritbowh91302xy' and then it should execute commands like (cd change dir) and 'ls -l'. I've tried the following code:

def erptool():
    sshProcess = subprocess.Popen(['ssh -T', 'ayaancritbowh91302xy'],stdin=subprocess.PIPE, stdout = subprocess.PIPE)
    sshProcess.stdin.write("cd /home/thvajra/transfer/08_sagarwa\n")
    sshProcess.stdin.write("ls -l\n")
    sshProcess.stdin.write("echo END\n")
    for line in stdout.readlines():
        if line == "END\n":
        break
        print(line)

i got the following error:

Traceback (most recent call last):
  File "Cae_Selector.py", line 34, in erptool
    for line in stdout.readlines():
NameError: global name 'stdout' is not defined
Pseudo-terminal will not be allocated because stdin is not a terminal.

How to do this? can anyone help me with this?

like image 511
ayaan Avatar asked Apr 19 '26 11:04

ayaan


1 Answers

Try this:

#!/usr/bin/env python
import subprocess
def erptool():
    sshProcess = subprocess.Popen(['ssh', '-T', 'ayaancritbowh91302xy'],
                                  stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    out, err = sshProcess.communicate("cd /home/thvajra/transfer/08_sagarwa\nls -l\n")
    print(out),
erptool()

I added -T so ssh wouldn't try to allocate a pseudo-tty, and avoid END and stdout issues by using communicate.

like image 116
Nick Russo Avatar answered Apr 22 '26 01:04

Nick Russo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!