Skip to content

Instantly share code, notes, and snippets.

@dorianim
Created April 28, 2021 10:38
Show Gist options
  • Save dorianim/c056bb9017aad98c5274b7e379136787 to your computer and use it in GitHub Desktop.
Save dorianim/c056bb9017aad98c5274b7e379136787 to your computer and use it in GitHub Desktop.
lmn7GetAllUptimes.py
#!/usr/bin/python3
import subprocess
import os
import xml.etree.ElementTree as ET
import csv
from datetime import datetime, timedelta
def listWorkstations(school):
"""
Generate a dict with workstations and parameters out of devices file
:return: Dict with all linbo informations for all workstations.
:rtype: dict
"""
if school == "default-school":
workstations_file = '/etc/linuxmuster/sophomorix/' + school + '/devices.csv'
else:
workstations_file = '/etc/linuxmuster/sophomorix/' + school + '/' + school + 'devices.csv'
LINBO_PATH = '/srv/linbo'
workstations = {}
with open(workstations_file, 'r') as w:
buffer = csv.reader(w, delimiter=";")
for row in buffer:
# Not a comment
if row[0][0] != "#":
# If config file exists
if os.path.isfile(os.path.join(LINBO_PATH, 'start.conf.'+row[2])):
room = row[0]
group = row[2]
host = row[1]
mac = row[3]
ip = row[4]
pxe = row[10]
if pxe != "1" and pxe != "2":
continue
if group not in workstations.keys():
workstations[group] = {'grp': group, 'hosts': []}
workstations[group]["hosts"].append({'host' : host, 'room' : room, 'mac' : mac, 'ip' : ip})
return workstations
def checkHostOnlineAndOs(host):
nmapOutput = subprocess.check_output(["nmap", "-p", "2222,22,135", host, "-oX", "-"])
#print(nmapOutput)
xmlRoot = ET.fromstring(nmapOutput)
openPorts = []
try:
hostElement = xmlRoot.findall("host")[0]
portsElement = hostElement.findall("ports")[0]
scannedPorts = portsElement.findall("port")
except:
return False, None
for scannedPort in scannedPorts:
portNumber = scannedPort.attrib["portid"]
portState = scannedPort.findall("state")[0].attrib["state"]
if portState == "open":
openPorts.append(portNumber)
if len(openPorts) == 0:
return False, None
elif len(openPorts) > 1:
return True, None
if openPorts[0] == "22":
return True, "linux"
elif openPorts[0] == "135":
return True, "windows"
elif openPorts[0] == "2222":
return True, "linbo"
else:
return True, None
def ldapTodatetime(ldap: float):
return datetime(1601, 1, 1) + timedelta(seconds=ldap/10000000) + timedelta(hours=2)
def checkHostUptime(host):
ldbSearchOutput = subprocess.check_output(["ldbsearch", "--url=/var/lib/samba/private/sam.ldb", "(&(sAMAccountName={}$))".format(host.upper()), "lastLogon"])
lastLogonTimestamp = None
for line in ldbSearchOutput.decode("utf-8").split("\n"):
if "lastLogon" in line:
tmpArray = line.split(":")
if len(tmpArray) == 2:
lastLogonTimestamp = tmpArray[1].strip()
continue
if lastLogonTimestamp != None:
lastLogonTimestamp = ldapTodatetime(float(lastLogonTimestamp))
uptime = datetime.now() - lastLogonTimestamp
return True, uptime
return False, None
workstations = listWorkstations("default-school")
try:
for group in workstations:
print()
print("---", workstations[group]["grp"], "---")
for host in workstations[group]["hosts"]:
hostname = host["host"]
up, os = checkHostOnlineAndOs(hostname)
rc, uptime = checkHostUptime(hostname)
if not up:
print(hostname, "is down")
elif not rc or os == "linbo":
print(hostname, "is up with", os)
else:
print(hostname, "is up with", os, "since", uptime)
except KeyboardInterrupt:
print("cancelled")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment