Category Archives: Linux

Linux admins, bid farewell to bash

If you work as a Linux administrator, you’re likely accustomed to scripting in bash. However, it might be time to bid farewell to bash and embrace Python instead. Python offers a rich ecosystem of libraries, enabling you to accomplish numerous tasks with more concise code. For those new to Python, ‘W3Schools’ is an invaluable resource. Let me introduce you to four Python libraries that are particularly beneficial for system administrators.

ipaddress library, bundled with Python 3.6 and later, allows you to validate whether a variable holds an IP address. The following script continues looping until the user inputs an IP address. Please ensure to copy and paste the script as-is, as Python uses whitespace indentation to establish the scope of statements..

#!/usr/bin/env python3
#IP validation
import ipaddress 
while True:      
    try:
        IP = ipaddress.ip_address (input ("Enter Host IP:"))
    except ValueError:
        print ("Please enter a valid IP for the host.")
        continue
    else:
        break

To discover the classes and functions made available by the ‘ipaddress’ library, begin by importing the library and then use the ‘help’ and ‘dir’ commands.

[root@nycpytprod ~]# python3 
Python 3.6.8 (default, Aug 13 2020, 07:46:32)  
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import ipaddress 
>>> help(ipaddress) 
>>> dir(ipaddress) 
>>> quit (0)

netaddr library serves as a useful tool for validating netmasks. However, this library is not included with Python 3.6 by default. You can install it with the following command: ‘pip3.6 install netaddr’.

#!/usr/bin/env python3
# netmask validation
from netaddr import *
while True:
    MASK = IPAddress(input("Enter Network Mask:"))
    YESMASK = IPAddress(MASK).is_netmask()
    if YESMASK:
      break
    else:
      print ("Please enter a valid Network mask.")
      continue

validators library offers a range of valuable functions. ‘pip3.6 install validators’ to install it.

#!/usr/bin/env python3
# FQDN validation
import validators
while True:
    FQDN = input("Enter Host FQDN:")
    YESFQDN = validators.domain(FQDN)
    if YESFQDN:  
      break    
    else:
      print ("Please enter a valid FQDN for the hostname.")
      continue

Finally, the ‘subprocess’ library proves handy for executing shell commands. It’s important to focus on the ‘check_call’ function and observe how the arguments for the ‘scp’ command are passed.

#!/usr/bin/env python3
# Calling shell commands
# calling scp to transfer a file to the host nycpytprod.

import subprocess
try:
 #supress stdout, not stderr
 subprocess.check_call(["scp", "ks.cfg", "root@nycpytprod:/tmp"],stdout=subprocess.DEVNULL)
except subprocess.CalledProcessError as e:
 print ('returncode:', e.returncode)
 print ("Error encountered when copying ks.cfg file\n")
else:
 print ("File copied to host nycpytprod.")

# Another example for subprocess to long list files
subprocess.check_call(["ls", "-l"])

Given your experience in bash scripting, transitioning to Python should be a straightforward journey.