if form.getvalue('viewlogs') is None: serv = form.getvalue('serv') else: serv = form.getvalue('viewlogs') hour = form.getvalue('hour') hour1 = form.getvalue('hour1') minut = form.getvalue('minut') minut1 = form.getvalue('minut1') print('Content-type: text/html\n') funct.check_login() funct.page_for_admin() log_path = funct.get_config_var('main', 'log_path') time_storage = sql.get_setting('log_time_storage') time_storage = int(time_storage) try: time_storage_hours = time_storage * 24 for dirpath, dirnames, filenames in os.walk(log_path): for file in filenames: curpath = os.path.join(dirpath, file) file_modified = datetime.datetime.fromtimestamp( os.path.getmtime(curpath)) if datetime.datetime.now() - file_modified > datetime.timedelta( hours=time_storage_hours): os.remove(curpath) except: print(
i = 0 print(userlist_user_group) for user in users: try: group = ' groups ' + userlist_user_group[i] except: group = '' new_users_list += " user " + user + " insecure-password " + passwords[ i] + group + "\n" i += 1 config_add = "\n" + name + new_userlist_groups + new_users_list try: if config_add: hap_configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir') cfg = hap_configs_dir + serv + "-" + funct.get_data('config') + ".cfg" funct.get_config(serv, cfg) try: with open(cfg, "a") as conf: conf.write(config_add) except IOError: print("error: Can't read import config file") funct.logging(serv, "add.py add new %s" % name) print( '<div class="line3" style="position: absolute;top: 35px;left: 200px;">' ) MASTERS = sql.is_master(serv)
if form.getvalue('action_waf') is not None and serv is not None: serv = form.getvalue('serv') action = form.getvalue('action_waf') funct.logging(serv, 'WAF service was '+action, haproxywi=1, login=1) commands = [ "sudo systemctl %s waf" % action ] funct.ssh_command(serv, commands) if act == "overviewHapserverBackends": from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('templates/ajax')) template = env.get_template('haproxyservers_backends.html') hap_configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir') try: sections = funct.get_sections(hap_configs_dir +funct.get_files()[0]) except: try: cfg = hap_configs_dir + serv + "-" + funct.get_data('config') + ".cfg" except: funct.logging('localhost', ' Cannot generate cfg path', haproxywi=1) try: error = funct.get_config(serv, cfg) except: funct.logging('localhost', ' Cannot download config', haproxywi=1) try: sections = funct.get_sections(cfg) except: funct.logging('localhost', ' Cannot get sections from config file', haproxywi=1)
def get_map(serv): from datetime import datetime from pytz import timezone import networkx as nx import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt stats_port = sql.get_setting('stats_port') haproxy_config_path = sql.get_setting('haproxy_config_path') hap_configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir') date = funct.get_data('config') cfg = hap_configs_dir + serv + "-" + date + ".cfg" print('<center>') print("<h3>Map from %s</h3><br />" % serv) G = nx.DiGraph() funct.get_config(serv, cfg) try: conf = open(cfg, "r") except IOError: print( '<div class="alert alert-danger">Can\'t read import config file</div>' ) node = "" line_new2 = [1, ""] i = 1200 k = 1200 j = 0 m = 0 for line in conf: if "listen" in line or "frontend" in line: if "stats" not in line: node = line i = i - 500 if line.find("backend") == 0: node = line i = i - 500 G.add_node(node, pos=(k, i), label_pos=(k, i + 150)) if "bind" in line: try: bind = line.split(":") if stats_port not in bind[1]: bind[1] = bind[1].strip(' ') bind = bind[1].split("crt") node = node.strip(' \t\n\r') node = node + ":" + bind[0] G.add_node(node, pos=(k, i), label_pos=(k, i + 150)) except: pass if "server " in line or "use_backend" in line or "default_backend" in line and "stats" not in line: if "timeout" not in line and "default-server" not in line and "#" not in line and "stats" not in line: i = i - 300 j = j + 1 if "check" in line: line_new = line.split("check") else: line_new = line.split("if ") if "server" in line: line_new1 = line_new[0].split("server") line_new[0] = line_new1[1] line_new2 = line_new[0].split(":") line_new[0] = line_new2[0] line_new[0] = line_new[0].strip(' \t\n\r') line_new2[1] = line_new2[1].strip(' \t\n\r') if j % 2 == 0: G.add_node(line_new[0], pos=(k + 250, i - 350), label_pos=(k + 225, i - 100)) else: G.add_node(line_new[0], pos=(k - 250, i - 50), label_pos=(k - 225, i + 180)) if line_new2[1] != "": G.add_edge(node, line_new[0], port=line_new2[1]) else: G.add_edge(node, line_new[0]) os.system("/bin/rm -f " + cfg) pos = nx.get_node_attributes(G, 'pos') pos_label = nx.get_node_attributes(G, 'label_pos') edge_labels = nx.get_edge_attributes(G, 'port') try: plt.figure(10, figsize=(9.5, 15)) nx.draw(G, pos, with_labels=False, font_weight='bold', width=3, alpha=0.1, linewidths=5) nx.draw_networkx_nodes(G, pos, node_color="skyblue", node_size=100, alpha=0.8, node_shape="p") nx.draw_networkx_labels(G, pos=pos_label, alpha=1, font_color="green", font_size=10) nx.draw_networkx_edges(G, pos, width=0.5, alpha=0.5, edge_color="#5D9CEB", arrows=False) nx.draw_networkx_edge_labels(G, pos, label_pos=0.5, font_color="blue", labels=edge_labels, font_size=8) plt.savefig("map.png") plt.show() except Exception as e: print('<div class="alert alert-danger">' + str(e) + '</div>') cmd = "rm -f " + os.path.dirname( os.getcwd()) + "/map*.png && mv map.png " + os.path.dirname( os.getcwd()) + "/map" + date + ".png" output, stderr = funct.subprocess_execute(cmd) print(stderr) print('<img src="/map%s.png" alt="map">' % date)
user_group = sql.get_user_group_by_uuid(user_id.value) token = sql.get_token(user_id.value) except: pass output_from_parsed_template = template.render(title = "Add", role = sql.get_user_role_by_uuid(user_id.value), user = user, selects = servers, add = form.getvalue('add'), conf_add = form.getvalue('conf'), group = user_group, token = token) print(output_from_parsed_template) hap_configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir') cert_path = funct.get_config_var('haproxy', 'cert_path') if form.getvalue('mode') is not None: serv = form.getvalue('serv') port = form.getvalue('port') force_close = form.getvalue('force_close') mode = " mode " + form.getvalue('mode') ssl = "" if form.getvalue('balance') is not None: balance = " balance " + form.getvalue('balance') + "\n" else: balance = "" if form.getvalue('ip') is not None:
#!/usr/bin/env python3 # -*- coding: utf-8 -*-" import cgi import create_db import funct mysql_enable = funct.get_config_var('mysql', 'enable') if mysql_enable == '1': from mysql.connector import errorcode import mysql.connector as sqltool else: import sqlite3 as sqltool def out_error(e): if mysql_enable == '1': error = e else: error = e.args[0] print('<span class="alert alert-danger" id="error">An error occurred: ' + error + ' <a title="Close" id="errorMess"><b>X</b></a></span>') def add_user(user, email, password, role, group): con, cur = create_db.get_cur() sql = """INSERT INTO user (username, email, password, role, groups) VALUES ('%s', '%s', '%s', '%s', '%s')""" % (user, email, password, role, group) try: cur.execute(sql) con.commit() except sqltool.Error as e: out_error(e) con.rollback() return False
if form.getvalue('grep') is None: grep = "" else: grep = form.getvalue('grep') if form.getvalue('rows') is None: rows = 10 else: rows = form.getvalue('rows') print('Content-type: text/html\n') funct.check_login() funct.page_for_admin() log_path = funct.get_config_var('main', 'log_path') time_storage = funct.get_config_var('logs', 'log_time_storage') time_storage = int(time_storage) try: time_storage_hours = time_storage * 24 for dirpath, dirnames, filenames in os.walk(log_path): for file in filenames: curpath = os.path.join(dirpath, file) file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath)) if datetime.datetime.now() - file_modified > datetime.timedelta(hours=time_storage_hours): os.remove(curpath) except: print('<center><div class="alert alert-danger" style="margin: 0; margin-bottom: 10px;">Can\'t delete old logs file. <br> Please check "log_time_storage" in config and <br>exist directory </div></center>') pass
import cgi import os import http.cookies import funct import sql from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('templates/')) template = env.get_template('config.html') print('Content-type: text/html\n') funct.check_login() funct.page_for_admin(level=2) form = cgi.FieldStorage() serv = form.getvalue('serv') log_path = funct.get_config_var('main', 'log_path') kp_save_configs_dir = funct.get_config_var('configs', 'kp_save_configs_dir') config_read = "" cfg = "" stderr = "" aftersave = "" error = "" try: cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE")) user_id = cookie.get('uuid') user = sql.get_user_name_by_uuid(user_id.value) servers = sql.is_master("123", master_slave=1) token = sql.get_token(user_id.value) except: pass
import funct import os import cgi import sql cgi_path = funct.get_config_var('main', 'cgi_path') fullpath = funct.get_config_var('main', 'fullpath') stats_port = funct.get_config_var('haproxy', 'stats_port') haproxy_config_path = funct.get_config_var('haproxy', 'haproxy_config_path') status_command = funct.get_config_var('haproxy', 'status_command') hap_configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir') form = cgi.FieldStorage() def get_overview(): listhap = sql.get_dick_permit() commands = ["ps -Af |grep [h]aproxy |wc -l"] commands1 = [ "ls -l %s |awk '{ print $6\" \"$7\" \"$8}'" % haproxy_config_path ] for server in listhap: print( '<tr><td class="padding10 first-collumn"><a href="#%s" title="Go to %s status" style="color: #000">%s</a></td><td class="second-collumn">' % (server[1], server[1], server[1])) funct.ssh_command(server[2], commands, server_status="1") print('</td><td>') if funct.is_admin(): print( '<a id="%s" class="start" title="Start HAproxy service"><img src=/image/pic/start.png alt="start" class="icon"></a>'
#!/usr/bin/env python3 # -*- coding: utf-8 -*-" import cgi import create_db import funct mysql_enable = funct.get_config_var('mysql', 'enable') if mysql_enable == '1': from mysql.connector import errorcode import mysql.connector as sqltool else: import sqlite3 as sqltool def add_user(user, email, password, role, group): con, cur = create_db.get_cur() sql = """INSERT INTO user (username, email, password, role, groups) VALUES ('%s', '%s', '%s', '%s', '%s')""" % ( user, email, password, role, group) try: cur.execute(sql) con.commit() except sqltool.Error as e: print( '<span class="alert alert-danger" id="error">An error occurred: ' + e.args[0] + ' <a title="Close" id="errorMess"><b>X</b></a></span>') con.rollback() return False else: return True cur.close()
stderr = "" aftersave = "" file = set() if configver: template = env.get_template('configver.html') try: user, user_id, role, token, servers, user_services = funct.get_users_params( disable=1) except: pass if service == 'keepalived': if funct.check_login(service=3): configs_dir = funct.get_config_var('configs', 'kp_save_configs_dir') title = "Working with versions Keepalived configs" conf_format = 'conf' servers = sql.get_dick_permit(keepalived=1) action = 'versions.py?service=keepalived' elif service == 'nginx': if funct.check_login(service=2): configs_dir = funct.get_config_var('configs', 'nginx_save_configs_dir') title = "Working with versions Nginx configs" conf_format = 'conf' servers = sql.get_dick_permit(nginx=1) action = 'versions.py?service=nginx' else: service = 'haproxy' if funct.check_login(service=1): title = "Working with versions HAProxy configs"
serv = form.getvalue('serv') act = form.getvalue('act') backend = form.getvalue('backend') print('Content-type: text/html\n') if form.getvalue('getcert') is not None and serv is not None: commands = ["ls -1t /etc/ssl/certs/ |grep pem"] try: funct.ssh_command(serv, commands, ip="1") except: print( '<div class="alert alert-danger" style="margin:0">Can not connect to the server</div>' ) if form.getvalue('ssh_cert'): ssh_keys = funct.get_config_var('ssh', 'ssh_keys') try: with open(ssh_keys, "w") as conf: conf.write(form.getvalue('ssh_cert')) except IOError: print( '<div class="alert alert-danger">Can\'t save ssh keys file. Check ssh keys path in config</div>' ) else: print( '<div class="alert alert-success">Ssh key was save into: %s </div>' % ssh_keys) try: funct.logging("local", "users.py#ssh upload new ssl cert %s" % ssh_keys)
#!/usr/bin/env python3 import cgi import html import os import sys import funct mysql_enable = funct.get_config_var('mysql', 'enable') if mysql_enable == '1': mysql_user = funct.get_config_var('mysql', 'mysql_user') mysql_password = funct.get_config_var('mysql', 'mysql_password') mysql_db = funct.get_config_var('mysql', 'mysql_db') mysql_host = funct.get_config_var('mysql', 'mysql_host') from mysql.connector import errorcode import mysql.connector as sqltool else: fullpath = funct.get_config_var('main', 'fullpath') db = fullpath + "/app/haproxy-wi.db" import sqlite3 as sqltool def check_db(): if mysql_enable == '0': if os.path.isfile(db): if os.path.getsize(db) > 100: with open(db, 'r', encoding="ISO-8859-1") as f: header = f.read(100) if header.startswith('SQLite format 3'): return False else:
#!/usr/bin/env python3 import funct mysql_enable = funct.get_config_var('mysql', 'enable') if mysql_enable == '1': mysql_user = funct.get_config_var('mysql', 'mysql_user') mysql_password = funct.get_config_var('mysql', 'mysql_password') mysql_db = funct.get_config_var('mysql', 'mysql_db') mysql_host = funct.get_config_var('mysql', 'mysql_host') mysql_port = funct.get_config_var('mysql', 'mysql_port') import mysql.connector as sqltool else: db = "/var/www/haproxy-wi/app/haproxy-wi.db" import sqlite3 as sqltool def check_db(): if mysql_enable == '0': import os if os.path.isfile(db): if os.path.getsize(db) > 100: with open(db, 'r', encoding="ISO-8859-1") as f: header = f.read(100) if header.startswith('SQLite format 3'): return False else: return True else: return True else:
if form.getvalue('action_waf') is not None and serv is not None: serv = form.getvalue('serv') action = form.getvalue('action_waf') funct.logging(serv, 'WAF service was '+action, haproxywi=1, login=1) commands = [ "sudo systemctl %s waf" % action ] funct.ssh_command(serv, commands) if act == "overviewHapserverBackends": from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('templates/ajax')) template = env.get_template('haproxyservers_backends.html') hap_configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir') try: sections = funct.get_sections(hap_configs_dir +funct.get_files()[0]) except: try: cfg = hap_configs_dir + serv + "-" + funct.get_data('config') + ".cfg" except: funct.logging('localhost', ' Cannot generate cfg path', haproxywi=1) try: error = funct.get_config(serv, cfg) except: funct.logging('localhost', ' Cannot download config', haproxywi=1) try: sections = funct.get_sections(cfg) except: funct.logging('localhost', ' Cannot get sections from config file', haproxywi=1)
ssh_keys = os.path.dirname(os.getcwd())+'/keys/'+name+'.pem' try: with open(ssh_keys, "w") as conf: conf.write(form.getvalue('ssh_cert')) except IOError: print('<div class="alert alert-danger">Can\'t save ssh keys file. Check ssh keys path in config</div>') else: print('<div class="alert alert-success">Ssh key was save into: %s </div>' % ssh_keys) try: funct.logging("local", "users.py#ssh upload new ssh cert %s" % ssh_keys) except: pass if serv and form.getvalue('ssl_cert'): cert_local_dir = funct.get_config_var('main', 'cert_local_dir') cert_path = sql.get_setting('cert_path') if not os.path.exists(cert_local_dir): os.makedirs(cert_local_dir) if form.getvalue('ssl_name') is None: print('<div class="alert alert-danger">Please enter desired name</div>') else: name = form.getvalue('ssl_name') + '.pem' try: with open(name, "w") as ssl_cert: ssl_cert.write(form.getvalue('ssl_cert')) except IOError: print('<div class="alert alert-danger">Can\'t save ssl keys file. Check ssh keys path in config</div>')
if form.getvalue('configver'): template = env.get_template('configver.html') try: cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE")) user_id = cookie.get('uuid') user = sql.get_user_name_by_uuid(user_id.value) token = sql.get_token(user_id.value) servers = sql.get_dick_permit(disable=0) except: pass if service == 'keepalived': title = "Working with versions Keepalived configs" files = funct.get_files(dir=funct.get_config_var('configs', 'kp_save_configs_dir'), format='conf') action = 'versions.py?service=keepalived' configs_dir = funct.get_config_var('configs', 'kp_save_configs_dir') format = 'conf' else: title = "Working with versions HAProxy configs" files = funct.get_files() action = "versions.py" configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir') format = 'cfg' if serv is not None and form.getvalue('del') is not None: if Select is not None: aftersave = 1 for get in form: