Establishing an SSH connection with paramiko

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 it. The private key is kept private from everyone except the owner of the key.

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.

You can use the SSHClient class to create an SSH client with the paramiko module:

ssh_client = paramiko.SSHClient()

By default, the instance of this client class will reject the unknown host keys. So, you can set up a policy to accept the unknown host keys. The built-in AutoAddPolicy() class will add the host keys as and when they are discovered. 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 need to restrict accepting connections only to specific hosts, you can use the load_system_host_keys() method to add the system host keys and system fingerprints:

ssh_client.load_system_host_keys()

Before executing a command on our server via ssh, we need to create an object of the SSHClient type, which will be responsible for sending all our requests to the server and handling the responses that are returned. You can wrap this code in a function called get_connection(), as follows:

import paramiko

def get_connection():
# start SSH client
ssh = paramiko.SSHClient()
# We add the list of known hosts
ssh.load_system_host_keys()
#If it does not find the host, it automatically adds it
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# need to use the domain name resolved through DNS query
ssh.connect('domain', username='user', password='password')
return ssh
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset