Automated SSH bot in Python
Last Updated :
26 Apr, 2025
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.
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.
- pwd command: Using the pwd command to print the present working directory.
Python3
- 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).
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 -
- Using Python we will connect to an SSH server and install packages like net-tools and python3.
- Then using the ifconfig command and Python's re module we will fetch the IP address from the output of the ifconfig command.
- 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.
- 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).
- 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.
Similar Reads
How to Automate an Excel Sheet in Python?
Before you read this article and learn automation in Python, let's watch a video of Christian Genco (a talented programmer and an entrepreneur) explaining the importance of coding by taking the example of automation.You might have laughed loudly after watching this video, and you surely might have u
8 min read
Getting started with Python for Automated Trading
Automated Trading is the terminology given to trade entries and exits that are processed and executed via a computer. Automated trading has certain advantages: Minimizes human intervention: Automated trading systems eliminate emotions during trading. Traders usually have an easier time sticking to t
3 min read
Automating some git commands with Python
Git is a powerful version control system that developers widely use to manage their code. However, managing Git repositories can be a tedious task, especially when working with multiple branches and commits. Fortunately, Git's command-line interface can be automated using Python, making it easier to
3 min read
Dominos Chatbot using Python
Chatbots are gaining popularity as a means for businesses to interact with their customers. Domino's Pizza is one such company that has used a chatbot to improve its customer service. In this article, we'll look at how to use Python to create a chatbot for Domino's Pizza. Tools and Technologies Used
11 min read
How To Embed Python Code In Batch Script
Embedding Python code in a batch script can be very helpful for automating tasks that require both shell commands and Python scripting. In this article, we will discuss how to embed Python code within a batch script. What are Batch Scripts and Python Code?Batch scripts are text files containing a se
4 min read
Automate Instagram Messages using Python
In this article, we will see how to send a single message to any number of people. We just have to provide a list of users. We will use selenium for this task. Packages neededSelenium: It is an open-source tool that automates web browsers. It provides a single interface that lets you write test scri
6 min read
Chat Bot in Python with ChatterBot Module
Nobody likes to be alone always, but sometimes loneliness could be a better medicine to hunch the thirst for a peaceful environment. Even during such lonely quarantines, we may ignore humans but not humanoids. Yes, if you have guessed this article for a chatbot, then you have cracked it right. We wo
3 min read
Best Python Modules for Automation
Automation is an addition of technology that performs tasks with reduced human assistance to processes that facilitate feedback loops between operations and development teams so that iterative updates can be deployed faster to applications in production. There are different types of automation libra
3 min read
Cloud Computing with Python
Cloud services offer on-demand computing resources, making applications more scalable, cost-effective and accessible from anywhere.Python has become one of the most popular programming languages for cloud computing due to its simplicity, flexibility and vast ecosystem of libraries. Whether youâre de
5 min read
Facebook Login using Python
Python scripting is one of the most intriguing and fascinating things to do meanwhile learning Python. Automation and controlling the browser is one of them. In this particular article, we will see how to log in to the Facebook account using Python and the power of selenium. Selenium automates and c
4 min read