adrian
adrian

Reputation: 17

Python - PARAMIKO SSH close session

I need help terminating my SSH session after my sendShell object runs through list commandfactory[].

I have a Python script where I use paramiko to connect to a cisco lab router via ssh; execute all commands in commandfactory[]; and output the results to the standard out. Everything seems to work except, I can't seem to get the SSH session to close after all my commands are ran. The session simply stays open until I terminate my script.

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

 

I would like the SSH session terminate once all the commands in my commandfactory list has been ran (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")

My code was mainly taken from https://daanlenaerts.com/blog/2016/07/01/python-and-ssh-paramiko-shell/. Much thanks to Daan Lenaerts for a good blog. I did make my own changes to fit my needs.

Upvotes: 0

Views: 11460

Answers (2)

adrian
adrian

Reputation: 17

Was able to solve by adding self.shell.transport.close() after my iterator.

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

Upvotes: 0

Lasse  VB
Lasse VB

Reputation: 129

End the sendShell function with self.transport.close(), see http://docs.paramiko.org/en/2.0/api/transport.html

Upvotes: 2

Related Questions