Automate your Linux life.
Since we’ve seen network automation methods in the last post of STEM with Python, this is the perfect opportunity to take a look at Linux command automation too. If you can code in the shell script, maybe you can automate them with Python as well.
In the last post of STEM with Python, we learned the very basics of network automation. So, this time, why don’t we learn about Linux command automation? Unlike the last one that experimented with a lot of methods, such as with/without logging the result-output into another file, this time, we’ll see a much simpler coding implementation.
The code:
So, this is the actual code that loops through the specified Linux commands and displays the result in the console. As we learned in the last section, maybe you can also apply the file open/read/write methods to this source code and make it more useful.
command_automation.py
import subprocess
# Define the commands to be run
commands = ["ls -l", "df -h", "uname -a"]
# Iterate through the commands
for command in commands:
# Run the command and capture the output
output = subprocess.run(command, shell=True, capture_output=True)
# Print the output
print(output.stdout.decode())
The executed result:
$python3 command_automation.py
total 12
-rw-rw-r-- 1 johnito users 383 Jan 14 16:58 cat.py
-rw-rw-r-- 1 johnito users 335 Jan 14 16:52 command_automation.py
-rw-rw-r-- 1 johnito users 1313 Jan 14 16:59 sample.txt
Filesystem Size Used Avail Use% Mounted on
udev 3.8G 0 3.8G 0% /dev
tmpfs 787M 6.7M 781M 1% /run
/dev/mapper/ubuntu--vg-ubuntu--lv 14G 13G 148M 99% /
tmpfs 3.9G 0 3.9G 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup
/dev/sdb1 98G 8.8M 93G 1% /shares/smb/seagate_hdd_100gb
/dev/loop0 64M 64M 0 100% /snap/core20/1738
/dev/loop1 64M 64M 0 100% /snap/core20/1778
/dev/loop2 92M 92M 0 100% /snap/lxd/24061
/dev/sda2 1.5G 205M 1.2G 15% /boot
/dev/loop3 92M 92M 0 100% /snap/lxd/23991
/dev/loop4 50M 50M 0 100% /snap/snapd/17883
/dev/sdc1 4.6T 184G 4.2T 5% /shares/smb/seagate_hdd_5tb
tmpfs 787M 0 787M 0% /run/user/1000
/dev/loop5 117M 117M 0 100% /snap/core/14399
/dev/loop6 116M 116M 0 100% /snap/kotlin/73
/dev/sdb2 98G 80K 93G 1% /home/johnito/seagate_hdd_100gb_home
/dev/sdb3 98G 32K 93G 1% /shares/smb/seagate_hdd_100gb_2
/dev/loop7 50M 50M 0 100% /snap/snapd/17950
/dev/loop8 117M 117M 0 100% /snap/core/14447
Linux skynewubuntuserver 5.4.0-135-generic #152-Ubuntu SMP Wed Nov 23 20:19:22 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
Afterthoughts:
Since Python3 is already installed in my environment (Ubuntu Server 20.04), the scripting language’s compatibility with Linux was simply amazing, and the OS-level unified compatibility is something that always makes me implement my ideas into the actual code even easier than other languages when it comes to coding on the Linux platforms.