Execute shell command on remote Linux machine using python

Hi All,

Recently i started learn python, very beginner level, have to say as a person who use Powershell more than 8-9 years, python definitely impressive!
Thereby, i want to show off little bit 🙂 and would like to share with you a great way to run shell on Remote Linux machine using python, indeed, it’s going to be very simple command…

I am using on PyCharm for my demonstration;
https://www.jetbrains.com/pycharm/download/

I will use on “paramiko” module, therefore, in order to import the module you can use on

import paramiko

First of all, add machine’s details which are: host name, user, password – make sure port 22 is opened.( we will check it as well)

hostname = "10.10.10.10"
username = "root"
password = "root@@##$$"

then we have to specify what command do we want to run on this machine:

commands = [
    "pwd",
    "uname -a",
    "df -h"
]

we are going to check the connection using the following code, if no we will print:” Cannot connect to the SSH Server”.

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    client.connect(hostname=hostname, username=username, password=password)
except:
    print("[!] Cannot connect to the SSH Server")
    exit()

Then we can execute the command using the following code:

# execute the commands
for command in commands:
    print("="*50, command, "="*50)
    stdin, stdout, stderr = client.exec_command(command)
    print(stdout.read().decode())
    err = stderr.read().decode()
    if err:
        print(err)

Results:

Code:

import paramiko

hostname = "10.10.10.10"
username = "root"
password = "root@@##$$"

commands = [
    "pwd",
    "uname -a",
    "df -h"
]

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    client.connect(hostname=hostname, username=username, password=password)
except:
    print("[!] Cannot connect to the SSH Server")
    exit()

# execute the commands
for command in commands:
    print("="*50, command, "="*50)
    stdin, stdout, stderr = client.exec_command(command)
    print(stdout.read().decode())
    err = stderr.read().decode()
    if err:
        print(err)