def disk(): # Devuelve histórico de información del disco de las últimas 24 horas. auth.check_apikey() out = str(os.popen('sar -d').read()).split('\n') c = 0 newout = {} time = "" for i in range(len(out) - 2): d = {} out[i] = ' '.join(out[i].split()) if len(out[i].split()) == 10: d["time"] = out[i].split()[0] d["tps"] = out[i].split()[2].replace( ',', '.') # Transferencias por segundo. d["read"] = out[i].split()[3].replace( ',', '.') # Lecturas de 512 bytes. d["write"] = out[i].split()[4].replace( ',', '.') # Escrituras de 512 bytes. d["used"] = out[i].split()[9].replace( ',', '.') # Porcentaje de discos usado. if (d["tps"] != "tps") and (d["time"] != "Average:"): if time == d["time"]: c -= 1 d["tps"] = float(d["tps"]) + float(newout[c]["tps"]) d["read"] = float(d["read"]) + float(newout[c]["read"]) d["write"] = float(d["write"]) + float(newout[c]["write"]) d["used"] = float(d["used"]) + float(newout[c]["used"]) time = d["time"] newout[c] = d c += 1 return json.dumps(newout, ensure_ascii=False)
def service(service, command): auth.check_apikey() output = str( os.popen('sudo service ' + str(service) + ' ' + str(command)).read()).replace('\n', '<br />') return output
def temperature(): # Usando el paquete lm-sensors, esta llamada devuelve una media de dos sensores del equipo. auth.check_apikey() out = os.popen('sensors | grep \"temp1\" | cut -d \"+\" -f2').read() t1 = float(out.split('\n')[0].split('°C')[0]) t2 = float(out.split('\n')[1].split('°C')[0]) return str(float((t1 + t2) / 2))
def ssh(): # Esta petición permite pasar como argumento POST una cadena el cual será interpretado por BASH # y la salida del comando es devuelto en el propio cuerpo de la respuesta. auth.check_apikey() data = request.body.read() result = json.loads(data) output = str(os.popen(result['cmd']).read()).replace('\n', '<br>') return output
def netAVG(): auth.check_apikey() out = str( os.popen( 'sar -n DEV 1 1 | grep "$(ip -o link show | awk \'{print $2,$9}\' | grep "UP" | head -n1 | cut -d ":" -f1)" | tail -n1' ).read()).rstrip().split() newout = {} newout["rx"] = out[4].replace(',', '.') newout["tx"] = out[5].replace(',', '.') return json.dumps(newout, ensure_ascii=False)
def clients(): """ Obtener la lista de dispositivos conectados al punto de acceso WiFi. Se realiza una intersección de MAC entre los servicios de dnsmasq y hostapd, de este modo conseguimos además la dirección IP asignada y el nombre del dispositivo. """ auth.check_apikey() cmd = "echo \"$(journalctl -eu dnsmasq | grep \"$(sudo hostapd_cli all_sta | grep dot11RSNAStatsSTAAddress | cut -d \"=\" -f2 | cut -d \" \" -f1)\" | grep DHCPACK | cut -c62-)\" > /tmp/ap-clients" os.system(cmd) output = str(os.popen("awk '!a[$0]++' /tmp/ap-clients").read()).strip().split('\n') return json.dumps(output)
def diskSize(): # Información acerca de la ocupación del disco principal del sistema operativo. auth.check_apikey() out = {} df = os.popen('df -k "/" | tail -n1 | xargs').read().split() out['folder'] = df[0] # Directorio principal usado por el sistema. out['blocks'] = df[1] # Número total de bloques de tamaño 1KB. out['used'] = df[2] # Bloques usados. out['avail'] = df[3] # Bloques disponibles. out['use'] = df[4] # % Usado. out['mount'] = df[5] # Directorio de montaje. return json.dumps(out, ensure_ascii=False)
def mem(): auth.check_apikey() out = str(os.popen('sar -r').read()).split('\n') c = 0 newout = {} for i in range(len(out) - 2): d = {} out[i] = ' '.join(out[i].split()) if len(out[i].split()) == 11: d["time"] = out[i].split()[0] d["free"] = out[i].split()[1] d["used"] = out[i].split()[2] if (d["free"] != "kbmemfree") and (d["time"] != "Average:"): newout[c] = d c += 1 return json.dumps(newout, ensure_ascii=False)
def log(): # Llamada que permite conocer la lista de últimos intentos, fallidos o aceptados, # a la llamada principal /api/login. auth.check_apikey() a = os.popen('cat ' + temp + '/access.log | tail -10').read().rstrip().split('\n') newout = {} c = 0 for i in a: out = {} out["time"] = i.split()[0] out["ip"] = i.split()[1] out["check"] = i.split()[2] newout[c] = out c += 1 return json.dumps(newout, ensure_ascii=False)
def list(): auth.check_apikey() out = str(os.popen( 'sudo systemctl -r --type service --all').read()).strip().split('\n') c = 0 newout = {} for i in range(1, len(out) - 9): d = {} t = 0 if out[i].split()[0] == "\xe2\x97\x8f": t = 1 d["name"] = out[i].split()[0 + t] d["status"] = out[i].split()[3 + t] newout[c] = d c += 1 return json.dumps(newout, ensure_ascii=False)
def cpu(): auth.check_apikey() out = str(os.popen('sar -u').read()).split('\n') c = 0 newout = {} for i in range(len(out) - 2): d = {} out[i] = ' '.join(out[i].split()) if len(out[i].split()) == 8: d["time"] = out[i].split()[0] d["user"] = out[i].split()[2].replace(',', '.') d["nice"] = out[i].split()[3].replace(',', '.') d["system"] = out[i].split()[4].replace(',', '.') d["iowait"] = out[i].split()[5].replace(',', '.') d["steal"] = out[i].split()[6].replace(',', '.') d["idle"] = out[i].split()[7].replace(',', '.') if (d["idle"] != "%idle") and (d["time"] != "Average:"): newout[c] = d c += 1 return json.dumps(newout, ensure_ascii=False)
def status(): # Llamada encargada de devolver un resumen de información del propio equipo. auth.check_apikey() out = {} out["host"] = os.popen( 'hostnamectl | grep \"Static hostname\"').read().rstrip().split()[-1] out["so"] = os.popen('hostnamectl | grep \"Operating System\"').read( ).rstrip().split(':')[-1] out["kernel"] = os.popen( 'hostnamectl | grep \"Kernel\"').read().rstrip().split(':')[-1] out["arch"] = os.popen( 'hostnamectl | grep \"Architecture\"').read().rstrip().split(':')[-1] out["ramGb"] = round( float( os.popen('grep MemTotal /proc/meminfo').read().rstrip().split(':') [1].split()[0]) / 1024 / 1024 * 100) / 100 out["model"] = os.popen( 'lscpu | grep \"Model name\"').read().rstrip().split(':')[1].strip() out["numCPU"] = os.popen('lscpu | grep \"CPU(s)\"').read().split( '\n')[0].split(':')[1].strip() out["mhzCPU"] = os.popen('lscpu | grep \"CPU MHz\"').read().split()[-1] out["uptime"] = os.popen( "awk '{print int($1/3600)\"h \"int(($1%3600)/60)\"m \"int($1%60)\"s\"}' /proc/uptime" ).read().rstrip() out["cuCPU"] = round( float( os.popen( 'grep \'cpu \' /proc/stat | awk \'{usage=($2+$4)*100/($2+$4+$5)} END {print usage}\'' ).read().rstrip()) * 100) / 100 mem = os.popen('free -m | grep Mem').read().split() out["cuMEM"] = round(float(mem[2]) / float(mem[1]) * 10000) / 100 load = os.popen('cat /proc/loadavg').read() newout = {} newout[0] = load.split()[0] newout[1] = load.split()[1] newout[2] = load.split()[2] out["loadAVG"] = newout return json.dumps(out, ensure_ascii=False)
def update(): # Trata de realizar una actualización del servicio ‘smanagement’ auth.check_apikey() raise HTTPResponse(status=202) #git pull REPOSITORIO restart()
def restart(): # Reinicia el propio servicio ‘smanagement’ auth.check_apikey() os.system('$(sleep 1; sudo service smanagement restart &)') raise HTTPResponse(status=202)
def firewall(): # Usando la utilidad de iptables del equipo, devuelve la lista de reglas actualmente aplicadas en el sistema. auth.check_apikey() return os.popen('sudo iptables -L').read().replace('\n', '<br>')