mirror of
https://gitlab.sectorq.eu/jaydee/python.git
synced 2025-12-13 18:24:53 +01:00
911 lines
38 KiB
Python
911 lines
38 KiB
Python
#!/usr/bin/env python3
|
|
|
|
from asyncio.log import logger
|
|
import paho.mqtt.client as mqtt
|
|
from getmac import get_mac_address
|
|
import platform
|
|
import socket
|
|
import re
|
|
import subprocess
|
|
import os
|
|
import json
|
|
import sys
|
|
import time
|
|
import json
|
|
import datetime
|
|
import ctypes
|
|
import getopt
|
|
import random
|
|
import requests
|
|
|
|
stats = {}
|
|
VERSION = "1.0.8"
|
|
curos = platform.system()
|
|
host = platform.node().lower()
|
|
print(host)
|
|
if curos == "Windows":
|
|
import python_aida64
|
|
|
|
def writeLog(msg, svr="INFO"):
|
|
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
if curos == "Windows":
|
|
log_path = "c:\Program Files\jaydee\jaydee.log"
|
|
else:
|
|
log_path = "/tmp/mqtt_srv.log"
|
|
f = open(log_path, "a")
|
|
f.write(ts + " | " + svr + " | " + str(msg) + "\n")
|
|
f.close()
|
|
|
|
if host != "router" and host != "nas":
|
|
import psutil
|
|
|
|
processes = list(p.name() for p in psutil.process_iter())
|
|
# print(processes)
|
|
count = processes.count("mqtt_srv.exe")
|
|
if int(count) >= 3:
|
|
writeLog("script exist")
|
|
sys.exit()
|
|
else:
|
|
cmnd = "ps |grep mqtt_srv.py|grep -v grep |wc -l"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
count = output
|
|
if int(count) >= 2:
|
|
writeLog("script exist")
|
|
sys.exit()
|
|
# Stops duplicate instance from running
|
|
|
|
writeLog(count)
|
|
|
|
writeLog("Starting : " + str(VERSION))
|
|
writeLog("Getting running proccesses", "DEBUG")
|
|
|
|
|
|
writeLog("done", "DEBUG")
|
|
|
|
FILE_TIMESTAMP = os.path.getmtime(sys.argv[0])
|
|
def get_sys_env(name):
|
|
key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r"System\CurrentControlSet\Control\Session Manager\Environment")
|
|
return winreg.QueryValueEx(key, name)[0]
|
|
|
|
def get_user_env(name):
|
|
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Environment")
|
|
return winreg.QueryValueEx(key, name)[0]
|
|
|
|
|
|
_PUBLISH = _SETVAR = False
|
|
try:
|
|
opts, args = getopt.getopt(sys.argv[1:], "Sspmt:", ["command=", "help", "output="])
|
|
except getopt.GetoptError as err:
|
|
# print help information and exit:
|
|
print(str(err)) # will print something like "option -a not recognized"
|
|
#usage()
|
|
sys.exit(2)
|
|
output = None
|
|
# QJ : getopts
|
|
|
|
for o, a in opts:
|
|
if o == "-d":
|
|
_ACTION = True
|
|
elif o in ("-p", "--publish"):
|
|
_PUBLISH = True
|
|
elif o in ("-m", "--publish"):
|
|
_MESSAGE = a
|
|
elif o in ("-t", "--publish"):
|
|
_TOPIC = a
|
|
elif o in ("-S", "--setvar"):
|
|
_SETVAR = True
|
|
_THR_NAME = sys.argv[2]
|
|
_THR_VAL = sys.argv[3]
|
|
else:
|
|
_WIZZARD = True
|
|
MQTT_HOST = "192.168.77.106"
|
|
MQTT_PORT = 1883
|
|
|
|
if _PUBLISH:
|
|
# generate client ID with pub prefix randomly
|
|
#client_id = f'python-mqtt-{random.randint(0, 1000)}'
|
|
client_id = 'python-mqtt-1004'
|
|
username = 'jaydee'
|
|
password = 'jaydee1'
|
|
|
|
def connect_mqtt():
|
|
def on_connect(client, userdata, flags, rc):
|
|
if rc == 0:
|
|
print("Connected to MQTT Broker!")
|
|
else:
|
|
print("Failed to connect, return code %d\n", rc)
|
|
|
|
client = mqtt.Client(client_id)
|
|
client.username_pw_set(username, password)
|
|
client.on_connect = on_connect
|
|
client.connect(MQTT_HOST, MQTT_PORT)
|
|
return client
|
|
|
|
|
|
def publish(client):
|
|
result = client.publish(_TOPIC, _MESSAGE)
|
|
# result: [0, 1]
|
|
status = result[0]
|
|
if status == 0:
|
|
print(f"Send `{_MESSAGE}` to topic `{_TOPIC}`")
|
|
else:
|
|
print(f"Failed to send message to topic {_TOPIC}")
|
|
|
|
client = connect_mqtt()
|
|
publish(client)
|
|
sys.exit()
|
|
|
|
if _SETVAR:
|
|
#myCmd = "setx " + _THR_NAME + " " + _THR_VAL + " -m"
|
|
myCmd = "setx " + _THR_NAME + " " + _THR_VAL
|
|
subprocess.Popen(myCmd.split(), shell=True)
|
|
sys.exit()
|
|
|
|
from ping3 import ping, verbose_ping
|
|
|
|
|
|
|
|
|
|
'''
|
|
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
|
python get-pip.py
|
|
pip3 install getmac
|
|
pip3 install paho.mqttdasdas
|
|
"""
|
|
|
|
'''
|
|
|
|
writeLog("Starting daemon in versin : " + VERSION)
|
|
|
|
VERS = '1.3'
|
|
'''
|
|
print("pinging")
|
|
lala = ping(MQTT_HOST)
|
|
|
|
connected = 0
|
|
while connected == 0:
|
|
if type(lala) == float:
|
|
print("Oleee connected")
|
|
writeLog("Mqtt connected", "INFO")
|
|
connected = 1
|
|
else:
|
|
print("blaaah not connected, waiting...(5)")
|
|
writeLog("blaaah not connected, waiting...(5)")
|
|
time.sleep(5)
|
|
lala = ping(MQTT_HOST)
|
|
'''
|
|
|
|
# Function to display hostname and
|
|
# IP address
|
|
def get_ip():
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
try:
|
|
# doesn't even have to be reachable
|
|
s.connect(('192.168.77.1', 1))
|
|
IP = s.getsockname()[0]
|
|
except ValueError:
|
|
IP = '127.0.0.1'
|
|
finally:
|
|
s.close()
|
|
return IP
|
|
|
|
|
|
IP = get_ip()
|
|
|
|
|
|
print("OS : " + curos)
|
|
writeLog("OS : " + curos)
|
|
if curos != "Windows":
|
|
import autorandr
|
|
else:
|
|
import winreg
|
|
|
|
|
|
if host == "raspberrypi":
|
|
mac = str(get_mac_address("eth0"))
|
|
elif host == "SERVER":
|
|
mac = str(get_mac_address("enp2s0"))
|
|
elif host == "ASUS" and curos != "Windows":
|
|
mac = str(get_mac_address("enp3s0f1"))
|
|
else:
|
|
mac = str(get_mac_address("Ethernet"))
|
|
|
|
|
|
print("MAC : " + mac)
|
|
writeLog("MAC : " + mac)
|
|
print("SYSTEM : " + host)
|
|
writeLog("SYSTEM : " + host)
|
|
print("IP : " + IP)
|
|
writeLog("IP : " + IP)
|
|
|
|
flag_connected = 0
|
|
# The callback for when the client receives a CONNACK response from the server.
|
|
def on_connect(client, userdata, flags, rc):
|
|
print("Connected with result code " + str(rc))
|
|
writeLog("Connected with result code " + str(rc))
|
|
global flag_connected
|
|
flag_connected = 1
|
|
# Subscribing in on_connect() means that if we lose the connection and
|
|
# reconnect then subscriptions will be renewed.
|
|
topic = "sectorq/systems/" + host.lower()
|
|
print(topic)
|
|
writeLog(topic)
|
|
time.sleep(1)
|
|
client.publish("sectorq/status", payload="{'action':'connect', 'system':'" + host.lower() + "', 'ip': '" + IP + "', 'mac':'" + mac + "', 'ver':'" + VERS + "'}", qos=0, retain=False)
|
|
client.publish("sectorq/systems/" + host.lower() + "/stat", payload="on", qos=0, retain=True)
|
|
if host.lower() == "router":
|
|
print("Getting fw info")
|
|
cmnd = "/etc/init.d/banip running"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
if status == 0:
|
|
stats["banip"] = "running"
|
|
else:
|
|
stats["banip"] = "stopped"
|
|
|
|
cmnd = "/root/router_cmd.sh -t firewall -n TOSHIBA-WIFI -m get"
|
|
#out = subprocess.Popen(cmnd.split())
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
print(output)
|
|
if output == 1:
|
|
stats["fw"] = 1
|
|
else:
|
|
stats["fw"] = 0
|
|
print("Getting wifi info")
|
|
cmnd = "/root/router_cmd.sh -t wireless -m get"
|
|
#out = subprocess.Popen(cmnd.split())
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
print(output)
|
|
if output == "allow":
|
|
stats["macfilter"] = "allow"
|
|
else:
|
|
stats["macfilter"] = "off"
|
|
client.publish("sectorq/systems/router/stats", json.dumps(stats), qos=0, retain=True)
|
|
if host.lower() == "nas":
|
|
print("Getting VM info")
|
|
|
|
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
|
|
print(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
l = 1
|
|
lines = output.splitlines()
|
|
VMS = {}
|
|
for i in lines:
|
|
l = l + 1
|
|
if l < 4:
|
|
continue
|
|
line = re.split(r" {2,}", i)
|
|
print(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
|
|
VMS[str(line[1].strip())] = str(line[2].strip())
|
|
|
|
|
|
|
|
for m in VMS:
|
|
|
|
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + m
|
|
#out = subprocess.Popen(cmnd.split())
|
|
print(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
print(output)
|
|
if output.strip() == "running":
|
|
client.publish("sectorq/systems/nas/" + m, payload=1, qos=0, retain=True)
|
|
else:
|
|
client.publish("sectorq/systems/nas/" + m, payload=0, qos=0, retain=True)
|
|
|
|
|
|
client.subscribe(topic)
|
|
|
|
def on_disconnect(client, userdata, rc):
|
|
print("disconnecting reason " +str(rc))
|
|
writeLog("disconnecting reason " +str(rc))
|
|
client.connected_flag=False
|
|
client.disconnect_flag=True
|
|
global flag_connected
|
|
flag_connected = 0
|
|
|
|
|
|
# The callback for when a PUBLISH message is received from the server.
|
|
def on_message(client, userdata, msg):
|
|
print(msg.topic)
|
|
print(msg.payload)
|
|
myObj = msg.payload.decode('utf-8')
|
|
# command = re.sub(r"^b\'|\'$", "", str(msg.payload))
|
|
# command = json.loads(msg.payload.decode("utf-8"))
|
|
try:
|
|
myObj = json.loads(msg.payload)
|
|
try:
|
|
writeLog(myObj["action"])
|
|
print(myObj["action"])
|
|
except:
|
|
print("Action not set")
|
|
writeLog("Action not set", "WARNING")
|
|
|
|
try:
|
|
print(myObj["cmd"])
|
|
writeLog(myObj["cmd"])
|
|
except:
|
|
print("Cmd not set")
|
|
writeLog("Cmd not set", "WARNING")
|
|
|
|
try:
|
|
print(myObj["target"])
|
|
writeLog(myObj["target"])
|
|
except:
|
|
print("Target Not Set")
|
|
writeLog("Target Not Set", "WARNING")
|
|
try:
|
|
print(myObj["status"])
|
|
writeLog(myObj["status"])
|
|
except:
|
|
print("Status Not Set")
|
|
writeLog("Status Not Set")
|
|
|
|
try:
|
|
print(myObj["command"])
|
|
writeLog(myObj["command"])
|
|
except:
|
|
print("Command Not Set")
|
|
writeLog("Command Not Set")
|
|
|
|
try:
|
|
print(myObj["cmd_line"])
|
|
writeLog(myObj["cmd_line"])
|
|
except:
|
|
print("Cmd_line Not Set")
|
|
writeLog("Cmd_line Not Set")
|
|
|
|
|
|
if myObj["cmd"] == "command":
|
|
|
|
print("Executing " + myObj["cmd_line"])
|
|
writeLog("Executing " + myObj["cmd_line"])
|
|
#os.system('start /b "' + myObj["cmd_line"] + '"')
|
|
try:
|
|
subprocess.Popen(myObj["cmd_line"].split(), shell=True)
|
|
#subprocess.Popen(myObj["cmd_line"].split())
|
|
# ctypes.windll.user32.MessageBoxW(0, myObj["cmd_line"], "Executed", 64)
|
|
except:
|
|
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 16)
|
|
print("Executed " + myObj["cmd_line"])
|
|
writeLog("Executed " + myObj["cmd_line"])
|
|
|
|
if myObj["cmd"] == "nas_cmd":
|
|
print("Executing NAS")
|
|
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + str(myObj["target"])
|
|
print(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
print(output)
|
|
cmd_type = myObj["command"]
|
|
if myObj["command"] == "start":
|
|
if output.strip() == "paused":
|
|
print("System suspended")
|
|
cmd_type = "resume"
|
|
else:
|
|
print("System Off")
|
|
cmd_type = "start"
|
|
if myObj["command"] == "suspend":
|
|
cmd_type = "shutdown"
|
|
|
|
|
|
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh " + cmd_type + " " + str(myObj["target"])
|
|
subprocess.Popen(cmnd.split())
|
|
print(cmnd)
|
|
if myObj["command"] == "start":
|
|
try:
|
|
print("sending")
|
|
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload=1, qos=0, retain=False)
|
|
except:
|
|
print("failed to execute!")
|
|
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload="failed", qos=0, retain=False)
|
|
else:
|
|
try:
|
|
print("sending")
|
|
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload=0, qos=0, retain=False)
|
|
except:
|
|
print("failed to execute!")
|
|
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload="failed", qos=0, retain=False)
|
|
|
|
|
|
if myObj["cmd"] == "distrib":
|
|
print("distributin313g")
|
|
# os.startfile(sys.argv[0])
|
|
#sys.exit()
|
|
subprocess.Popen(['/bin/systemctl', 'restart', 'mqtt'])
|
|
|
|
if myObj["cmd"] == "uci":
|
|
print("uci1")
|
|
print("Executing " + myObj["cmd_line"])
|
|
writeLog("Executing " + myObj["cmd_line"])
|
|
|
|
if myObj["cmd_line"] == "wireless1":
|
|
cmnd = "/root/router_cmd.sh -t wireless -v 1 -m set"
|
|
try:
|
|
subprocess.Popen(cmnd.split())
|
|
print("sending")
|
|
stats["macfilter"] = "allow"
|
|
client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
|
|
writeLog("Payload : " + json.dumps(stats))
|
|
except:
|
|
print("failed to execute!")
|
|
client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
|
|
|
|
elif myObj["cmd_line"] == "wireless0":
|
|
cmnd = "/root/router_cmd.sh -t wireless -v 0 -m set"
|
|
try:
|
|
subprocess.Popen(cmnd.split())
|
|
print("sending")
|
|
stats["macfilter"] = "off"
|
|
client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
|
|
writeLog("Payload : " + json.dumps(stats))
|
|
except:
|
|
print("failed to execute!")
|
|
client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
|
|
elif myObj["cmd_line"] == "fw0":
|
|
cmnd = "/root/router_cmd.sh -t firewall -n TOSHIBA-WIFI -p enabled -v 0 -m set"
|
|
try:
|
|
subprocess.Popen(cmnd.split())
|
|
print("sending")
|
|
stats["fw"] = 0
|
|
client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
|
|
writeLog("Payload : " + json.dumps(stats))
|
|
except:
|
|
print("failed to execute!")
|
|
client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
|
|
elif myObj["cmd_line"] == "fw1":
|
|
cmnd = "/root/router_cmd.sh -t firewall -n TOSHIBA-WIFI -p enabled -v 1 -m set"
|
|
try:
|
|
#subprocess.Popen(myObj["cmd_line"].split(), shell=True)
|
|
subprocess.Popen(cmnd.split())
|
|
# ctypes.windll.user32.MessageBoxW(0, myObj["cmd_line"], "Executed", 64)
|
|
print("sending")
|
|
stats["fw"] = 1
|
|
client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=False)
|
|
writeLog("Payload : " + json.dumps(stats))
|
|
except:
|
|
print("failed to execute!")
|
|
client.publish("sectorq/systems/router/stats", payload="failed", qos=0, retain=False)
|
|
elif myObj["cmd_line"] == "serv_dest":
|
|
writeLog("Payload111111 : " + myObj["target"].lower())
|
|
|
|
if myObj["target"].lower() == "192.168.77.246":
|
|
dest_ip = "192.168.77.246"
|
|
elif myObj["target"].lower() == "192.168.77.106":
|
|
dest_ip = "192.168.77.106"
|
|
|
|
RULES = ["EMAIL993", "EMAIL995", "EMAIL143", "EMAIL25", "EMAIL993", "EMAIL465", "HTTPS", "HTTP"]
|
|
for i in RULES:
|
|
cmnd = "uci set firewall.{}.dest_ip={}".format(i,dest_ip)
|
|
writeLog(cmnd)
|
|
subprocess.Popen(cmnd.split())
|
|
|
|
#cmnd = "uci set dhcp.@dnsmasq[0].address=/mqtt_broker/" + dest_ip
|
|
#writeLog(cmnd)
|
|
#subprocess.Popen(cmnd.split())
|
|
time.sleep(1)
|
|
cmnd = "uci commit"
|
|
|
|
subprocess.Popen(cmnd.split())
|
|
|
|
writeLog("Starting " + myObj["target"].lower())
|
|
if myObj["target"].lower() == "192.168.77.246":
|
|
dest_ip = "192.168.77.246"
|
|
|
|
|
|
cmnd = "ssh root@192.168.77.246 'docker start mailu_resolver_1 mailu_redis_1 mailu_front_1 mailu_antispam_1 mailu_imap_1 mailu_admin_1 mailu_smtp_1 mailu_webmail_1 watchtower_watchtower_1 nginx-proxy-manager_db_1 nginx-proxy-manager_app_1 HomeAssistant webhub_client_1 dockermon_docker_mon_1 mosquitto_mosquitto_1 node-red_node-red_1 nextcloud_db_1 nextcloud_app_1'"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
elif myObj["target"].lower() == "192.168.77.106":
|
|
dest_ip = "192.168.77.106"
|
|
cmnd = "ssh root@192.168.77.246 'docker stop mailu_resolver_1 mailu_redis_1 mailu_front_1 mailu_antispam_1 mailu_imap_1 mailu_admin_1 mailu_smtp_1 mailu_webmail_1 watchtower_watchtower_1 nginx-proxy-manager_db_1 nginx-proxy-manager_app_1 HomeAssistant webhub_client_1 dockermon_docker_mon_1 mosquitto_mosquitto_1 node-red_node-red_1 nextcloud_db_1 nextcloud_app_1'"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
time.sleep(1)
|
|
cmnd = "/etc/init.d/firewall restart"
|
|
subprocess.Popen(cmnd.split())
|
|
#cmnd = "/etc/init.d/dnsmasq restart"
|
|
#subprocess.Popen(cmnd.split())
|
|
writeLog("reconfigure iot")
|
|
MQTT_BROKER = dest_ip
|
|
MQTT_USER = "jaydee"
|
|
MQTT_PASS = "jaydee1"
|
|
|
|
cmnd = "nmap -sP 192.168.77.*|grep \"Nmap scan report\"|egrep -o \"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\""
|
|
#print(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
|
|
# print(output)
|
|
|
|
ips = output.splitlines()
|
|
tasm_data = {}
|
|
for sys_ip in ips:
|
|
# print("Thsis is ip : " + sys_ip)
|
|
cmnd = "nmap " + sys_ip + " -p80|grep \"80/tcp open http\""
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
# print("status of 80 : " + str(status))
|
|
if status == 0:
|
|
try:
|
|
# url = "http://" + sys_ip + "/cm?user=admin&password=l4c1j4yd33Du5l0&cmnd=STATUS+5"
|
|
|
|
url = "http://" + sys_ip + "/cm?cmnd=Backlog%20MqttHost%20" + MQTT_BROKER + "%3BMqttUser%20" + MQTT_USER + "%3BMqttPassword%20" + MQTT_PASS
|
|
print(url)
|
|
requests.get(url)
|
|
|
|
except:
|
|
#print(sys_ip + " : Not a tasmota!")
|
|
pass
|
|
else:
|
|
#print(sys_ip + " : Not a listening")
|
|
pass
|
|
|
|
|
|
|
|
time.sleep(1)
|
|
cmnd = "sed -i 's/^MQTT_HOST = .*/MQTT_HOST = \"" + dest_ip + "\"/' /root/mqtt_srv.py"
|
|
writeLog(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
#for i in ;do uci set firewall.${i}.dest_ip=192.168.77.246;done;uci set firewall.HTTPS.dest_port='443';uci set firewall.HTTP.dest_port='80' ;uci commit;/etc/init.d/firewall restart
|
|
else:
|
|
pass
|
|
#cmnd = "/root/router_cmd.sh -t wireless -v 0"
|
|
|
|
|
|
print("Executed " + cmnd)
|
|
writeLog("Executed " + cmnd)
|
|
|
|
|
|
if myObj["cmd"] == "banip":
|
|
if myObj["status"] == "ban":
|
|
cmnd = "echo " + str(myObj["target"]) + " >> /etc/banip/banip.blacklist; /etc/init.d/banip refresh"
|
|
elif myObj["status"] == "enable":
|
|
cmnd = "/etc/init.d/banip resume"
|
|
stats["banip"] = "enabled"
|
|
elif myObj["status"] == "disable":
|
|
cmnd = "/etc/init.d/banip suspend"
|
|
stats["banip"] = "paused"
|
|
writeLog(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
|
|
client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=True)
|
|
|
|
if myObj["cmd"] == "vnc":
|
|
print(myObj["target"])
|
|
writeLog(myObj["target"])
|
|
|
|
# os.startfile(sys.argv[0])
|
|
#sys.exit()
|
|
myCmd = 'c:\\Program Files\\RealVNC\\VNC Viewer\\vncviewer.exe C:\\Users\\jaydee\\' + myObj["target"].upper() + '.vnc'
|
|
print(myCmd)
|
|
writeLog(myCmd)
|
|
subprocess.Popen(myCmd.split())
|
|
if myObj["cmd"] == "getstats":
|
|
print("lalaa1")
|
|
try:
|
|
client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":" + get_user_env('mb_temp') + ",\"mem_usage\":" + get_user_env('mem_usage') + ",\"cpu_temp\":" + get_user_env('cpu_temp') + ",\"cpu_usage\":" + get_user_env('cpu_usage') + ",\"gpu_temp\":" + get_user_env('gpu_temp') + ",\"gpu_usage\":" + get_user_env('gpu_usage') + "}", qos=0, retain=False)
|
|
print("ok")
|
|
except:
|
|
print("failed")
|
|
client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)
|
|
|
|
print("lalaa2")
|
|
|
|
if myObj["cmd"] == "display":
|
|
if curos == "Windows1":
|
|
# os.startfile(sys.argv[0])
|
|
#sys.exit()
|
|
#print("reconfigure")
|
|
myCmd = 'MonitorSwitcher.exe -load:' + myObj["target"] + '.xml'
|
|
writeLog(myCmd)
|
|
#writeLog(os.path.realpath(__file__))
|
|
print("lalaa2")
|
|
#subprocess.Popen(r'"{}"'.format(myCmd), shell=True)
|
|
print("lalaa3")
|
|
subprocess.Popen(myCmd.split(), shell=True,cwd=r'c:\Progra~1\jaydee')
|
|
else:
|
|
'''
|
|
myCmd = ""
|
|
if myObj["target"] == "mid":
|
|
myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --off --output eDP-1 --off"
|
|
elif myObj["target"] == "all":
|
|
myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-2 --mode 1920x1080 --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --auto --right-of HDMI-2 --mode 1920x1080"
|
|
elif myObj["target"] == "midleft":
|
|
myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --off"
|
|
elif myObj["target"] == "midtop":
|
|
myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-2 --mode 1920x1080 --output HDMI-1 --off --output eDP-1 --off"
|
|
elif myObj["target"] == "midleftbuild":
|
|
myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --auto --right-of HDMI-2 --mode 1920x1080"
|
|
elif myObj["target"] == "midbuild":
|
|
myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1 --off --output eDP-1 --auto --right-of HDMI-2 --mode 1920x1080"
|
|
elif myObj["target"] == "midlefttop":
|
|
myCmd = "xrandr --output HDMI-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-2 --mode 1920x1080 --output HDMI-1 --auto --left-of HDMI-2 --mode 1920x1080 --output eDP-1 --off"
|
|
else:
|
|
pass
|
|
|
|
if myCmd != "":
|
|
print(myCmd)
|
|
subprocess.Popen(myCmd.split())
|
|
'''
|
|
myCmd = ""
|
|
writeLog(myObj["target"])
|
|
if curos == "Windows":
|
|
if myObj["target"] == "mid":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile mid"
|
|
elif myObj["target"] == "all":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile all"
|
|
elif myObj["target"] == "midleft":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile midleft"
|
|
elif myObj["target"] == "midtop":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile midtop"
|
|
elif myObj["target"] == "midleftbuild":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile midleftbuild"
|
|
elif myObj["target"] == "midbuild":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile midbuild"
|
|
elif myObj["target"] == "midlefttop":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile midlefttop"
|
|
elif myObj["target"] == "build":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile build"
|
|
elif myObj["target"] == "midtopbuild":
|
|
myCmd = "DisplayFusionCommand.exe -monitorloadprofile midtopbuild"
|
|
else:
|
|
pass
|
|
else:
|
|
if myObj["target"] == "mid":
|
|
myCmd = "xrandr --output HDMI-1-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1-1 --off --output eDP-1-1 --off"
|
|
elif myObj["target"] == "all":
|
|
myCmd = "xrandr --output HDMI-1-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-1-2 --mode 1920x1080 --output HDMI-1-1 --auto --left-of HDMI-1-2 --mode 1920x1080 --output eDP-1-1 --auto --right-of HDMI-1-2 --mode 1920x1080"
|
|
elif myObj["target"] == "midleft":
|
|
myCmd = "xrandr --output HDMI-1-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1-1 --auto --left-of HDMI-1-2 --mode 1920x1080 --output eDP-1-1 --off"
|
|
elif myObj["target"] == "midtop":
|
|
myCmd = "xrandr --output HDMI-1-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-1-2 --mode 1920x1080 --output HDMI-1-1 --off --output eDP-1-1 --off"
|
|
elif myObj["target"] == "midleftbuild":
|
|
myCmd = "xrandr --output HDMI-1-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1-1 --auto --left-of HDMI-1-2 --mode 1920x1080 --output eDP-1-1 --auto --right-of HDMI-1-2 --mode 1920x1080"
|
|
elif myObj["target"] == "midbuild":
|
|
myCmd = "xrandr --output HDMI-1-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --off --output HDMI-1-1 --off --output eDP-1-1 --auto --right-of HDMI-1-2 --mode 1920x1080"
|
|
elif myObj["target"] == "midlefttop":
|
|
myCmd = "xrandr --output HDMI-1-2 --primary --auto --mode 1920x1080 --output DVI-I-2-1 --auto --above HDMI-1-2 --mode 1920x1080 --output HDMI-1-1 --auto --left-of HDMI-1-2 --mode 1920x1080 --output eDP-1-1 --off"
|
|
elif myObj["target"] == "build":
|
|
myCmd = "xrandr --output HDMI-1-2 --off --output DVI-I-2-1 --off --output HDMI-1-1 --off --output eDP-1-1 --auto --mode 1920x1080"
|
|
else:
|
|
pass
|
|
|
|
writeLog(myCmd)
|
|
if myCmd != "":
|
|
print(myCmd)
|
|
subprocess.Popen(myCmd.split())
|
|
|
|
if myObj["cmd"] == "display2":
|
|
# os.startfile(sys.argv[0])
|
|
#sys.exit()
|
|
#print("reconfigure")
|
|
subprocess.Popen(['MultiMonitorTool.exe', '/SaveConfig', 'c:\\Program Files\\jaydee\\switcher.cfg'])
|
|
myCmd = "powershell switcher.ps1 " + str(myObj["target"]) + " " + str(myObj["status"])
|
|
writeLog(myCmd)
|
|
subprocess.Popen(myCmd.split())
|
|
time.sleep(1)
|
|
subprocess.Popen(['MultiMonitorTool.exe', '/LoadConfig', 'c:\\Program Files\\jaydee\\switcher.cfg'])
|
|
client.publish("sectorq/feedback", payload='{"action":"resp", "source":"ASUS", "dev":{"display' + str(myObj["target"]) + '":'+ str(myObj["status"]) +'} }' , qos=0, retain=False)
|
|
if myObj["cmd"] == "displ":
|
|
print("Display")
|
|
# os.startfile(sys.argv[0])
|
|
#sys.exit()
|
|
subprocess.Popen(['/usr/bin/xrandr', '--output', 'HDMI-1-1', '--off'])
|
|
|
|
if myObj["cmd"] == "xrandr":
|
|
if curos == "Windows":
|
|
subprocess.Popen(['MultiMonitorTool.exe', '/LoadConfig', 'c:\\Program Files\\jaydee\\all_on.cfg'])
|
|
else:
|
|
print("Display")
|
|
# os.startfile(sys.argv[0])
|
|
#sys.exit()
|
|
os.system("export DISPLAY=:0")
|
|
subprocess.Popen(['/usr/bin/xrandr'])
|
|
|
|
if myObj["cmd"] == "suspend":
|
|
print("suspending")
|
|
if curos == "Windows":
|
|
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
|
|
#cmnd = "psshutdown -d -t 1"
|
|
writeLog(cmnd)
|
|
#status, output = subprocess.getstatusoutput(cmnd)
|
|
#subprocess.Popen(["psshutdown", "-d", "-t", "1"])
|
|
#writeLog(output)
|
|
else:
|
|
if host == "nas" or host == "octopi":
|
|
subprocess.Popen(["/sbin/poweroff"])
|
|
else:
|
|
#subprocess.Popen(["/bin/systemctl", "suspend", "-i"])
|
|
subprocess.Popen(["sudo", "pm-suspend"])
|
|
if myObj["cmd"] == "stats":
|
|
grep = subprocess.Popen(['grep', 'cpu', '/proc/stat'],
|
|
stdout=subprocess.PIPE,
|
|
)
|
|
|
|
awk = subprocess.Popen(['awk', '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'],
|
|
stdin=grep.stdout,
|
|
stdout=subprocess.PIPE,
|
|
)
|
|
|
|
# cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'
|
|
|
|
end_of_pipe = awk.stdout
|
|
|
|
for line in end_of_pipe:
|
|
# print(line.strip())
|
|
# usage = re.sub(r"^b\'|\'$", "", (line.strip()))
|
|
cpu = round(float(line.strip().decode("utf-8")))
|
|
free = subprocess.Popen(['free'],
|
|
stdout=subprocess.PIPE,
|
|
)
|
|
|
|
grep = subprocess.Popen(['grep', 'Mem'],
|
|
stdout=subprocess.PIPE,
|
|
stdin=free.stdout,
|
|
)
|
|
|
|
awk = subprocess.Popen(['awk', '{print $3/$2 * 100.0}'],
|
|
stdin=grep.stdout,
|
|
stdout=subprocess.PIPE,
|
|
)
|
|
|
|
end_of_pipe = awk.stdout
|
|
|
|
for line in end_of_pipe:
|
|
# print(line.strip())
|
|
# mem = re.sub(r"^b\'|\'$", "", (line.strip()))
|
|
mem = round(float(line.strip().decode("utf-8")))
|
|
# mem = re.sub(r"^b\'|\'$", "", mem)
|
|
# cpu = re.sub(r"^b\'|\'$", "", cpu)
|
|
# print(mem)
|
|
jn = {"cpu": cpu, "mem": mem}
|
|
jn = json.dumps(jn)
|
|
client.publish("sectorq/status/" + host, payload=jn, qos=0, retain=False)
|
|
except:
|
|
print("not a json!")
|
|
|
|
client = mqtt.Client()
|
|
payload = "off"
|
|
client.username_pw_set("jaydee", password="jaydee1")
|
|
client.will_set("sectorq/systems/" + host.lower() + "/stat", payload=payload, qos=0, retain=False)
|
|
client.on_connect = on_connect
|
|
client.on_message = on_message
|
|
writeLog(MQTT_HOST)
|
|
client.connect(MQTT_HOST, MQTT_PORT, 5)
|
|
|
|
# client.publish("sectorq/status", payload="{'action':'connect', 'system':'" + host + "', 'ip': '" + IP + "', 'mac':'" + mac + "', 'ver':'?'}", qos=0, retain=False)
|
|
|
|
|
|
# Blocking call that processes network traffic, dispatches callbacks and
|
|
# handles reconnecting.
|
|
# Other loop*() functions are available that give a threaded interface and a
|
|
# manual interface.
|
|
|
|
if curos == "Windows":
|
|
#client.loop_forever()
|
|
client.loop_start()
|
|
NEXT_CHECK = 0
|
|
while True:
|
|
print(VERSION)
|
|
time.sleep(5)
|
|
try:
|
|
mtime = os.path.getmtime(sys.argv[0])
|
|
except OSError:
|
|
mtime = 0
|
|
print(mtime)
|
|
if NEXT_CHECK < int(time.time()):
|
|
NEXT_CHECK = int(time.time()) + 10
|
|
writeLog("Blalala : Next : " + str(NEXT_CHECK))
|
|
if curos == "Windows":
|
|
data = python_aida64.getData()
|
|
#print(json.dumps(data))
|
|
stats = {}
|
|
for i in data:
|
|
for j in data[i]:
|
|
stats[j["id"]] = j["value"]
|
|
|
|
|
|
jn = json.dumps(stats)
|
|
client.publish("home-assistant/" + host + "/hwstats", payload=jn, qos=0, retain=False)
|
|
#print(json.dumps(stats))
|
|
#writeLog(json.dumps(stats))
|
|
else:
|
|
|
|
|
|
client.loop_start()
|
|
|
|
NEXT_CHECK = 0
|
|
while True:
|
|
print(VERSION)
|
|
time.sleep(5)
|
|
try:
|
|
mtime = os.path.getmtime(sys.argv[0])
|
|
except OSError:
|
|
mtime = 0
|
|
print(mtime)
|
|
if NEXT_CHECK < int(time.time()):
|
|
NEXT_CHECK = int(time.time()) + 60
|
|
writeLog("Blalala : Next : " + str(NEXT_CHECK))
|
|
|
|
|
|
if host.lower() == "router":
|
|
cmnd = "/etc/init.d/banip status|grep \"+ status\"|awk '{ print $4 }'"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
writeLog("BanIP Status : " + str(status))
|
|
stats["banip"] = output
|
|
|
|
cmnd = "ncat -z 192.168.77.106 25"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
if status == 0:
|
|
stats["mail_nas"] = "available"
|
|
else:
|
|
stats["mail_nas"] = "unavailable"
|
|
cmnd = "ncat -z 192.168.77.246 25"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
if status == 0:
|
|
stats["mail_rasp"] = "available"
|
|
else:
|
|
stats["mail_rasp"] = "unavailable"
|
|
cmnd = "/root/router_cmd.sh -t serv_dest -m get"
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
stats["serv_dest"] = output
|
|
#out = subprocess.Popen(cmnd.split())
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
print("Getting fw info")
|
|
cmnd = "/root/router_cmd.sh -t firewall -n TOSHIBA-WIFI -m get"
|
|
#out = subprocess.Popen(cmnd.split())
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
print(output)
|
|
stats["fw"] = output
|
|
#client.publish("sectorq/systems/router/fw", payload=str(output), qos=0, retain=True)
|
|
print("Getting wifi info")
|
|
cmnd = "/root/router_cmd.sh -t wireless -m get"
|
|
#out = subprocess.Popen(cmnd.split())
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
print(output)
|
|
if output != 'allow':
|
|
output = 'off'
|
|
stats["macfilter"] = output
|
|
# if output == "allow":\
|
|
writeLog("Payload : " + str(json.dumps(stats)))
|
|
client.publish("sectorq/systems/router/stats", payload=json.dumps(stats), qos=0, retain=True)
|
|
#else:
|
|
# client.publish("sectorq/systems/router/macfilter", payload=0, qos=0, retain=True)
|
|
if host.lower() == "nas":
|
|
print("Getting VM info")
|
|
|
|
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
|
|
writeLog(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
l = 1
|
|
lines = output.splitlines()
|
|
VMS = {}
|
|
for i in lines:
|
|
l = l + 1
|
|
if l < 4:
|
|
continue
|
|
line = re.split(r" {2,}", i)
|
|
print(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
|
|
VMS[str(line[1].strip())] = str(line[2].strip())
|
|
|
|
|
|
|
|
for m in VMS:
|
|
|
|
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + m
|
|
#out = subprocess.Popen(cmnd.split())
|
|
writeLog(cmnd)
|
|
status, output = subprocess.getstatusoutput(cmnd)
|
|
writeLog(output)
|
|
if output.strip() == "running":
|
|
client.publish("sectorq/systems/nas/" + m, payload=1, qos=0, retain=True)
|
|
else:
|
|
client.publish("sectorq/systems/nas/" + m, payload=0, qos=0, retain=True)
|
|
|
|
|
|
if FILE_TIMESTAMP != mtime:
|
|
writeLog("Script updated ! restarting...")
|
|
#os.execv(sys.executable, ['python'] + sys.argv)
|
|
#os.system("/share/ZFS530_DATA/.qpkg/QPython39/bin/python3 mqtt_srv.py")
|
|
|
|
if host.lower() == "nas":
|
|
sys.stdout.flush()
|
|
os.execv("/share/ZFS530_DATA/.qpkg/QPython39/bin/python3", sys.argv)
|
|
if host.lower() == "router":
|
|
#sys.stdout.flush()
|
|
sys.exit()
|
|
#os.execv("/usr/bin/python3", sys.argv) |