- How to Utilize Python for Basic Linux System Administration and Networking Tasks
- Content
- What Is Python?
- Installing Python on Linux
- Using the “os” Module
- Performing Networking Tasks Using the “socket” Module
- Using Paramiko for Logging in to an SSH Server and Running Commands
- Frequently Asked Questions
- 1. Do I need Python 3 to use these modules and libraries?
- 2. Do I need to install the “os” and “socket” modules?
- 3. Can I use Paramiko to log in to non-Unix systems?
- Introduction to Python for Linux System Administrators
- Scope of the article
- Introduction
- Setting up Python
- Installing Python on Ubuntu
How to Utilize Python for Basic Linux System Administration and Networking Tasks
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.
Content
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:
If Python is installed, the command will display the version of your Python configuration.
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 '' created successfully") #Prints the result, in case the directory already exists except FileExistsError: print(f"Directory '' already exists")
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 '' deleted successfully") #Prints the result, if the directory doesn't exist except FileNotFoundError: print(f"Directory '' doesn't exist")
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 '' was successfully renamed to ''") #Print the error message, if the directory or file doesn't exist except FileNotFoundError: print(f"Directory/File '' doesn't exist")
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 '' deleted successfully") #Prints the result, if the file doesn't exist except FileNotFoundError: print(f"File '' doesn't exist")
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")
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 '' doesn't exist")
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")
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: ") #Prints the hostname print(f"Hostname: ") #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: ") #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:
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.
Technical Writer — Linux & Cybersecurity.
Our latest tutorials delivered straight to your inbox
Introduction to Python for Linux System Administrators
Python is a high-level, interpreted programming language that is widely used in the world of Linux system administration. Python’s simplicity, readability, and easy-to-learn syntax make it an ideal choice for automation, scripting, and tool building in a Linux environment. It is also widely used for web development, scientific computing, and data analysis.
Python’s versatility and wide range of libraries and frameworks make it an invaluable tool for Linux system administrators who need to automate repetitive tasks, manage configurations, and monitor system performance.
In addition, Python’s community-driven development and extensive documentation make it easy for Linux system administrators to get help, find solutions, and collaborate with other Python users. With Python, Linux system administrators can streamline their work, increase efficiency, and gain deeper insights into their systems.
Scope of the article
- Overview of Python: Introduce the Python programming language, its features, and its advantages for system administration tasks.
- Setting up Python: Guide the reader through the installation of Python on a Linux system, including any dependencies or libraries that may be required.
- Basic Python syntax: Cover the basics of Python syntax, including data types, variables, operators, and control structures.
- Python libraries for system administration: Introduce the reader to popular Python libraries and modules for system administration tasks, such as paramiko, fabric, psutil, and pyyaml.
- Best practices for Python coding: Discuss coding best practices such as using virtual environments, code organization, error handling, and logging.
Introduction
Python is a high-level programming language that has gained widespread popularity among developers, data analysts, and system administrators due to its simplicity, readability, and versatility. As a Linux system administrator, learning Python can significantly enhance your productivity by automating routine tasks, analyzing system data, and creating custom scripts.
Python provides a vast array of frameworks that make it easy to work with various operating systems and system components, such as networking, databases, and web services. In this Introduction to Python for Linux System Administrators, we will cover the basics of Python programming, including syntax, data types, control structures, and functions.
We will also explore how to use Python for system administration tasks such as file management, process management, and system monitoring. Whether you are a beginner or an experienced Linux system administrator, this course will provide you with the essential knowledge and skills needed to start using Python effectively for your daily tasks.
Setting up Python
Setting up Python on a Linux system involves several steps, including installing the Python interpreter and any required dependencies or libraries. In this guide, we will walk you through the process of installing Python on a Linux system, specifically focusing on Ubuntu and CentOS distributions.
Installing Python on Ubuntu
sudo apt install python3 python3-pip