ssh 与 Subprocess.popen [英] ssh with Subprocess.popen

查看:67
本文介绍了ssh 与 Subprocess.popen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我遇到了一个小问题.可能是我遗漏了一些明显的东西,但我无法找出问题所在.我有一个 GUI,我有一个名为erp"的按钮,如果我按下它应该首先对一台名为(主机 ID 名称)'ayaancritbowh91302xy' 的机器执行 ssh然后它应该执行诸如 (cd change dir) 和 'ls -l' 之类的命令.我试过以下代码:

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)

我收到以下错误:

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?

推荐答案

试试这个:

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

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

这篇关于ssh 与 Subprocess.popen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆