![](/img/trans.png)
[英]How to continuously write output from Python Program running on a remote host (Raspberry Pi) executed with C# SSH.NET on local console?
[英]how to get console output from a remote computer (ssh + python)
我用google搜索“python ssh”。 有一個很棒的模塊pexpect
,它可以使用ssh(帶密碼)訪問遠程計算機。
連接遠程計算機后,我可以執行其他命令。 但是我無法再次在python中獲得結果。
p = pexpect.spawn("ssh user@remote_computer")
print "connecting..."
p.waitnoecho()
p.sendline(my_password)
print "connected"
p.sendline("ps -ef")
p.expect(pexpect.EOF) # this will take very long time
print p.before
如何在我的情況下得到ps -ef
的結果?
你嘗試過更簡單的方法嗎?
>>> from subprocess import Popen, PIPE
>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
... stdout=PIPE).communicate()
>>> print(stdout)
當然,這只能起作用,因為我的ssh-agent
運行時預先加載了遠程主機知道的私鑰。
child = pexpect.spawn("ssh user@remote_computer ps -ef")
print "connecting..."
i = child.expect(['user@remote_computer\'s password:'])
child.sendline(user_password)
i = child.expect([' .*']) #or use i = child.expect([pexpect.EOF])
if i == 0:
print child.after # uncomment when using [' .*'] pattern
#print child.before # uncomment when using EOF pattern
else:
print "Unable to capture output"
Hope this help..
嘗試發送
p.sendline("ps -ef\n")
IIRC,您發送的文本是逐字解釋的,因此另一台計算機可能正在等待您完成命令。
您可能還想研究paramiko ,它是Python的另一個SSH庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.