Python Script for SSH into Remote Server

Python Script for SSH into Remote Server. Before we jump into our python script. Lets recap that – SSH is a network protocol and is used to manage a device or servers through remote access. SSH uses public key encryption for security purposes. The important difference between Telnet and SSH is that SSH uses encryption, which means that all data transmitted over a network is protected from unauthorized real-time interception.

Here, I am two Centos 7 machines. One having the IP address of, on which I am going to create python script for ssh into remote server. The other machine (remote server) is having an IP address of

python script for ssh into remote server

In a production environment, you will have ssh key based authentication configured. So the remote machine will not ask for any password. In case its not there, you have to manually supply the password. Use your favorite editor like vim or notepad++ (notepadplusplus) for creating the python script.

python script for ssh into remote server

Once the script is ready you can simply run it using python.

python script for ssh into remote server

In the previous python script first, we imported the subprocess module, then we defined the host address where you want to establish the SSH connection. After that, we gave one simple command that executed over the remote device. After all this was set up, we put this information in the subprocess.Popen() function.

This function executed the arguments defined inside that function to create a connection with the remote device. After the SSH connection was established, our defined command was executed and provided the result. Then we printed the result of SSH on the Terminal, as shown in the output.