How to Execute Shell Commands in a Remote Machine using Python – Paramiko
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 they key.
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:
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.
To install paramiko library, run the subsequent command in the command prompt. paramiko needs cryptography as a dependency module. So run both commands in 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:
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.
$ 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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course