【发布时间】:2013-11-26 03:47:22
【问题描述】:
每个人。
我在窗口 7 x64 上使用带有 python 3.3.3 x64 的 parmiko,以下是我的代码,奇怪的是我需要在使用 client.close() 结束会话之前添加 time.sleep(0.01) 延迟.否则SSH主机会存在很多进程,无法自动结束。
谁能帮我解释一下这些? 用于 python3 的 paramiko: (https://travis-ci.org/nischu7/paramiko)
重复的步骤如下: A) 去掉 client.close() 之前的 time.sleep(0.01) 并运行脚本
B)输入 SSH 主机的密码
C)输入第一条命令,例如:ls -la
D) 非常频繁地键入命令,例如,按住向上箭头并多次输入交替非常快
E)当使用 ps -ef | grep dropbear(SSH服务器,OpenSSH我没测试过),存在很多进程
F) 键入 exit 和 Ctrl + Z 以终止脚本
G)在 client.close() 之前保持 time.sleep(0.01) 并再次运行脚本
H) 执行上述 B、C、D 步骤,然后用 ps -ef | 检查再次grep dropbear,这个脚本只会生成一个SSH进程。
这里是代码:
from tkinter import *
from threading import Thread
from queue import Queue, Empty
import _thread
import time
from paramiko import SSHClient, Transport, AutoAddPolicy, WarningPolicy
import getpass
def start(client):
try :
client.connect(hostname='127.0.0.1', port=22, username='ubuntu', password=pw)
return True
except Exception as e:
client.close()
print(e)
return False
def check(client,outqueue):
while start(client):
outqueue.put("Command to run: ")
cmd = input()
if cmd == "exit":
client.close()
break
chan = client.get_transport().open_session()
outqueue.put("running '%s'" % cmd)
chan.exec_command(cmd)
while True:
if chan.recv_ready():
data = chan.recv(4096).decode('ascii')
outqueue.put("recv:\n%s" %data)
if chan.recv_stderr_ready():
error = chan.recv_stderr(4096).decode('ascii')
outqueue.put("error:\n%s" %error)
if chan.exit_status_ready():
exitcode = chan.recv_exit_status()
outqueue.put("exit status: %s" %exitcode)
#print('close s')
#print(client.close())
time.sleep(0.01)
client.close()
#print('close e')
#time.sleep(0.05)
break
def reader(outqueue):
while True:
while outqueue.qsize():
try:
data = outqueue.get()
if data:
print(data)
except Excetpiton as e:
print(e)
#continue
#time.sleep(0.5)
if __name__=='__main__':
pw = getpass.getpass()
client = SSHClient()
client.set_missing_host_key_policy(WarningPolicy())
#client.set_missing_host_key_policy(AutoAddPolicy())
outqueue = Queue()
r = Thread(target=reader,args=(outqueue,))
r.daemon = True
r.start()
t = Thread(target=check,args=(client,outqueue,))
#t.daemon = True
t.start()
t.join()
【问题讨论】:
标签: python-3.x paramiko