Learning Python Network Programming

(Sean Pound) #1
Chapter 5

By default, the instance of this client class will reject the unknown host keys.
So, you can set up a policy for accepting the unknown host keys. The built-in
AutoAddPolicy() class will add the host keys as and when they are discovered.
Now, you need to run the set_missing_host_key_policy() method along with
the following argument on the ssh_client object.


ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

If, you want to restrict connecting only to certain hosts, then you can define your
own policy and replace it with the AutoAddPolicy() class.


You may also be interested in adding the system host keys by using the
load_system_host_keys() method.


ssh_client.load_system_host_keys()

So far, we have discussed how to encrypt the connection. However, SSH needs your
authentication credentials. This means that the client needs to prove to the server
that a specific user is talking, not someone else. This can be done in a few ways. The
simplest way is by using the username and the password combination. Another
popular way is by using the key-based authentication method. This means that the
user's public key can be copied to the server. There's a specific tool for doing that.
This comes with the later versions of the SSH. Here's an example of how to use
ssh-copy-id.


ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]


This command will copy the SSH public key of the faruq user to a machine,
debian6box.localdomain.loc:


Here, we can simply call the connect() method along with the target hostname
and the SSH login credentials. To run any command on the target host, we need to
invoke the exec_command() method by passing the command as its argument.


ssh_client.connect(hostname, port, username, password)
stdin, stdout, stderr = ssh_client.exec_command(cmd)

The following code listing shows how to do SSH login to a target host and then run a
simple ls command:


#!/usr/bin/env python3

import getpass
import paramiko
Free download pdf