Learning Python Network Programming

(Sean Pound) #1

Interacting with Remote Systems


Secure shell – access using Python


SSH has become a very popular network protocol for performing secure data
communication between two computers. It provides an excellent cryptographic
support, so that unrelated third-parties cannot see the content of the data during
the transmission process. Details of the SSH protocol can be found in these RFC
documents: RFC4251-RFC4254, available at http://www.rfc-editor.org/rfc/
rfc4251.txt.


Python's paramiko library provides a very good support for the SSH-based network
communication. You can use Python scripts to benefit from the advantages of
SSH-based remote administration, such as the remote command-line login,
command execution, and the other secure network services between two networked
computers. You may also be interested in using the pysftp module, which is
based on paramiko. More details regarding this package can be found at PyPI:
https://pypi.python.org/pypi/pysftp/.


The SSH is a client/server protocol. Both of the parties use the SSH key pairs to
encrypt the communication. Each key pair has one private and one public key. The
public key can be published to anyone who may be interested in that. The private
key is always kept private and secure from everyone except the owner of the key.


The SSH public and private keys can be generated and digitally signed by an external
or an internal certificate authority. But that brings a lot of overhead to a small
organization. So, alternatively, the keys can be generated randomly by utility tools,
such as ssh-keygen. The public key needs to be available to all participating parties.
When the SSH client connects to the server for the first time, it registers the public
key of the server on a special file called ~/.ssh/known_hosts file. So, the subsequent
connection to the server ensures that the client is talking to the same server as it spoke
to before. On the server side, if you would like to restrict access to certain clients who
have certain IP addresses, then the public keys of the permitted hosts can be stored
to another special file called ssh_known_hosts file. Of course, if you re-build the
machines, such as the server machine, then the old public key of the server won't
match with that of the one stored in the ~/.ssh/known_hosts file. So, the SSH client
will raise an exception and prevent you from connecting to it. You can delete the old
key from that file and then try to re-connect, as if for the first time.


We can use the paramiko module to create an SSH client and then connect it to the
SSH server. This module will supply the SSHClient() class.


ssh_client = paramiko.SSHClient()
Free download pdf