10 Subprocess Module Examples for Linux Automation

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.

output = subprocess.check_output(["uname", "-a"])
print(output.decode())

3. Handle Errors Gracefully

This ensures that failed commands are handled smoothly, which is essential in Linux automation tasks.

try:
    subprocess.run(["wrongcommand"], check=True)
except subprocess.CalledProcessError:
    print("Command failed!")

4. Redirect Output to a File

Automation scripts often need reports. Consequently, this approach stores command results directly into files.

with open("disk_usage.txt", "w") as f:
    subprocess.run(["df", "-h"], stdout=f)

5. Run a Command with Input

By passing input, Linux automation scripts can mimic interactive processes.

subprocess.run(["grep", "root"], input=b"root:x:0:0:root:/root:/bin/bash\n", text=True)

6. Use Pipes Between Commands

With pipes, complex automation workflows become possible. As a result, tasks like process filtering are easier.

ps = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE)
grep = subprocess.Popen(["grep", "python"], stdin=ps.stdout, stdout=subprocess.PIPE)
output = grep.communicate()[0]

7. Monitor Long-Running Processes

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.

import os
env = os.environ.copy()
env["MY_VAR"] = "LinuxAutomation"
subprocess.run(["printenv", "MY_VAR"], env=env)

9. Execute Commands with Environment Variables

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.

Leave a Reply

Your email address will not be published. Required fields are marked *