[英]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'
. 我在GUI上有一个名为“ erp”的按钮,如果按此按钮,它应该首先对名为(主机ID名称)
'ayaancritbowh91302xy'
的计算机执行ssh
命令,然后应执行(cd更改目录)和'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?
谁能帮我这个?
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. 我添加了-T,因此ssh不会尝试分配伪tty,并通过使用communication来避免END和stdout问题。
To execute several shell commands via ssh: 要通过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
contains stdout, error
-- stderr, p.returncode
-- exit status. output
包含stdout, error
p.returncode
, p.returncode
退出状态。
与进程的标准输出对话时,它必须是sshProcess.stdout.readLines()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.