【问题标题】:Python - PARAMIKO SSH close sessionPython - PARAAMIKO SSH 关闭会话
【发布时间】:2017-01-28 13:09:56
【问题描述】:

在我的 sendShell 对象通过列表 commandfactory[] 运行后,我需要帮助终止我的 SSH 会话。

我有一个 Python 脚本,我使用 paramiko 通过 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()

 

我希望在我的commandfactory 列表中的所有命令都运行后终止 SSH 会话(代码如下)。

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 的精彩博客。我确实根据自己的需要进行了更改。

【问题讨论】:

    标签: python ssh paramiko


    【解决方案1】:

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

    【讨论】:

    • VB,天哪,它一直在我面前。我知道使用self.transport.close(),但我不知道在哪里,直到我看到你的回复;出于某种奇怪的原因,这就是帮助我弄清楚的原因。为了得到我想要的,我把 transport.close() 放在我的 commandfactory 迭代器之后。现在,如果我可能会问,一旦我关闭会话,你会建议我做什么来打破循环并结束我的 python 脚本?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 2014-09-24
      • 2016-04-04
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多