Python and SSH: Paramiko shell

In my previous article about Paramiko I promised a follow-up tutorial about Paramiko. A lot of people have requested it, so here it finally is! In this article I’m going to show you how to set up a shell-like connection over SSH with Paramiko and Python 3.

For more information about Paramiko, read the previous article here.
For more blog posts regarding Python, have a look at this page.

Before you get started, make sure that you’ve installed the necessary packages. For instructions on how to install Paramiko, have a look at the Paramiko installation page. To download Python 3, have a look at the Python download page.

When you’ve installed both Python and Paramiko, create a new Python file and import the paramiko module. We’re also going to use multi-threading, so import threading as well. To quickly exit the application when exit is typed, import sys too.

The next step would be to create a ssh class we can use later on to set up connections.

The code is pretty self-explanatory. The __init__ method is used when creating a new instance of the ssh class. The closeConnection method is used to close the ssh connection, self-explanatory huh?

The openShell method, on the other hand, should be used to invoke the ssh shell with the host and credentials defined on initialization. Lastly the method sendShell should be used to send a command to the shell.

As you’ve probably already noticed, the process method will output the results from the commands to our local terminal window. The process method will run constantly (hence  while True ) in a separate thread to retrieve the output. This is not an ideal approach for every type of output data, or for extremely reliable connections, but it easily shows how the paramiko shell can be used.

The output checking thread is started with the following three lines. Which you can find in the __init__ method inside the ssh class we just defined.

The only thing left is to open the connection and start sending commands to our ssh server. To do so, add the following lines. Make sure to replace “SSH USERNAME”, “SSH PASSWORD” and “SSH SERVER ADDRESS” with your own credentials and server address for the device you want to connect to.

The final code:



  1. Pingback: Python and SSH: sending commands over SSH using Paramiko | Daan Lenaerts

  2. Hi,

    Thank you for this code. Can you please add this implementation:

    “To quickly exit the application when exit is typed, import sys too.”


  3. Hi,
    Do you mention password as a text? isnt that security threat. what if i want to send encrypted password to function? how is that possible?

Leave a Reply

Your email address will not be published. Required fields are marked *

Protected with IP Blacklist CloudIP Blacklist Cloud