In the world of Linux automation, Python plays a crucial role. One of the most powerful tools Python provides is the subprocess module. This module allows you to run system commands, capture their output, and even integrate them into automation scripts. In fact, the subprocess module for Linux automation is widely used by system administrators and DevOps engineers because it makes automation both reliable and efficient.
In this blog, we will explore 10 maximum practical subprocess module examples for Linux automation. Each example is explained in simple terms, ensuring that you can apply them directly in real-world scenarios.
All should be in python script.
1. Run a Simple Linux Command
This command lists files in the current directory. As a result, automation scripts can easily verify file structures.
import subprocess
subprocess.run(["ls", "-l"])
2. Capture Command Output
By using check_output, you can capture system information. Therefore, administrators can log details automatically.
With this method, real-time monitoring is possible. This proves useful in automated health checks.
process = subprocess.Popen(["ping", "-c", "4", "google.com"], stdout=subprocess.PIPE)
for line in process.stdout:
print(line.decode().strip())print(output.decode())
8. Execute Commands with Environment Variables
Setting environment variables ensures that automation scripts remain flexible.
This demonstrates how multiple commands can be automated seamlessly. Therefore, repetitive tasks become effortless.
commands = [["mkdir", "backup"], ["cp", "-r", "/etc", "backup/"]]
for cmd in commands:
subprocess.run(cmd)
10. Run Shell Commands Directly
This demonstrates how multiple commands can be automated seamlessly. Therefore, repetitive tasks become effortless.
subprocess.run("echo Hello Linux Automation", shell=True)
Conclusion
The subprocess module for Linux automation is not just powerful, but also highly practical. With these 10 subprocess examples, you can run commands, capture results, handle errors, and even automate complex workflows. Moreover, by combining multiple subprocess techniques, your Linux automation scripts will become more efficient and reliable.
If you are working as a system administrator or DevOps professional, mastering the subprocess module will definitely make your automation tasks smoother.