【问题标题】:ssh with Subprocess.popenssh 与 Subprocess.popen
【发布时间】:2014-12-01 09:29:02
【问题描述】:

大家好,我遇到了一个小问题。可能是我遗漏了一些明显的东西,但我无法找出问题所在。我有一个 GUI,我有一个名为“erp”的按钮,如果我按下它,它应该首先对名为(主机 ID 名称)'ayaancritbowh91302xy' 的机器执行 ssh,然后它应该执行类似(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.

如何做到这一点?谁能帮我解决这个问题?

【问题讨论】:

  • 首先修复 stdout 错误:尝试添加“from sys import stdout”或将其更改为 sshProcess.stdout,如果这就是您的意思。
  • 考虑在 'ssh' 之后添加一个 '-T',这样 ssh 甚至不会尝试分配伪终端。
  • 我在 ssh 之后使用了 '-t' 现在我得到了以下错误:文件“Cae_Selector.py”,第 35 行,在 erptool 中,对于 stdout.readlines() 中的行:IOError: File not open for读取用法:ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q cipher |密码验证 |麦克 |凯克斯 |克
  • 对不起——大写的T
  • @ayaan 如果您想在后台保持 ssh 进程打开,请不要使用communicate,但请查看stackoverflow.com/questions/375427/… 接受的答案

标签: python ssh subprocess


【解决方案1】:

试试这个:

#!/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 问题。

【讨论】:

    【解决方案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 -- 标准错误,p.returncode -- 退出状态。

    【讨论】:

    【解决方案3】:

    它必须是 sshProcess.stdout.readLines() ,因为您正在与进程的标准输出对话......

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 2023-03-09
      • 2013-01-02
      • 2011-06-25
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      相关资源
      最近更新 更多