Python - PARAMIKO SSH关闭会话

时间:2016-09-20 14:36:32

标签: python paramiko

我的sendShell对象通过list commandfactory []后,我需要帮助终止我的SSH会话。

我有一个python脚本,我使用paramiko通过ssh连接到cisco lab路由器;在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"中的所有命令后终止。列表已经运行(CODE BELOW)。

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提供了一个很好的博客。我确实做了自己的改变以满足我的需求。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

能够通过在迭代器之后添加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()