Python Ssh


Python, Paramiko SSH, and Network Devices (2014-01-23) By Kirk Byers. You have been learning Python—but as a network engineer what can you do with it? In this article, I will show you how to use Paramiko SSH (a Python SSH library) to connect to and gather information from a router. Raspberry pi officially comes with “Python” as a major programming language. It comes with python IDE which is known as “IDLE3”. Well we are talking about programming over SSH, so forget about it. For writing a program in Raspberry pi or in any other system you first need an editor. Welcome to Paramiko!¶ Paramiko is a Python (2.7, 3.4+) implementation of the SSHv2 protocol, providing both client and server functionality.While it leverages a Python C extension for low level cryptography (Cryptography), Paramiko itself is a pure Python interface around SSH networking concepts.

If you have ever agonized over connecting and communicating with a remote machine in python, give Paramiko a go. Paramiko is most helpful for cases where one needs to securely communicate and exchange data, execute commands on remote machines, handle connect requests from remove machines or access ssh services like sftp. As described in the paramiko’s homepage

MyCommand = 'ssh', '-t', hostname1, myCommandStr myCommandStr = ' '.join(pipes.quote(n) for n in myCommand)'ssh', '-t', hostname2, myCommandStr) Because we aren't redirecting stdin or stdout, they should still be pointed at the terminal from which your Python program was started, so SSH should be able to execute its password prompts directly. SSH sessions are repeated for ‘x’ number of times. Paramiko SSH module is used in this script. Paramiko is a native Python implementation of SSH. This module can be installed on a linux system using pip. Commands are: #sudo apt-get install python-pip #sudo pip install paramiko Code.

“Paramiko is a module for python 2.2 (or higher) that implements the SSH2 protocol for secure (encrypted and authenticated) connections to remote machines.”

Paramiko: Dependencies & Installation

The version I’m using is 1.7.5. paramiko is written purely in python and the only dependency for it is pycrypto 1.9+.
I installed using easy_install

On ubuntu, paramiko can be installed by

The rpm equivalent is also available.

Another option is to download the source code/module from the parent site and install using ‘

To use paramiko effectively, We will need to understand the basics of ssh.

SSH and Security

SSH, or Secure SHell, as a network protocol provides mechanism for authenticated and encrypted connections between remote machines over unsecure network. Before ssh was employed, telnet and rcp protocols exchanged authentication information as plaintext over unsecure network, while establishing the connection.  SSH solved this by using encrypted communication even while establishing the connection, effectively replacing other network protocols.

SSH provides

  • Encryption of all communication between the two entities with a several cipher algorithms to choose from
  • Authentication using password or a public key or using both options as a two-factor authentication
  • Ensuing integrity of data is by creating a digital signature of the data transferred from one entity to another. There are multiple message authentication algorithms to choose from the signature creation.

Connecting Using Paramiko

Paramiko supports both password based authentication and public key based authentication. Paramiko’s API facilitate both high level and low level control over the ssh connection.

The simplest and probably the easiest way to connect to a remote machine using Paramiko is the SSHClient object. It is a high-level representation of a session with an SSH server. This class incorporates Transport, Channel, and SFTPClient to provide simpler authentication and connection apis.

The ssh server will be verified by the host keys loaded from the user’s local ssh’s known_hosts file. In case of failure to verify, the default policy is to reject the server’s keys and raise an SSHException. Here I’m overriding it with the AutoAddPolicy wherein the new server will be automatically added to the list of known hosts. Its also possible to define our own policies on how to handle unidentified servers.

Authentication of the client is attempted in the following order of priority:

  • The pkey or key_filename passed in (if any)
  • Any key we can find through an SSH agent
  • Any “id_rsa” or “id_dsa” key discoverable in ~/.ssh/
  • Plain username/password auth, if a password was given

Using Paramiko’s SSHClient

In the below example I’m using the password to authenticate.

The ‘connect’ method also allows you to provide your own private key, or connect to the SSH agent on the local machine or read from the user’s local key files. Click here for a more detailed description of the ‘connect‘ method’s signature.




The Transport Object


It provides more direct control over how the connections are formed and authentication is carried over. It provides for various options such as logging debugging information like hex dump, manipulating the algorithms used and their priorities, controlling the authentication methods and their sequence, the type of channels to open, forcing renegotiating keys etc. It is also possible to start an SSH Server or SFTP Server using this object.

The below example uses the Transport Object to connect:

import os
import paramiko
server, port, username, password = (‘host’, 22, ‘username’, ‘password’)
nbytes = 100

An SSH Transport attaches to a stream (usually a socket), negotiates an encrypted session, authenticates, and then creates stream tunnels, called Channels, across the session. Multiple channels can be multiplexed across a single session (and often are, in the case of port forwardings).

Next, after authentication, we create a channel of type “session”

We need to wait till the command is executed or the channel is closed. recv_exit_status return the result of the exit status of the command executed or -1 if no exit status was given.

Now the command execution is over and stdout and stderr streams will be linked to the channel and can be read.

We can also create SFTP client from the Transport Object as below

SFTP client object. SFTPClient is used to open an sftp session across an open ssh Transport and do remote file operations.

Personally I prefer to write a wrapper module over the SSHClient api and use that in my day to day needs.


Python Ssh Connection

Paramiko’s SFTPClient is significantly slower compared to sftp or scp, some times by an order of magnitude, especially for huge files. The scp implementation listed in the ‘Interesting Read’ below assures to be faster though I’ve not tested it yet.

Python Ssh Api

Paramiko’s SSHClient does not allow for setting a timeout for exec_command. This means that, in case of the remote_machine not returning the exec_command call, the process would freeze and need to be killed.

Python Ssh-add

Interesting Read