0
當我的sendShell函數中的所有命令完成執行我的commandfactory列表中的所有命令時,我希望我的腳本停止。我可以成功關閉傳輸連接,但腳本似乎在所有命令運行並且傳輸連接關閉後掛起。任何人都可以幫助我找到一種方法來阻止我的腳本,當所有的命令完成執行和傳輸會話關閉?無法殺死Python腳本
我試圖通過添加while而不是self.transport.close()到我的輸出循環來殺死腳本。
def process(self):
while not self.transport.close(): #Kill script here !!!
# Print data when available
if self.shell != None and self.shell.recv_ready():
alldata = self.shell.recv(1024)
while self.shell.recv_ready():
alldata += self.shell.recv(1024)
strdata = alldata.decode("utf8")
strdata.rstrip("\r\n")
print(strdata, end = ""),
代碼:
import threading, paramiko, re, os
class ssh:
shell = None
client = None
transport = None
def __init__(self, address, username, password):
print("Connecting to server on ip", str(address) + ".")
self.client = paramiko.client.SSHClient()
self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
self.transport = paramiko.Transport((address, 22))
self.transport.connect(username=username, password=password)
thread = threading.Thread(target=self.process)
thread.daemon = True
thread.start()
def closeConnection(self):
if(self.client != None):
self.client.close()
self.transport.close()
def openShell(self):
self.shell = self.client.invoke_shell()
def sendShell(self):
self.commandfactory = []
print("\nWelcome to Command Factory. Enter Commands you want to execute.\nType \"done\" when you are finished:")
while not re.search(r"done.*", str(self.commandfactory)):
self.commandfactory.append(input(":"))
if self.commandfactory[-1] == "done":
del self.commandfactory[-1]
break
print ("Here are the commands you're going to execute:\n" + str(self.commandfactory))
if(self.shell):
self.shell.send("enable" + "\n")
self.shell.send("ilovebeer" + "\n")
self.shell.send("term len 0" + "\n")
for cmdcnt in range(0,len(self.commandfactory)):
self.shell.send(self.commandfactory[cmdcnt] + "\n")
self.shell.send("exit" + "\n")
self.shell.transport.close()
else:
print("Shell not opened.")
def process(self):
# global connection
while not self.transport.close():
# Print data when available
if self.shell != None and self.shell.recv_ready():
alldata = self.shell.recv(1024)
while self.shell.recv_ready():
alldata += self.shell.recv(1024)
strdata = alldata.decode("utf8")
strdata.rstrip("\r\n")
print(strdata, end = ""),
sshUsername = "xxxxx"
sshPassword = "xxxxxxx"
sshServer = "xxxxxxxx"
connection = ssh(sshServer, sshUsername, sshPassword)
connection.openShell()
while True:
connection.sendShell()
我希望那些不是您發佈在這裏的真實登錄憑證? – benten
@benten, 他們是一個關閉虛擬機測試路由器的登錄,但我刪除,以防萬一有人緊張:) – adrian
刪除'while while True:'。 –