Python - PARAMIKO SSH close session
<p>I need help terminating my SSH session after my sendShell object runs through list commandfactory[].</p>

<p>I have a python script where I use paramiko to connect to a cisco lab router via ssh; execute 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.</p>

<pre><code>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()
</code></pre>

<p>I would like the SSH session terminate once all the commands in my "commandfactory" list has been ran (CODE BELOW).</p>

<pre><code>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")
</code></pre>

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

<p>End the sendShell function with self.transport.close(), see <a href="http://docs.paramiko.org/en/2.0/api/transport.html" rel="nofollow">http://docs.paramiko.org/en/2.0/api/transport.html</a></p>

python networking ssh cisco