Back to the main page

Script to remove client's dhcp reservation

Intro

This is python3.5 script to remove dhcp reservation of a client. It does quick check that script is not run on some of two 'special' hosts.
Assumptions:
1. Each client has its own reservation file, location is /etc/dhcp/clients/ directory.
2. The /etc/dhcp/dhcpd.conf has "include "/etc/dhcp/clients.include";" , hence this file needs to be also generated.

Script

#!/some-path/python3 """ The script to remove DHCP reservation """ import os import sys import socket import argparse import click import re import subprocess import platform from colorama import Fore, Back, Style import getpass from time import gmtime, strftime import datetime import logging, logging.handlers def not_whq_pls(): """ Check that script is not used on DHCP in WHQ and PLS. Colorama help Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Style: DIM, NORMAL, BRIGHT, RESET_ALL """ if socket.gethostname() == "hq-infra1.???.com" or socket.gethostname() == "pls-infra1.???.com": sys.exit(Back.RED + Fore.YELLOW + Style.BRIGHT + 'Error: this cannot be run on WHQ/PLS DHCP servers, please file request via our Bugzilla.' + Style.RESET_ALL) # Make sure this is not run on whq/pls dhcp servers. not_whq_pls() # define logging directory structure PROGRAM = os.path.basename(sys.argv[0]) # name of this script LOG_PATH = ("/var/log/" + PROGRAM) # put together "/var/log/" if not os.path.exists(LOG_PATH): # create LOG_PATH if doesn't exists os.makedirs(LOG_PATH) os.chown(LOG_PATH,-1,580) # root(-1 means no change):crm os.chmod(LOG_PATH,0o775) # drwxrwxr-x parser = argparse.ArgumentParser( description="Delete DHCP reservation (not for WHQ and PLS)") parser.add_argument("-s", "--system", help="System's name", required=True) args = parser.parse_args() system=args.system # --- Define logging LOG_FILE = (LOG_PATH + "/" + system + "_" + datetime.datetime.now().strftime("%m-%d-%Y_%Hh%Mm%Ss")) # create logger (interface that script uses for logging) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create file handler (define log destination) handler = logging.handlers.TimedRotatingFileHandler(LOG_FILE, when='MIDNIGHT', backupCount=100, utc=False) # create formatter (define layout of logs) formatter = logging.Formatter('%(asctime)s:%(levelname)s: %(message)s') handler.setFormatter(formatter) # add handler to logger logger.addHandler(handler) def who_run_script(): i_am=getpass.getuser() if i_am != "root": logger.debug(i_am + ", please run this via sudo, exiting") sys.exit(i_am + ", please run this via sudo, exiting") def dhcp_cfg_check(): """ Check DHCP cfg syntax, ol678 """ if re.match("6.*", platform.dist()[1]): logger.debug("Check DHCP config for OL6") return True if subprocess.call(['service', 'dhcpd', 'configtest']) == 0 else False else: logger.debug("Check DHCP config for OL[78]") return True if subprocess.call(['dhcpd', '-t']) == 0 else False def dhcp_restart(): """ Restart DHCP service, ol678 """ if re.match("6.*", platform.dist()[1]): logger.debug("OL6 DHCP service restart") return True if subprocess.call(['service', 'dhcpd', 'restart']) == 0 else False else: logger.debug("OL[78] DHCP service restart") return True if subprocess.call(['systemctl', 'restart', 'dhcpd']) == 0 else False def del_reservation(): path_system="/etc/dhcp/clients/" + system if os.path.exists(path_system): os.remove(path_system) logger.debug("Removed reservation for " + path_system) print("Removed reservation for " + path_system) else: logger.debug(path_system + " doesn't exist. Is another name used for reservation? ") sys.exit(path_system + " doesn't exist. Is another name used for reservation? ") def refresh_clients_include(): """ Refresh clients.include file """ CLNTDIR = "/etc/dhcp/clients/" if not os.path.exists(CLNTDIR): logger.debug("ERROR: " + CLNTDIR + " does not exist.") sys.exit("ERROR: " + CLNTDIR + " does not exist.") f = open("/etc/dhcp/clients.include", "w+") try: for root, dirs, files in os.walk(CLNTDIR): for clientname in files: f.write("include \"" + CLNTDIR + clientname + "\" ;\n") logger.debug("OK: Compiled new /etc/dhcp/clients.include") print("OK: Compiled new /etc/dhcp/clients.include") except: logger.debug("ERROR: cannot compile /etc/dhcp/clients.include") sys.exit("ERROR: cannot compile /etc/dhcp/clients.include") f.close() # ---- MAIN ----- if __name__ == '__main__': # start logging logger.debug("") logger.debug("Start at: " + strftime("%a, %d %b %Y %H:%M:%S", gmtime())) who_run_script() if click.confirm('Do you really want to remove reservation for %s?' % system): del_reservation() refresh_clients_include() dhcp_cfg_check() dhcp_restart() logger.debug("Finish at: " + strftime("%a, %d %b %Y %H:%M:%S", gmtime())) sys.exit(0)



Back to the main page