使用Subprocess.popen的ssh

时间:2014-10-07 02:41:41

标签: python ssh subprocess

大家好,我遇到了一个小问题。可能是我错过了一些明显的东西,但我无法弄清楚问题。我有GUI,我有一个名为“erp”的按钮,如果我按下它应首先ssh到名为(主机ID名称)'ayaancritbowh91302xy'的机器,然后它应该执行像(如() cd change dir)和'ls -l'。我尝试过以下代码:

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)

我收到以下错误:

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.

怎么做?任何人都可以帮我这个吗?

3 个答案:

答案 0 :(得分:3)

试试这个:

#!/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()

我添加-T所以ssh不会尝试分配伪tty,并通过使用通信来避免END和stdout问题。

答案 1 :(得分:2)

通过ssh执行多个shell命令:

#!/usr/bin/env python3
from subprocess import Popen, PIPE

with Popen(['ssh', '-T', 'ayaancritbowh91302xy'],
           stdin=PIPE, stdout=PIPE, stderr=PIPE,
           universal_newlines=True) as p:
    output, error = p.communicate("""            
        cd /home/thvajra/transfer/08_sagarwa
        ls -l
        """)
    print(output)
    print(error)
    print(p.returncode)

output包含标准输出,error - stderr,p.returncode - 退出状态。

答案 2 :(得分:1)

当你正在与进程的stdout交谈时,它必须是sshProcess.stdout.readLines()....