Open In App

How to Execute Shell Commands in a Remote Machine using Python – Paramiko

Improve
Improve
Like Article
Like
Save
Share
Report

Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model.

Authenticating SSH connection

To authenticate an SSH connection, we need to set up a private RSA SSH key (not to be confused with OpenSSH). We can generate a key using the following command:

$ ssh-keygen -t rsa

This will prompt us to provide a name for our key. Name it whatever you like and generate a public/private RSA key pair. Enter the name by which you wish to save the key.

i.e., /home/username/.ssh/id_rsa 

Next, you’ll be prompted to provide a password (feel free to leave this blank).

Now that we have our key, we need to copy this to our remote host. The easiest way to do this is by using ssh-copy-id:

$ ssh-copy-id -i ~/.ssh/mykey username@my_remote_host.org

If you’d like to check which keys you already have, these can be found in your system’s .ssh directory:

 ~/.sshCheck 

We’re looking for keys that begin with the following header:

—–BEGIN RSA PRIVATE KEY—–

—–END RSA PRIVATE KEY—–

SSH(Secure Shell) is an access credential that is used in the SSH Protocol. In other words, it is a cryptographic network protocol that is used for transferring encrypted data over the network. It allows you to connect to a server, or multiple servers, without having you remember or enter your password for each system that is to log in remotely from one system into another.

Installing Paramiko

To install paramiko library, run the subsequent command in the command prompt. paramiko needs cryptography as a dependency module. So run both commands in the command prompt :

pip install paramiko

pip install cryptography

Note: For more information, refer to Install Paramiko on Windows and Linux

After installation is completed, now we’ll hook up with a remote SSH server using paramiko library. Code snippet for an equivalent is given below:

Python3




import paramiko
 
# Create object of SSHClient and
# connecting to SSH
ssh = paramiko.SSHClient()
 
# Adding new host key to the local
# HostKeys object(in case of missing)
# AutoAddPolicy for missing host key to be set before connection setup.
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 
ssh.connect('1.1.1.2', port=22, username='UserName',
            password='PassWord', timeout=3)
 
# Execute command on SSH terminal
# using exec_command
stdin, stdout, stderr = ssh.exec_command('show ip interface brief')


Taking this as a base, one can automate the things of login to the remote SSH server, executing commands, and capturing the results, just using one python script.

By this, you can create an SSH connection to another host from within your application, with this connection you can send your commands to the host and retrieve the output. 

Given below is a program to depict the same. Here we are printing the username.

Program:

Python3




import paramiko
output_file = 'paramiko.org'
 
 
def paramiko_GKG(hostname, command):
    print('running')
    try:
        port = '22'
         
        # created client using paramiko
        client = paramiko.SSHClient()
         
        # here we are loading the system
        # host keys
        client.load_system_host_keys()
         
        # connecting paramiko using host
        # name and password
        client.connect(hostname, port=22, username='geeksForgeeks',
                       password='geeksForgeeks')
         
        # below line command will actually
        # execute in your remote machine
        (stdin, stdout, stderr) = client.exec_command(command)
         
        # redirecting all the output in cmd_output
        # variable
        cmd_output = stdout.read()
        print('log printing: ', command, cmd_output)
         
        # we are creating file which will read our
        # cmd_output and write it in output_file
        with open(output_file, "w+") as file:
            file.write(str(cmd_output))
             
        # we are returning the output
        return output_file
    finally:
        client.close()
 
 
paramiko_GKG('10.10.10.1', 'uname')


Output:

$ python GFG_paramiko.py
running
[log printing: ,'uname','Linux\n']

So by running our Python file we are getting out a printed statement with uname command and Linux as an output. The same program can be modified for different commands to get information as required.



Last Updated : 19 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads