Open In App

Automated SSH bot in Python

Last Updated : 05 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how we can use Python to Automate some basic SSH processes.

What is SSH?

SSH stands for Secure Shell or Secure Socket Shell, in simple terms, it is a network communication protocol used to communicate between two computers and share data among them. The main feature of SSH is that the communication between two computers is encrypted meaning that it is safer and is recommended to use in insecure networks. SSH is mostly used to safely ‘login’ into remote computers but it can also be used to share data.

Prerequisite:

Users need to have Windows Subsystem for Linux (WSL) installed and set up on their devices. The steps and requirements are different for Windows 10 and Windows 11 users, so please keep that in Mind.

Steps to Install WSL/WSL 2 in Windows 10 and 11 :

To install WSL/WSL 2 in Windows follows this article: Setup OpenSSH server in Windows Subsystem for Linux (WSL) in windows.

Users need to follow the steps mentioned in the Article linked above to install WSL and set up a Local SSH server, otherwise, all the code below will NOT WORK. 

After installing and verifying that the SSH server is working fine they can continue to write the below code.

Required Modules:

First, we need to install a module named fabric.

Fabric is a Python library and command line tool for streamlining the use of SSh for application deployment or systems administration tasks.

Step 1:  Open cmd or PowerShell or any other terminal of user’s choice.

Step 2:  Write the below command there, and press enter.

pip install fabric

Step 3: (Optional): To check if the fabric has been installed properly or not, write the below command and press enter.

pip list

If it has been installed successfully user will see an output like this.

Automated SSH bot in Python

 

As the user can see, I have installed fabric successfully and it is showing in the list (has been highlighted for better understanding).

Configuring our Python Code with the SSH –

Step 1:  We will use two classes of fabric modules, Connection, and Config, so first let’s import them. We will also import the Python getpass module.

Python3




from fabric import Connection,Config
import getpass


Step 2:  Now in a variable we will store the root password entered by the user and pass it as a keyworded argument of the Config as a dictionary value, the key to that dictionary would be ‘sudo’.

Python3




password = getpass.getpass("Enter your root password: ")
configure = Config(overrides={'sudo' : {'password' : password}})


Step 3:  Now we need to have WSL installed and configured properly (Link given above). Now we need to get the IP address of the ssh server running in Ubuntu. So we will use the ifconfig command to fetch it and then store it in a variable in our code by passing it as an argument of the Connection function.

Python3




conn = Connection("<your_ip_address>",
                  user="<your username>",
                  config=configure)


here I have used a variable named ‘conn’, the user can use any name, but it doesn’t matter. To know the user’s IP Address user needs to use the ifconfig command on the Ubuntu terminal, then copy and paste it there. if the user gets any error with the ifconfig command like it is not available etc. then write the following command in the Ubuntu terminal –

sudo apt install net-tools

After that retry the ifconfig command and copy the IP address from the output and paste it on the above code..

We have now successfully eligible for establishing the connection with the remote SSH server using Python code.

Point to Remember : If the user runs the code more than once then every time please double check the IP address using the ifconfig command (in the Ubuntu terminal) if the IP address of the SSH server is wrong then this program will give an error.

Using some Linux Command – 

  • ls command: Using the ls command of Linux we can now list all the files and folders available. Write the below line in the Python code.

Python3




"""Type 1"""
conn.run("ls -la")
  
  
"""Type 2"""
result = conn.run("ls -la", hide=True)
print(result.stdout)


Here, as the user can see, I have used 2 types, both will return the same result though. Type 1 will just directly print all the list in the Terminal but in Type 2 as I have used hide = True it will not print everything like last time, rather than that it will store the value into the variable result and then we will simply use the print statement to see the output in the terminal.

Automated SSH bot in Python

 

  • pwd command: Using the pwd command to print the present working directory.

Python3




conn.run('pwd')


Automated SSH bot in Python

 

  • cd command: We can also change the directory, but for this one we will not use the run method. There is an inbuilt cd method in the Connection function we will use that with the with statement.

Python3




with conn.cd("/mnt/c/Users/Asus/Desktop"):
    conn.run("touch myfile.txt")
    conn.run("pwd")


Now first of all I am changing the Directory to the Desktop (The Real Desktop of my Laptop, not the home directory of Ubuntu). The by default path of the Desktop is ‘/mnt/c/Users/<user_name>/Desktop”, after reaching there, I am re-running the conn.run method with the touch command which creates a blank text file named myfile.txt and saves it on the Desktop, then I am running the pwd command again to re-assure I am in the proper directory (in this case, it is the Desktop).

Automated SSH bot in Python

 

user can see that for the last pwd command we got the Desktop directory as Output and if the user check user desktop user will see a file named myfile.txt will be created.

Installing some dependencies –

There is a built-in method inside the Connection class called sudo() which is used to run some commands as root without adding the ‘sudo’ in Infront of them using the run() method used earlier. One benefit of using sudo() is that if we don’t give the correct root password then every command written inside the sudo() will not work, but in the case of the run() it is not necessary.

Syntax:

conn.sudo(“<command>”)

As I have used the ‘conn’ variable to store the Connection function, I have written it above, the user will write the variable in place of conn in which the user has stored the Connection function.

Below are some Examples: 

Whenever we run the main Python file with .sudo() if we don’t provide the correct root password then this will not work.

Installing vim using sudo:

Python3




conn.sudo("apt install vim")


Installing Python using sudo: 

Python3




conn.sudo("apt install python3")


Updating the packages using sudo:

Python3




# or you can also write - apt-get update
conn.sudo("apt update")  


The below code is the Example of an Automation Process which is described below –

Using the below we code will Automate the following process –  

  1. Using Python we will connect to an SSH server and install packages like net-tools and python3.
  2. Then using the ifconfig command and Python’s re module we will fetch the IP address from the output of the ifconfig command. 
  3. change our directory to the real Desktop of our local machine and create a new folder inside which we will create 2 new text files.
  4. One of the new files will be a .txt file in which we will write something like ‘Hello World’ (but this process will be entirely done in the Ubuntu terminal using Ubuntu commands like echo passed in our main Python Code).
  5. The other file will be another text file in which we will store the fetched ip_address from previous steps and show that into the Ubuntu terminal.  

Python3




from fabric import Connection, Config
import getpass
import re
password = getpass.getpass("Enter your root password: ")
configure = Config(overrides={'sudo': {'password': password}})
conn = Connection("<your_ip_address>",
                  user="<your_Ubuntu_user_name>", config=configure)
  
# Installing latest version of Python in terminal
conn.sudo("apt install python3")
  
result = conn.run("ifconfig")
lines = result.stdout.split("\n")
inet_lines = [l for l in lines if "inet" in l and "127.0.0.1" not in l]
  
span = re.search("inet ([0-9)]+\.){3}[0-9]+", inet_lines[0]).span()
ip_address = inet_lines[0][span[0]+5:span[1]]
  
  
desktop_path = "/mnt/c/Users/<your_user_name>/Desktop"
  
with conn.cd(desktop_path):
    conn.run("mkdir test_folder")
  
    with conn.cd(desktop_path+"/test_folder"):
        conn.run('echo "Hello World From inside\
        the Ubuntu Terminal" > hello.txt')
        conn.run("cat hello.txt")
        conn.run(f'echo "Your IP Address is : {ip_address}" > ip.txt')
        conn.run("cat ip.txt")


If the user has successfully run the code and it gave the expected output then before running it a second time please delete the test_folder or whatever folder name they might provide after the mkdir command as if the folder is already available at that location mkdir will throw an error and code will stop right there.

Output:

In this video, the user can see the code in action and how the folders getting made and inside that folder, the files are made and get written inside it.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads