network.py 3.01 KiB
import platform
import subprocess
import re
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from iotAmak.tool.remote_client import RemoteClient
from iotAmak.tool.ssh_client import SSHClient, Cmd
from ..models import Client, Agent
def get_remote_client():
res = []
for client in Client.objects.all():
if client.status == "Online":
res.append(RemoteClient(client.hostname, client.username, client.password))
return res
def get_ssh_client():
return SSHClient(get_remote_client())
def update(request):
ssh = get_ssh_client()
version = "0.0.1"
commands = [
Cmd(
cmd="cd Desktop/mqtt_goyon/iotamak-core"
),
Cmd(
cmd="git pull"
),
Cmd(
cmd="git checkout main"
),
Cmd(
cmd="git pull"
),
Cmd(
cmd="python3 -m pip install --force-reinstall dist/iotAmak-" + version + "-py3-none-any.whl"
)
]
for i_client in range(len(ssh.clients)):
print("Hostname :", ssh.clients[i_client].hostname, " User :", ssh.clients[i_client].user)
ssh.run_cmd(i_client, commands)
return HttpResponseRedirect(reverse('ping:index'))
def agents(request):
ssh = get_ssh_client()
Agent.objects.all().delete()
commands = [
Cmd(
cmd="ps -ef | tr -s ' ' | cut -d ' ' -f 8-",
do_print=False
)]
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
for i_client in range(len(ssh.clients)):
raw_string = ssh.run_cmd(i_client, commands)[0].split("\r\n")
raw_string = [i for i in raw_string if "python D" in i]
for line in raw_string:
new_entry = Agent(ip=ssh.clients[i_client].hostname, command=ansi_escape.sub('', line))
new_entry.save()
return HttpResponseRedirect(reverse('ping:index'))
def kill(request):
ssh = get_ssh_client()
commands = [
Cmd(
cmd="for pid in $(ps -ef | grep 'python ' | awk '{print $2}'); do kill $pid; done",
do_print=False
)]
for i_client in range(len(ssh.clients)):
ssh.run_cmd(i_client, commands)
return HttpResponseRedirect(reverse('ping:index'))
def index(request):
template = loader.get_template('ping/index.html')
context = {
"host_list": Client.objects.all(),
"agents": Agent.objects.all()
}
return HttpResponse(template.render(context, request))
def pressed(request):
for client in Client.objects.all():
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, '1', client.hostname]
response = subprocess.call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
c = Client.objects.get(hostname=client.hostname)
if response:
c.status = "Online"
else:
c.status = "Offline"
c.save()
return HttpResponseRedirect(reverse('ping:index'))