server automation

python 2 days, 12 hours ago
import re import subprocess import sys import shutil import time if len(sys.argv) != 2: print('Please pass the servername\nEx: python compare_connections.py <SITE>') exit(1) width = shutil.get_terminal_size((70, 30)).columns if width < 120: input("Please maximize the terminal window for better display and Enter:") dest = sys.argv[1] def get_console_out(command, shell=False): result = subprocess.run(command, shell=shell, stdout=subprocess.PIPE) lines = result.stdout.decode('utf-8').split("\n") return lines hostname = get_console_out("hostname", shell=True)[0] server_no = (int(hostname[-3:])-1)*2 sources = { 'idrac': {'dest': f'{dest}401to1', 'dest_itf': 'GigabitEthernet0/0/0/0'}, 'eno3': {'dest': f'{dest}401to1', 'dest_itf': f'GigabitEthernet0/0/0/{int(hostname[-3:])+5}'}, 'enp94s0f0': {'dest': f'{dest}401to1', 'dest_itf': f'TenGigE0/0/0/{server_no+12}'}, 'enp216s0f0': {'dest': f'{dest}402to1', 'dest_itf': f'TenGigE0/0/0/{server_no+12}'}, 'enp94s0f1': {'dest': f'{dest}401to1', 'dest_itf': f'TenGigE0/0/0/{server_no+13}'}, 'enp216s0f1': {'dest': f'{dest}402to1', 'dest_itf': f'TenGigE0/0/0/{server_no+13}'}, } RED = "\033[31m" GREEN = "\033[32m" YELLOW = "\033[33m" RESET = "\033[0m" def print_headers(): print(f"{'#':<5} {'Check':<25} {'Expected':<40} {'Installed':<40} {'Result':<10}") print("-" * 120) counter = 0 def print_row(ch, ex, ins, res): global counter counter += 1 print(f"{counter:<5} {ch:<25} {ex:<40} {ins:<40} {res:<10}") print('\n') print('-'*120) print("Hardware Validations") print_headers() cpu_lines = get_console_out(["racadm", "get", "BIOS.ProcSettings"]) for line in cpu_lines: if "NumCores" in line: cpu_cores = int(line.split('=')[1]) if cpu_cores > 22: print_row("CPU Cores", "Min 22", cpu_cores, YELLOW + "WARNING" + RESET) elif cpu_cores == 22: print_row("CPU Cores", "Min 22", cpu_cores, GREEN + "PASSED" + RESET) else: print_row("CPU Cores", "Min 22", cpu_cores, RED + "FAILED" + RESET) # if re.findall('Proc[0-9]+Brand', line): # print(line) memory_lines = get_console_out(["racadm", "get", "BIOS.MemSettings"]) for line in memory_lines: if "SysMemSize" in line: if "384 GB" not in line: print_row("Memory", "384GB", line, RED + "FAILED" + RESET) else: print_row("Memory", "384GB", "384 GB", GREEN + "PASSED" + RESET) slots = get_console_out(["racadm", "get", "NIC.NICConfig"]) valid_slots = ["NIC.Slot.3-1-1", "NIC.Slot.3-2-1", "NIC.Slot.8-1-1", "NIC.Slot.8-2-1"] slots_present = [] for line in slots: if "Slot" in line: slots_present.append(re.findall("NIC\.Slot\.[0-9]+-[0-9]+-[0-9]+", line)[0]) nn = 1 for slot in valid_slots: if slot not in slots_present: print_row("NIC Slot", slot, "Not Present", RED + "FAILED" + RESET) else: print_row("NIC Slot", slot, slot, GREEN + "PASSED" + RESET) nn += 1 ''' card_out = get_console_out("/usr/bin/lshw -businfo | /bin/grep 5e:00.0 |/usr/bin/awk '{print $4}'|/bin/sed 's/^ *//g'", shell=True) if card_out and card_out[0].strip() in ["MT28800", "MT28841"]: print_row("Correct Card", "MT28800 / MT28841", card_out[0].strip(), GREEN + "PASSED" + RESET) else: print_row("Correct Card", "MT28800 / MT28841", card_out[0].strip(), RED + "FAILED" + RESET) ''' dim_lines = get_console_out("dmidecode -t 17", shell=True) dims = [] cur_dim = None for dim_line in dim_lines: cur_line = dim_line.strip() if "Handle" in cur_line and "DMI type" in cur_line: cur_dim = [cur_line] if "Size" in cur_line and "No Module Installed" not in cur_line: cur_dim.append(cur_line) elif "Size" in cur_line and "No Module Installed" in cur_line: cur_dim = None if cur_dim and "Locator" in cur_line: cur_dim.append(cur_line) dims.append(cur_dim) cur_dim = None if len(dims) == 12: print_row("DIM Slots Count", 12, 12, GREEN + "PASSED" + RESET) else: print_row("DIM Slots Count", 12, len(dims), RED + "FAILED" + RESET) for dim in dims: if "32 GB" not in dim[1]: print_row("DIM Memory", "32 GB", dim[1].replace("Size:", "").strip(), RED + 'FAILED' + RESET) # print_row("DIM Memory", "32 GB", dim[0].split(",")[0]+" "+dim[1], RED + 'FAILED' + RESET) else: print_row("DIM Memory", "32 GB", dim[1].replace("Size:", "").strip(), GREEN + 'PASSED' + RESET) raid_slot = get_console_out(["racadm", "storage", "get", "controllers"], shell=False) if "RAID.Slot.6-1" in raid_slot[0]: print_row("RAID Slot", "RAID.Slot.6-1", "RAID.Slot.6-1", GREEN + "PASSED" + RESET) else: print_row("RAID Slot", "RAID.Slot.6-1", re.findall("RAID\.Slot\.[0-9]+\-[0-9]+", raid_slot[0])[0], RED + "FAILED" + RESET) hw_disks = get_console_out("/bin/racadm storage get pdisks|grep Disk|wc -l", shell=True) if hw_disks[0].strip() in ["4", "16"]: print_row("HW Disk Count", "4 or 16", hw_disks[0].strip(), GREEN + "PASSED" + RESET) else: print_row("HW Disk Count", "4 or 16", hw_disks[0].strip(), RED + "FAILED" + RESET) counter = 0 print('\n') print('-'*120) print("Software Validations") print_headers() BIOS_firmware = get_console_out("/bin/racadm getversion -f bios|sed -n 1p|awk -F= '{print $2}'|/bin/sed 's/^ *//g'", shell=True) BIOS_firmware = [i for i in BIOS_firmware if i and i.strip()!=""] if BIOS_firmware and BIOS_firmware[0].strip() == "2.21.2": print_row("BIOS firmware", "2.21.2", "2.21.2", GREEN + "PASSED" + RESET) else: print_row("BIOS firmware", "2.21.2", BIOS_firmware[0], RED + "FAILED" + RESET) iDRAC_firmware = get_console_out(["/bin/racadm getversion -f lc |sed -n 1p|awk -F= '{print $2}'|/bin/sed 's/^ *//g'"], shell=True) if iDRAC_firmware and iDRAC_firmware[0].strip() == "7.00.00.172": print_row("iDRAC firmware", "7.00.00.172", "7.00.00.172", GREEN + "PASSED" + RESET) else: print_row("iDRAC firmware", "7.00.00.172", iDRAC_firmware[0], RED + "FAILED" + RESET) RAID_controller_firmware = get_console_out(["/bin/racadm storage get controllers:RAID.Slot.6-1|/bin/grep -i Firmware|/usr/bin/awk -F= '{print $2}'|/bin/sed 's/^[ \t]*//;s/[ \t]*$//'"], shell=True) if RAID_controller_firmware and RAID_controller_firmware[0].strip() == "25.5.9.0001": print_row("RAID controller firmware", "25.5.9.0001", "25.5.9.0001", GREEN + "PASSED" + RESET) else: print_row("RAID controller firmware", "25.5.9.0001", RAID_controller_firmware[0], RED + "FAILED" + RESET) CPLD_firmware = get_console_out(["/bin/racadm getversion -c|sed -n 1p|awk -F= '{print $2}'|/bin/sed 's/^ *//g'"], shell=True) if CPLD_firmware and CPLD_firmware[0].strip() == "1.1.4": print_row("CPLD firmware", "1.1.4", "1.1.4", GREEN + "PASSED" + RESET) else: print_row("CPLD firmware", "1.1.4", CPLD_firmware[0], RED + "FAILED" + RESET) nics_order = ['eno1', 'eno2', 'eno3', 'eno4', 'enp94s0f0', 'enp94s0f1', 'enp216s0f0', 'enp216s0f1'] for i in range(1,9): cmd_out = get_console_out("/bin/racadm get NIC.FrmwImgMenu."+str(i)+"|sed -n 3p|awk -F= '{print $2}'", shell=True) if cmd_out and i<9: if cmd_out[0].strip() == "22.5.7": print_row(nics_order[i-1], "22.5.7", "22.5.7", GREEN + "PASSED" + RESET) else: print_row(nics_order[i-1], "22.5.7", cmd_out[0], RED + "FAILED" + RESET) counter = 0 print('\n') print('-'*120) print('Connectivity Validations') print_headers() def compare_server(sources): interfaces = sources compared = {} lines = get_console_out(['lldpcli', 'show', 'neighbors']) for line in lines: line1 = line.strip() if "Interface" in line1: cur_if = line1.replace("Interface:", "").split(",")[0].strip() compared[cur_if] = [] if "SysName:" in line1: cur_dest = re.findall(".*40[1-2]+to1", line1.replace("SysName:", "").strip().lower()) if cur_dest: interfaces[cur_if]['cur_dest'] = cur_dest[0] if "PortID" in line1: cur_itf_lst = re.findall(f'{interfaces[cur_if]["dest_itf"][0:-2]}[0-9]+', line1) cur_itf = cur_itf_lst[0] if cur_itf_lst else '-' interfaces[cur_if]['cur_itf'] = cur_itf if interfaces[cur_if]["dest_itf"] in cur_itf and interfaces[cur_if]['cur_dest'] == interfaces[cur_if]['dest'].lower(): interfaces[cur_if]['result'] = GREEN + "PASSED" + RESET else: interfaces[cur_if]['result'] = RED + "FAILED" + RESET return compared compare_server(sources) for intf, rec in sources.items(): cur_val = f"{rec.get('cur_dest', '')}:{rec.get('cur_itf', '')}" if cur_val.strip() == ":": cur_val = "" print_row(f"Conn: {intf}", f"{rec['dest']}:{rec['dest_itf']}", cur_val, rec.get('result', RED +'FAILED'+ RESET)) print('\n')
32
Posted By
Python Script to create AWS beanstalk
#!/usr/bin/python
  
import boto
python aws beanstalk
sandeep sandeep
List all files and folders using python os mo
import os

def list_files_folders(path):
python python-os
kishore_kumar
Get current environment variables in python
import os
env = os.environ

python python-os
kishore_kumar
Get os details using python os
import os
print os.uname()
# Don't use os.system('uname -a'), its j
python python-os
kishore_kumar
Get stats ( lines, words, char count ) of fil
def file_stats(path):
    f = open(path, 'r')
    lines = f.readlines()
python
kishore_kumar
Use map function in python
def get_double(num):
    return num * 2

python
kishore_kumar
Python sample codes for beginners
print "Welcome to python"
python
gaya38 gaya38
Python program for even number checking
a=input("Enter a value:")
if (a%2==0):
    print "The given number is even numb
python
gaya38 gaya38
Python program for prime number check
a=input("Enter a value:")
k=0
b=(a/2)+1
python
gaya38 gaya38
Pass command line arguments in python
import sys
x=len(sys.argv)
a=[]
python
gaya38 gaya38
Python program for the largest number in an a
a = [1,43,98,5]#Dummy data
for l in range(len(a)-1):
        if (a[l]>a[l+1]):
python
gaya38 gaya38
print list of even numbers within a range
n=100
a=[10,20,30,40,50]
b=[60,70,80,90]
python
gaya38 gaya38
generate fibonacci series in python
n=input("Enter the constraint to print n
m=input("Enter the maximum value to prin
a=0
python
gaya38 gaya38
Generate Random number within the range in py
import random
print random.uniform(10,500)
python
gaya38 gaya38
Shuffle list elements in python
import random;
z = [1,90,4,2]
z = random.shuffle(z)
python
gaya38 gaya38
use python requests to get contents of url (
import requests

req = requests.get("https://httpbin.org/
python python-requests
kishore_kumar
how to iterate or get values in python dictio
sample_dict = { "number": 1, "fruits": [

for key in sample_dict:
python
kishore_kumar
create matrix and multiply using numpy in pyt
import numpy as np

matrix = [[1,2,3], [4,5,6], [7,8,9]]
python numpy
kishore_kumar
generate random numbers matrix with numpy pyt
import numpy as np

random_arr = np.random.randint(1,50,9)
python numpy
kishore_kumar
Find min , max and mean for numpy arrays
import numpy as np

random_arr = np.random.randint(1,50,9)
python numpy
kishore_kumar