Pymonit/app.py

72 lines
2.5 KiB
Python

#!/usr/bin/python3
import paramiko
from config import *
from flask import Flask, redirect, render_template, request, url_for, Response, stream_with_context
import time
from datetime import datetime
import json
app = Flask(__name__)
def get_remote(hostname, port, username, password, local_script_path, remote_script_path):
ssh = paramiko.SSHClient()
try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, port, username, password)
sftp = ssh.open_sftp()
sftp.put(local_script_path, remote_script_path)
sftp.close()
stdin, stdout, stderr = ssh.exec_command(f"python3 {remote_script_path}")
output = stdout.read().decode()
return(output)
finally:
ssh.close()
def get_boot_time(psboot):
boot_time = datetime.fromtimestamp(psboot - 60)
return str(boot_time)
def get_full(node):
remote_info = get_remote(node, ssh_conf.port, ssh_conf.username, ssh_conf.password, paths.agent_path, paths.remote_path)
full = eval(remote_info)
return full
@app.route("/", methods = ['GET'])
def get_info():
node = 'localhost'
full = get_full(node)
boottime = get_boot_time(full['boot_time'])
return render_template('index.html', full = full, client = client, titre = flask_conf.title, node = node, boottime = boottime)
@app.route("/n/<node>", methods = ['POST', 'GET'])
def get_node_info(node):
full = get_full(node)
boottime = get_boot_time(full['boot_time'])
return render_template('index.html', full = full, client = client, titre = flask_conf.title, node = node, boottime = boottime)
def get_ressources(nodename):
while True:
full = get_full(nodename)
json_data = json.dumps(
{
"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"cpu": full['cpu']['percent'],
"mem": full['mem']['percent'],
"swap": full['swap']['percent'],
}
)
yield f"data:{json_data}\n\n"
time.sleep(1)
@app.route("/chart-ressources/<nodename>")
def chart_data(nodename) -> Response:
response = Response(stream_with_context(get_ressources(nodename)), mimetype="text/event-stream")
response.headers["Cache-Control"] = "no-cache"
response.headers["X-Accel-Buffering"] = "no"
return response
if __name__ == "__main__":
app.run(host=flask_conf.host, port=flask_conf.port, use_reloader=flask_conf.reloader, threaded=flask_conf.thread, debug=flask_conf.debug)