How to Execute Shell Commands in a Remote Machine in Python

Learning how you can execute shell commands and scripts on a remote machine in Python using paramiko library.
Abdou Rockikz · 4 min read · Updated feb 2020 · General Python Topics

Have you ever wanted to quickly execute certain commands in your Linux machine in a remote manner ? or you want to routinely execute some lines of code in your server to automate stuff ? In this tutorial, you will learn how you can write a simple Python script to remotely execute shell commands in your Linux machine.

RELATEDHow to Brute-Force SSH Servers in Python.

We will be using paramiko library, let's install it:

pip3 install paramiko

Defining some connection credentials:

import paramiko

hostname = ""
username = "test"
password = "abc123"

In the above code, I've defined the hostname, username and password, this is my local Linux box, you need to edit these variables for your case, or you may want to make command line argument parsing using argparse module as we usually do in such tasks.

Note that, it isn't safe to connect to SSH using credentials like that, you can configure your SSH listener daemon to only accept public authentication key, instead of using a password. However, for demonstration purposes, we will be using a password.

Executing Shell Commands

Now let's create a list of commands you wish to execute on that remote machine:

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

In this case, just simple commands that outputs some useful information about the operating system.

The below code is responsible for initiating the SSH client and connecting to the server:

# initialize the SSH client
client = paramiko.SSHClient()
# add to known hosts
    client.connect(hostname=hostname, username=username, password=password)
    print("[!] Cannot connect to the SSH Server")

Now let's iterate over commands we just defined and execute them one by one:

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

Here is my results:

================================================== pwd ==================================================

================================================== id ==================================================
uid=1000(test) gid=0(root) groups=0(root),27(sudo)

================================================== uname -a ==================================================
Linux rockikz 4.17.0-kali1-amd64 #1 SMP Debian 4.17.8-1kali1 (2018-07-24) x86_64 GNU/Linux

================================================== df -h ==================================================
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           392M  6.2M  386M   2% /run
/dev/sda1       452G  410G   19G  96% /
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
tmpfs           392M   12K  392M   1% /run/user/131
tmpfs           392M     0  392M   0% /run/user/1000

Awesome, these commands were successfully executed on my Linux machine  !

Executing Scripts

Now that you know how you can execute commands one by one, let's dive a little bit deeper and execute entire shell (.sh) scripts.

Consider this script (named ""):

cd Desktop
mkdir test_folder
cd test_folder
echo "$PATH" > path.txt

After the SSH connection, instead of iterating for commands, now we read the content of this script and execute it:

# read the BASH script content from the file
bash_script = open("").read()
# execute the BASH script
stdin, stdout, stderr = client.exec_command(bash_script)
# read the standard output and print it
# print errors if there are any
err =
if err:
# close the connection

exec_command() method executes the script using the default shell (BASH, SH, or any other) and returns standard input, standard output and standard error respectively, we will read from stdout and stderr if there are any, and then we close the SSH connection.

After the execution of the above code, a new file test_folder was created in Desktop and got a text file inside that contain the global $PATH variable:

Results after executing the Script in Python


As you can see, this is useful for many scenarios, for example, you may want to manage your servers only with executing Python scripts remotely, you can do anything you want ! Let us know what you did with this in the comments below ! 

And by the way, If you want to run more complex jobs on a remote server you might want to look into Ansible instead.

You can also use Fabric library as it is a high level Python library designed just to execute shell commands remotely over SSH, it builds on top of Invoke and Paramiko.

Feel free to edit the code as you wish, for example, you may want to parse command line arguments with argparse.

READ ALSOHow to Create a Reverse Shell in Python.

Happy Coding ♥

View Full Code
Sharing is caring!

Read Also

Comment panel

Comment system is still in Beta, if you find any bug, please consider contacting us here.