每個人。paramiko的SSHClient.Close()方法需要等待?
我在窗口7 x64上使用python 3.3.3 x64的parmiko,以下是我的代碼,奇怪的是我需要在使用client.close()結束之前添加time.sleep(0.01)會話。否則,SSH主機中會存在很多進程,無法自動結束。
任何人都可以幫我解釋這些嗎? 的用於python3的paramiko: (https://travis-ci.org/nischu7/paramiko)
以下是重複以下步驟:)) 甲除去client.close(前time.sleep(0.01)和運行該腳本
B)類型的密碼SSH主機
C)鍵入第一個命令,例如:LS -la
d)輸入命令很頻繁,例如,按住向上箭頭和可選地輸入非常快幾次
E)當使用ps -ef | grep的dropbear(SSH服務器,我還沒有測試約OpenSSH的),有很多的工藝存在
F)鍵入exit和Ctrl + Z終止腳本
G)保持time.sleep(0.01)在client.close()之前再次運行腳本
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()