Python and SSH: sending commands over SSH using Paramiko

SSH is a remote connection tool commonly used in the Unix world. Wit SSH many things can be achieved, but one of the most important, and most common, use cases for SSH is communicating with a remote server shell from your local system. That’s what SSH stands for, secure shell. SSH is encrypted by default, and not difficult to use. Those two make that SSH is widely accepted and used. Mostly for server management.

Python, on the other hand, is an extremely versatile, yet powerful high level programming language which is perfectly suited for server-side applications. So let’s combine the two and create a Python script that can communicate with a remote server over SSH.

In this tutorial I’m only going to cover the basics. Which means connecting to a system over SSH, sending a command and retrieving the result. In following tutorials I’m going to cover more advanced things, like an interactive shell, as well.

Read the next tutorial, Python and SSH: Paramiko shell, here.

First make sure that you have installed Paramiko. You can read more about the installation process here. It’s fairly straight-forward, on OS X and Linux at least.

When you’ve installed Paramiko, create a new python file and import client from Paramiko.

To make everything more modular, create a new class, called ssh and initialize a variables called client with None.

Then create an initialization function inside the class we just created.

The following function should be placed inside the ssh class as well. This function will be used to send commands to the remote machine, after a connection in made.

The class should look like this:

You can open a new connection with the following command. Replace the values between, and including, the < and > symbols.

You can send a command like this. Replace <COMMAND> with the actual command you want to send.

Keep in mind that the channel that’s used will get closed after you run a command, so multiple commands are executed as if you run them in a different “shell“. You might have to send multiple commands at once. For example

will create a folder called “testfolder” in your home folder, instead in the “~/folder” directory. If you want to create a new directory inside “~/folder” you have to use the following code.

In the next tutorial about Paramiko I’m going to show you how you can manage the connection and channels yourself, so you can run multiple commands without having to send them all at once. Like having a real shell connection.

Read the next tutorial, Python and SSH: Paramiko shell, here.

 

 

17 Comments

  1. I enjoyed the article. I am looking forward to the next installment. May I have the link?

    From the article: “In the next tutorial about Paramiko I’m going to show you how you can manage the connection and channels yourself, so you can run multiple commands without having to send them all at once.”

    1. Hi Wayne, glad to hear you enjoyed the article.

      I’ve been very busy lately, I’ve yet to write the next tutorial about Paramiko. So I won’t be able to give you a link.
      I already wrote some code for this though, so if you’re interested you can send me an email (me@daanlenaerts.com) then I’ll send some sample code your way.

      1. Hi Daan,

        Can you please help me in managing the connection and channels yourself, so you can run multiple commands without having to send them all at once.

        or provide me the link of your next tutorials as you mention in the last para in this tutorials.

        As I am trying to automate test suite using python paramiko

        Regards
        Vikrant

          1. I am trying to use this for a network switch which prompts only for password (a headless authentication) anyway i can get this working? Please let me know

  2. I am trying to leverage your code to connect to an avaya switch. It requires a ctrl+y(which i believe is ‘\x19’) to get
    an interactive prompt, but I cannot send that command with self,client.exec_command(‘\x19’). could you point me
    in the right direction?

    import paramiko
    from paramiko import client

    class ssh:
    client = None

    def __init__(self, address, username, password):
    print("Connecting to server.")
    self.client = client.SSHClient()
    self.client.set_missing_host_key_policy(client.AutoAddPolicy())
    self.client.connect(address, username=username, password=password, look_for_keys=False)
    stdin, stdout, stderr = self.client.exec_command('\x19')
    #self.client.exec_command('\x19')

    def sendCommand(self, command):
    if(self.client):
    stdin, stdout, stderr = self.client.exec_command(command)
    while not stdout.channel.exit_status_ready():
    # Print data when available
    if stdout.channel.recv_ready():
    alldata = stdout.channel.recv(1024)
    prevdata = b"1"
    while prevdata:
    prevdata = stdout.channel.recv(1024)
    alldata += prevdata

    print(str(alldata, "utf8"))
    else:
    print("Connection not opened.")

      1. Hi,
        I had the same requirement. I have to send the ctrl+C character to a linux server that i have connected through paramiko in python. Can you tell me how to do this?

  3. Pingback: Python and SSH: Paramiko shell | Daan Lenaerts

  4. Thank you – this was amazingly helpful. I needed to use Paramiko for a project, and I simply could not get it to execute multiple commands at once until I found your code.

  5. Hi Daan ,

    Thanks for sharing your knowledge !!! really great job …

    With the above code , I am bale to connect to remote server and able to create/execute commands .

    But I want to copy files from my local systems to remote server .

    Could you please help me with the code by including in above code .

    Thanks,
    Your Friend ….

  6. when using it to access (remote) windows machine I got this message:

    message: Unable to execute command or shell on remote system: Failed to Execute
    process. after this command:

    cddir=conn.sendCommand(‘cd /temp/scriptFolder && mkdir folder2)

    the cd /temp/scriptFolder exists and have full access.

    here it is the log (debug mode) before this message:
    ……
    2018-01-12 13:17:23,267:INFO:Authentication (password) successful!
    2018-01-12 13:17:23,267:DEBUG:[chan 0] Max packet in: 32768 bytes
    2018-01-12 13:17:23,267:DEBUG:[chan 0] Max packet out: 98304 bytes
    2018-01-12 13:17:23,268:DEBUG:Secsh channel 0 opened.
    2018-01-12 13:17:23,268:DEBUG:[chan 0] Sesch channel 0 request ok
    2018-01-12 13:17:23,295:DEBUG:[chan 0] EOF sent (0)
    2018-01-12 13:17:23,296:DEBUG:Ignoring message for dead channel 0
    2018-01-12 13:17:23,296:DEBUG:Ignoring message for dead channel 0
    2018-01-12 13:17:23,299:DEBUG:EOF in transport thread

    Any ideas?

    thanks

Leave a Reply

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

Protected with IP Blacklist CloudIP Blacklist Cloud