Мне нужна помощь, завершающая мой сеанс SSH после того, как объект sendShell проходит через список commandfactory [].Python - PARAMIKO SSH close session
У меня есть сценарий python, где я использую paramiko для подключения к маршрутизатору лаборатории cisco через ssh; выполнять команды в commandfactory []; и выводит результаты на стандарт. Кажется, все работает, но я не могу заставить SSH-сессию закрыться после того, как все мои команды запущены. Сеанс просто остается открытым до тех пор, пока я не закончу свой сценарий.
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.send("\n")
else:
print("Shell not opened.")
def process(self):
global connection
while True:
# 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 = str(alldata, "utf8")
strdata.strip()
print(strdata, end = "")
sshUsername = "adrian"
sshPassword = "ilovebeer"
sshServer = "10.10.254.129"
connection = ssh(sshServer, sshUsername, sshPassword)
connection.openShell()
while True:
connection.sendShell()
Я хотел бы, SSH сессии прекратить, как только все команды в моем списке «commandfactory» был побежал (КОД НИЖЕ).
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.send("\n")
Мой код в основном взято из https://daanlenaerts.com/blog/2016/07/01/python-and-ssh-paramiko-shell/. Огромное спасибо Даану Ленерсу за хороший блог. Я сделал свои изменения, чтобы соответствовать моим потребностям.
VB, OMG, это было перед моим лицом все время. Я знал, что использую self.transport.close(), но я не знал, где, пока не увижу ваш ответ; и по какой-то странной причине это помогло мне разобраться. Чтобы получить то, что я хотел, я ставлю transport.close() после моего итератора commandfactory. Теперь, если я могу спросить, что бы вы предложили мне сделать, чтобы разбить мои циклы и закончить мой скрипт python после закрытия сеанса? – adrian