Python PARAMIKO SSH关闭会话

2024-09-28 22:34:00 发布

您现在位置:Python中文网/ 问答频道 /正文

在sendShell对象运行完list commandfactory[]之后,我需要帮助来终止SSH会话。

我有一个python脚本,使用paramiko通过ssh连接到cisco实验室路由器;在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/。非常感谢Daan Lenaerts的一个好博客。我确实根据自己的需要做了一些改变。


Tags: toselfreclientnoneyousendparamiko
2条回答

使用self.transport.close()结束sendShell函数,请参见http://docs.paramiko.org/en/2.0/api/transport.html

通过在迭代器之后添加self.shell.transport.close()可以解决这个问题。

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()

相关问题 更多 >