How to Utilize Python for Basic Linux System Administration and Networking Tasks

Learn how to make good use of Python to better manage your Linux system..

How To Utilize Python For Basic Linux System Administration And Networking Tasks Featured Image

Python is a great programming language for automating system administration tasks on Linux systems. With its wide selection of different libraries, many of them can be used to improve the efficiency of various tasks. Using the examples below, you can easily run Linux system commands, work with files and directories, perform networking tasks and automate authentication processes in just a few seconds.

What Is Python?

Python can be best described as a general-purpose programming language. It was developed by a Dutch computer scientist named Guido van Rossum in the late 1980s and early 1990s to be a dynamically-typed programming language and successor to the “ABC” programming language.

Today it is widely considered to be one of the most popular programming languages in the world, with use-cases ranging from anything in web development to complex mathematics and scientific calculations. It is also appreciated for its elegant syntax and being relatively easy to learn.

Installing Python on Linux

Many Linux distributions already have Python installed by default. To check whether or not your system has Python 3 installed, you can run the python3 command with the --version flag:

python3 --version
Python3 Version Check

If Python is installed, the command will display the version of your Python configuration.

To install Python on Ubuntu and Debian systems:

sudo apt update && sudo apt upgrade -y
sudo apt install python3.10

Alternatively, Python can also be downloaded as a “.tgz” or “.xz” file.

Using the “os” Module

One of the best Python libraries for Linux system administrators is the “os” module. You can use it for the automation of many different kinds of tasks, such as handling directories and files. It can also run system commands.

As an example, you can utilize the module to create a new directory:

#Import the OS module
import os
 
#Name of the new directory
dir_name = "example"
 
try:
 
#Creates the new directory
    os.mkdir(dir_name)
 
#Prints the result, if the directory was successfully created
    print(f"Directory '{dir_name}' created successfully")
 
#Prints the result, in case the directory already exists
except FileExistsError:
    print(f"Directory '{dir_name}' already exists")
Python Os Module Create Directory 1

You can also delete a directory using the module:

#Import the OS module
import os
 
#Name of the directory to be deleted
dir_name = "example"
 
try:
 
#Deletes the directory
    os.rmdir(dir_name)
 
#Prints the result, if the directory was successfully deleted
    print(f"Directory '{dir_name}' deleted successfully")
 
#Prints the result, if the directory doesn't exist
except FileNotFoundError:
    print(f"Directory '{dir_name}' doesn't exist")
Python Os Module Delete Directory 1

You can rename files and directories:

#Import the OS module
import os
 
#Current name of the directory or file
current_name = "example"
 
new_name = "example2.0"
 
try:
 
#Renames the directory or file
    content = os.rename(current_name, new_name)
 
#Prints the contents of the directory
    print(f"Directory/File '{current_name}' was successfully renamed to '{new_name}'")
 
#Print the error message, if the directory or file doesn't exist
except FileNotFoundError:
    print(f"Directory/File '{current_name}' doesn't exist")
Python Os Module Rename Directory 1

Files are easily removable using the module:

#Import the OS module
import os
 
#Name of the file to be deleted
file_name = "example.txt"
 
try:
 
#Deletes the file
    os.remove(file_name)
 
#Prints the result, if the file was successfully deleted
    print(f"File '{file_name}' deleted successfully")
 
#Prints the result, if the file doesn't exist
except FileNotFoundError:
    print(f"File '{file_name}' doesn't exist")
Python Os Module Delete File 1

The current working directory is easily printable:

#Import the OS module
import os
 
try:
 
#Gets the current working directory
    cwd = os.getcwd()
 
#The name of the current working directory is printed out
    print(cwd)
 
#If an error occurs, it is printed out
except:
    print("An error occurred")
Python Os Module Print Current Working Directory 1

The contents of a directory, like files and subdirectories, can be checked easily:

#Import the OS module
import os
 
#Name of the directory
dir_name = "example"
 
try:
 
#Gets the contents of the directory
    content = os.listdir(dir_name)
 
#Prints the contents of the directory
    print(content)
 
#Prints the error, if the directory doesn't exist
except FileNotFoundError:
    print(f"Directory '{dir_name}' doesn't exist")
Python Os Module Check Contents 1

Use the module to print out the current user:

#Import the OS module
import os
 
try:
 
#Gets the name of the current user
    user = os.getlogin()
 
#Prints the name of the current user
    print(user)
 
#Prints an error message, in case it occurs
except:
    print("An error occurred")

Also run Linux shell commands using the module:

#Import the OS module
import os
 
#The shell command to run
command = "sudo apt update && sudo apt upgrade -y"
 
try:
 
#Runs the system command
    result = os.system(command)
 
#Prints the result of the command
    print(result)
 
#Prints an error message, in case an error occurs
except:
    print("An error occurred")
Python Os Module Run Shell Command

Performing Networking Tasks Using the “socket” Module

Python has a module that is built to perform different networking tasks and create complex networking-related utilities, like port scanners and video game servers. It is no surprise that the “socket” module can also be used to perform common and basic networking tasks on your system.

You can, for example, check your system’s IP address and hostname:

#Import the socket module
import socket
 
try:
 
#Getting the hostname
    host = socket.gethostname()
 
#Getting the IP address of the host
    ip = socket.gethostbyname(host)
 
#Prints the IP address
    print(f"IP address: {ip}")
 
#Prints the hostname
    print(f"Hostname: {host}")
 
#Prints an error message, if an error occurs
except:
    print("An error occurred")

You can also use the module to check the IP address of a website:

#Import the socket module
import socket
 
try:
 
#Domain to be checked
    domain = "duckduckgo.com"
 
#Getting the IP address of the domain
    ip = socket.gethostbyname(domain)
 
#Prints the IP address
    print(f"IP address: {ip}")
 
#Prints an error message, if an error occurs
except:
    print("An error occurred")

Using Paramiko for Logging in to an SSH Server and Running Commands

If you want to automate the process of logging in to an SSH server setup and running commands there, a “Paramiko” Python library will be extremely useful.

First download the library using Python’s pip3 package manager:

pip3 install paramiko
Python Paramiko Pip3 Install

Use the module to log in to an SSH server and run commands:

#Importing the Paramiko library
import paramiko
 
#Specifying the IP and credentials
ip = '127.0.0.1'
port = 22
user = 'example'
password = 'example'
 
command = "uname -a"
 
try:
 
#Initiating the Paramiko client
    ssh = paramiko.SSHClient()
 
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 
#Connecting to the SSH server
    ssh.connect(ip, port, user, password)
 
#Running a command on the system
    stdin, stdout, stderr = ssh.exec_command(command)
 
#Prints the result of the command
    print(stdout.read().decode())
 
#Prints an error message, in case an error occurs
except:
    print("An error occurred")

Frequently Asked Questions

1. Do I need Python 3 to use these modules and libraries?

While most of these libraries and modules do work with Python 2, there is a difference in syntax, and these code snippets won’t run. With some changes, you can adapt them to run in Python 2. However, Python 2 is outdated, so you should be using Python 3.

2. Do I need to install the “os” and “socket” modules?

Generally, no. Most installations of Python come with these modules straight out of the box.

3. Can I use Paramiko to log in to non-Unix systems?

According to the developer of Paramiko, at this time the library can’t be used to log in to non-Unix systems with SSH.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox