haproxy-wi/app/funct.py

525 lines
14 KiB
Python
Raw Normal View History

2018-04-27 13:34:11 +00:00
# -*- coding: utf-8 -*-"
2018-01-15 06:16:04 +00:00
import cgi
2018-04-28 04:06:48 +00:00
import os, sys
2018-01-15 06:16:04 +00:00
import paramiko
import http.cookies
from paramiko import SSHClient
from datetime import datetime
from pytz import timezone
from configparser import ConfigParser, ExtendedInterpolation
2018-01-15 06:16:04 +00:00
2018-04-10 03:58:56 +00:00
form = cgi.FieldStorage()
serv = form.getvalue('serv')
2018-01-15 06:16:04 +00:00
2018-07-31 02:20:23 +00:00
def get_app_dir():
d = sys.path[0]
d = d.split('/')[-1]
if d == "app":
return sys.path[0]
else:
return os.path.dirname(sys.path[0])
def get_config_var(sec, var):
try:
2018-07-31 02:20:23 +00:00
path_config = get_app_dir()+"/haproxy-webintarface.config"
config = ConfigParser(interpolation=ExtendedInterpolation())
config.read(path_config)
except:
2018-06-01 12:27:58 +00:00
print('Content-type: text/html\n')
2018-05-29 09:53:20 +00:00
print('<center><div class="alert alert-danger">Check the config file, whether it exists and the path. Must be: app/haproxy-webintarface.config</div>')
try:
var = config.get(sec, var)
return var
except:
2018-06-01 12:27:58 +00:00
print('Content-type: text/html\n')
print('<center><div class="alert alert-danger">Check the config file. Presence section %s and parameter %s</div>' % (sec, var))
def get_data(type):
import sql
now_utc = datetime.now(timezone(sql.get_setting('time_zone')))
if type == 'config':
fmt = "%Y-%m-%d.%H:%M:%S"
if type == 'logs':
fmt = '%Y%m%d'
2018-05-29 09:53:20 +00:00
if type == "date_in_log":
fmt = "%b %d %H:%M:%S"
return now_utc.strftime(fmt)
def logging(serv, action, **kwargs):
2018-05-03 06:36:50 +00:00
import sql
log_path = get_config_var('main', 'log_path')
try:
IP = cgi.escape(os.environ["REMOTE_ADDR"])
cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))
user_uuid = cookie.get('uuid')
login = sql.get_user_name_by_uuid(user_uuid.value)
except:
pass
if kwargs.get('alerting') == 1:
mess = get_data('date_in_log') + action + "\n"
log = open(log_path + "/checker-"+get_data('logs')+".log", "a")
elif kwargs.get('metrics') == 1:
mess = get_data('date_in_log') + action + "\n"
log = open(log_path + "/metrics-"+get_data('logs')+".log", "a")
else:
mess = get_data('date_in_log') + " from " + IP + " user: " + login + " " + action + " for: " + serv + "\n"
log = open(log_path + "/config_edit-"+get_data('logs')+".log", "a")
try:
log.write(mess)
log.close
except IOError:
print('<center><div class="alert alert-danger">Can\'t read write log. Please chech log_path in config</div></center>')
pass
2018-07-25 06:28:33 +00:00
def telegram_send_mess(mess, **kwargs):
import telebot
from telebot import apihelper
import sql
2018-07-25 06:28:33 +00:00
telegrams = sql.get_telegram_by_ip(kwargs.get('ip'))
2018-07-25 15:57:42 +00:00
for telegram in telegrams:
token_bot = telegram[1]
channel_name = telegram[2]
proxy = sql.get_setting('proxy')
2018-01-26 07:36:01 +00:00
if proxy is not None:
apihelper.proxy = {'https': proxy}
2018-07-25 15:57:42 +00:00
try:
bot = telebot.TeleBot(token=token_bot)
bot.send_message(chat_id=channel_name, text=mess)
except:
print("Fatal: Can't send message. Add Telegram chanel before use alerting at this servers group")
sys.exit()
2018-01-26 07:36:01 +00:00
2018-02-27 13:39:24 +00:00
def check_login(**kwargs):
import sql
cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))
user_uuid = cookie.get('uuid')
ref = os.environ.get("SCRIPT_NAME")
2018-06-01 12:27:58 +00:00
sql.delete_old_uuid()
if user_uuid is not None:
2018-06-01 12:27:58 +00:00
sql.update_last_act_user(user_uuid.value)
if sql.get_user_name_by_uuid(user_uuid.value) is None:
print('<meta http-equiv="refresh" content="0; url=login.py?ref=%s">' % ref)
else:
print('<meta http-equiv="refresh" content="0; url=login.py?ref=%s">' % ref)
2018-04-05 03:34:17 +00:00
def is_admin(**kwargs):
import sql
2018-02-23 17:37:59 +00:00
cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))
user_id = cookie.get('uuid')
try:
role = sql.get_user_role_by_uuid(user_id.value)
except:
role = 3
pass
level = kwargs.get("level")
2018-04-05 03:34:17 +00:00
if level is None:
level = 1
2018-04-05 03:34:17 +00:00
2018-02-23 17:37:59 +00:00
try:
if role <= level:
2018-02-23 17:37:59 +00:00
return True
else:
return False
except:
return False
pass
2018-04-05 03:34:17 +00:00
def page_for_admin(**kwargs):
give_level = kwargs.get("level")
if give_level is None:
give_level = 1
if not is_admin(level = give_level):
print('<center><h3 style="color: red">How did you get here?! O_o You do not have need permissions</h>')
print('<meta http-equiv="refresh" content="10; url=/">')
import sys
sys.exit()
2018-07-25 15:57:42 +00:00
def ssh_connect(serv, **kwargs):
import sql
2018-06-24 09:31:28 +00:00
fullpath = get_config_var('main', 'fullpath')
for sshs in sql.select_ssh(serv=serv):
ssh_enable = sshs[3]
ssh_user_name = sshs[4]
ssh_user_password = sshs[5]
ssh_key_name = fullpath+'/keys/%s.pem' % sshs[2]
2018-01-15 06:16:04 +00:00
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
2018-02-06 06:36:43 +00:00
try:
if ssh_enable == 1:
2018-06-24 09:31:28 +00:00
k = paramiko.RSAKey.from_private_key_file(ssh_key_name)
2018-02-06 06:36:43 +00:00
ssh.connect(hostname = serv, username = ssh_user_name, pkey = k )
else:
2018-06-24 09:31:28 +00:00
ssh.connect(hostname = serv, username = ssh_user_name, password = ssh_user_password)
if kwargs.get('check'):
return True
else:
return ssh
2018-02-06 06:36:43 +00:00
except paramiko.AuthenticationException:
if kwargs.get('check'):
print('<div class="alert alert-danger">Authentication failed, please verify your credentials</div>')
return False
else:
return 'Authentication failed, please verify your credentials'
2018-05-08 09:12:16 +00:00
pass
2018-02-06 06:36:43 +00:00
except paramiko.SSHException as sshException:
if kwargs.get('check'):
print('<div class="alert alert-danger">Unable to establish SSH connection: %s </div>' % sshException)
return False
else:
return 'Unable to establish SSH connection: %s ' % sshException
2018-05-08 09:12:16 +00:00
pass
2018-02-06 06:36:43 +00:00
except paramiko.BadHostKeyException as badHostKeyException:
if kwargs.get('check'):
print('<div class="alert alert-danger">Unable to verify server\'s host key: %s </div>' % badHostKeyException)
return False
else:
return 'Unable to verify server\'s host key: %s ' % badHostKeyException
2018-05-08 09:12:16 +00:00
pass
2018-02-06 06:36:43 +00:00
except Exception as e:
2018-08-01 08:06:09 +00:00
if e == "No such file or directory":
if kwargs.get('check'):
2018-08-01 08:06:09 +00:00
print('<div class="alert alert-danger">{}. Check ssh key</div>'.format(e))
else:
2018-08-01 08:06:09 +00:00
return '{}. Check ssh key'.format(e)
2018-05-08 09:12:16 +00:00
pass
2018-08-01 08:06:09 +00:00
elif e == "Invalid argument":
if kwargs.get('check'):
print('<div class="alert alert-danger">Check the IP of the new server</div>')
else:
error = 'Check the IP of the new server'
2018-05-08 09:12:16 +00:00
pass
2018-05-03 06:36:50 +00:00
else:
if kwargs.get('check'):
2018-08-01 08:06:09 +00:00
print('<div class="alert alert-danger">{}</div>'.format(e))
else:
2018-08-01 08:06:09 +00:00
error = e
2018-05-08 09:12:16 +00:00
pass
if kwargs.get('check'):
return False
else:
return error
2018-01-26 07:36:01 +00:00
2018-04-28 04:06:48 +00:00
def get_config(serv, cfg, **kwargs):
import sql
error = ""
2018-04-28 04:06:48 +00:00
if kwargs.get("keepalived"):
2018-04-28 08:19:00 +00:00
config_path = "/etc/keepalived/keepalived.conf"
2018-04-28 04:06:48 +00:00
else:
config_path = sql.get_setting('haproxy_config_path')
2018-04-28 04:06:48 +00:00
2018-01-26 07:36:01 +00:00
ssh = ssh_connect(serv)
2018-02-06 06:36:43 +00:00
try:
sftp = ssh.open_sftp()
2018-04-28 04:06:48 +00:00
sftp.get(config_path, cfg)
2018-02-06 06:36:43 +00:00
sftp.close()
ssh.close()
except Exception as e:
ssh += str(e)
return ssh
2018-01-15 06:16:04 +00:00
2018-05-29 09:53:20 +00:00
def diff_config(oldcfg, cfg):
import subprocess
log_path = get_config_var('main', 'log_path')
diff = ""
date = get_data('date_in_log')
cmd="/bin/diff -ub %s %s" % (oldcfg, cfg)
output, stderr = subprocess_execute(cmd)
2018-05-29 09:53:20 +00:00
for line in output:
diff += date + " " + line + "\n"
try:
log = open(log_path + "/config_edit-"+get_data('logs')+".log", "a")
log.write(diff)
log.close
except IOError:
print('<center><div class="alert alert-danger">Can\'t read write change to log. %s</div></center>' % stderr)
pass
2018-07-17 03:21:08 +00:00
def install_haproxy(serv, **kwargs):
import sql
2018-04-28 04:06:48 +00:00
script = "install_haproxy.sh"
tmp_config_path = sql.get_setting('tmp_config_path')
haproxy_sock_port = sql.get_setting('haproxy_sock_port')
stats_port = sql.get_setting('stats_port')
server_state_file = sql.get_setting('server_state_file')
stats_user = sql.get_setting('stats_user')
stats_password = sql.get_setting('stats_password')
proxy = sql.get_setting('proxy')
2018-04-28 04:06:48 +00:00
os.system("cp scripts/%s ." % script)
if proxy is not None:
proxy_serv = proxy
else:
proxy_serv = ""
commands = [ "chmod +x "+tmp_config_path+script+" && " +tmp_config_path+"/"+script +" PROXY=" + proxy_serv+
" SOCK_PORT="+haproxy_sock_port+" STAT_PORT="+stats_port+" STAT_FILE="+server_state_file+
" STATS_USER="+stats_user+" STATS_PASS="+stats_password ]
2018-04-28 04:06:48 +00:00
upload(serv, tmp_config_path, script)
ssh_command(serv, commands, print_out="1")
2018-04-28 04:06:48 +00:00
2018-07-17 03:21:08 +00:00
if kwargs.get('syn_flood') == "1":
syn_flood_protect(serv)
2018-08-17 04:41:50 +00:00
if kwargs.get('waf') == "1":
waf_install(serv)
2018-07-17 03:21:08 +00:00
os.system("rm -f %s" % script)
def syn_flood_protect(serv, **kwargs):
import sql
2018-07-17 03:21:08 +00:00
script = "syn_flood_protect.sh"
tmp_config_path = sql.get_setting('tmp_config_path')
2018-07-17 03:21:08 +00:00
if kwargs.get('enable') == "0":
enable = "disable"
else:
enable = "enable"
os.system("cp scripts/%s ." % script)
commands = [ "chmod +x "+tmp_config_path+script, tmp_config_path+script+ " "+enable ]
upload(serv, tmp_config_path, script)
ssh_command(serv, commands, print_out="1")
2018-07-17 03:21:08 +00:00
2018-04-28 04:06:48 +00:00
os.system("rm -f %s" % script)
2018-08-17 04:41:50 +00:00
def waf_install(serv, **kwargs):
import sql
script = "waf.sh"
tmp_config_path = sql.get_setting('tmp_config_path')
proxy = sql.get_setting('proxy')
haproxy_dir = sql.get_setting('haproxy_dir')
ver = check_haproxy_version(serv)
os.system("cp scripts/%s ." % script)
commands = [ "chmod +x "+tmp_config_path+script+" && " +tmp_config_path+script +" PROXY=" + proxy+
" HAPROXY_PATH="+haproxy_dir +" VERSION="+ver ]
upload(serv, tmp_config_path, script)
ssh_command(serv, commands, print_out="1")
os.system("rm -f %s" % script)
def check_haproxy_version(serv):
import sql
haproxy_sock_port = sql.get_setting('haproxy_sock_port')
ver = ""
cmd="echo 'show info' |nc %s %s |grep Version |awk '{print $2}'" % (serv, haproxy_sock_port)
output, stderr = subprocess_execute(cmd)
for line in output:
ver = line
return ver
def upload(serv, path, file, **kwargs):
full_path = path + file
try:
ssh = ssh_connect(serv)
except Exception as e:
print('<div class="alert alert-danger">Connect fail: %s</div>' % e)
try:
sftp = ssh.open_sftp()
file = sftp.put(file, full_path)
sftp.close()
2018-04-27 04:07:59 +00:00
ssh.close()
except Exception as e:
print('<div class="alert alert-danger">Upload fail: %s</div>' % e)
2018-01-18 09:15:11 +00:00
def upload_and_restart(serv, cfg, **kwargs):
import sql
tmp_file = sql.get_setting('tmp_config_path') + "/" + get_data('config') + ".cfg"
error = ""
2018-04-26 04:24:23 +00:00
try:
os.system("dos2unix "+cfg)
except OSError:
2018-05-06 19:58:52 +00:00
return 'Please install dos2unix'
pass
2018-04-26 04:24:23 +00:00
try:
ssh = ssh_connect(serv)
except:
2018-05-06 19:58:52 +00:00
return 'Connect fail'
2018-01-15 06:16:04 +00:00
sftp = ssh.open_sftp()
sftp.put(cfg, tmp_file)
2018-01-15 06:16:04 +00:00
sftp.close()
2018-04-28 04:06:48 +00:00
if kwargs.get("keepalived") == 1:
if kwargs.get("just_save") == "save":
2018-05-06 19:58:52 +00:00
commands = [ "sudo mv -f " + tmp_file + " /etc/keepalived/keepalived.conf" ]
2018-04-28 04:06:48 +00:00
else:
2018-05-06 19:58:52 +00:00
commands = [ "sudo mv -f " + tmp_file + " /etc/keepalived/keepalived.conf", "sudo systemctl restart keepalived" ]
else:
2018-04-28 04:06:48 +00:00
if kwargs.get("just_save") == "save":
commands = [ "sudo /sbin/haproxy -q -c -f " + tmp_file + "&& sudo mv -f " + tmp_file + " " + sql.get_setting('haproxy_config_path') ]
2018-04-28 04:06:48 +00:00
else:
commands = [ "sudo /sbin/haproxy -q -c -f " + tmp_file + "&& sudo mv -f " + tmp_file + " " + sql.get_setting('haproxy_config_path') + " && sudo " + sql.get_setting('restart_command') ]
2018-04-28 04:06:48 +00:00
try:
if sql.get_setting('firewall_enable') == "1":
2018-04-28 04:06:48 +00:00
commands.extend(open_port_firewalld(cfg))
except:
return 'Please check the config for the presence of the parameter - "firewall_enable". Mast be: "0" or "1". Firewalld configure not working now'
2018-04-27 04:42:20 +00:00
2018-01-15 06:16:04 +00:00
for command in commands:
stdin, stdout, stderr = ssh.exec_command(command)
2018-05-06 19:58:52 +00:00
return stderr.read()
2018-01-15 06:16:04 +00:00
ssh.close()
2018-04-27 04:07:59 +00:00
def open_port_firewalld(cfg):
try:
conf = open(cfg, "r")
except IOError:
print('<div class="alert alert-danger">Can\'t read export config file</div>')
firewalld_commands = []
for line in conf:
if "bind" in line:
bind = line.split(":")
bind[1] = bind[1].strip(' ')
bind = bind[1].split("ssl")
bind = bind[0].strip(' \t\n\r')
2018-05-06 19:58:52 +00:00
firewalld_commands.append('sudo firewall-cmd --zone=public --add-port=%s/tcp --permanent' % bind)
2018-04-27 04:07:59 +00:00
2018-05-06 19:58:52 +00:00
firewalld_commands.append('sudo firewall-cmd --reload')
2018-04-27 04:07:59 +00:00
return firewalld_commands
def check_haproxy_config(serv):
import sql
commands = [ "/sbin/haproxy -q -c -f %s" % sql.get_setting('haproxy_config_path') ]
ssh = ssh_connect(serv)
for command in commands:
stdin , stdout, stderr = ssh.exec_command(command)
if not stderr.read():
return True
else:
return False
2018-04-27 04:07:59 +00:00
ssh.close()
def show_log(stdout):
i = 0
for line in stdout:
i = i + 1
if i % 2 == 0:
2018-05-08 09:12:16 +00:00
print('<div class="line3">' + escape_html(line) + '</div>')
else:
2018-05-08 09:12:16 +00:00
print('<div class="line">' + escape_html(line) + '</div>')
2018-02-10 13:35:48 +00:00
def show_ip(stdout):
for line in stdout:
print(line)
2018-07-09 03:35:31 +00:00
def server_status(stdout):
2018-03-24 13:50:53 +00:00
proc_count = ""
2018-07-09 03:35:31 +00:00
for line in stdout:
2018-08-17 04:41:50 +00:00
if "Ncat: " not in line:
2018-07-09 03:35:31 +00:00
for k in line:
proc_count = k.split(":")[1]
else:
proc_count = 0
2018-08-01 08:06:09 +00:00
return proc_count
def ssh_command(serv, commands, **kwargs):
2018-01-26 07:36:01 +00:00
ssh = ssh_connect(serv)
2018-02-10 13:35:48 +00:00
2018-01-15 06:16:04 +00:00
for command in commands:
2018-02-06 09:14:08 +00:00
try:
stdin, stdout, stderr = ssh.exec_command(command)
except:
continue
2018-02-07 04:39:42 +00:00
if kwargs.get("ip") == "1":
show_ip(stdout)
2018-02-17 17:20:30 +00:00
elif kwargs.get("show_log") == "1":
show_log(stdout)
2018-02-17 17:20:30 +00:00
elif kwargs.get("server_status") == "1":
2018-02-07 04:39:42 +00:00
server_status(stdout)
elif kwargs.get('print_out'):
print(stdout.read().decode(encoding='UTF-8'))
2018-02-06 04:39:43 +00:00
else:
2018-08-01 08:06:09 +00:00
return stdout.read().decode(encoding='UTF-8')
print(stderr.read().decode(encoding='UTF-8'))
2018-05-08 09:12:16 +00:00
try:
ssh.close()
except:
print(ssh)
pass
2018-02-23 17:37:59 +00:00
2018-05-08 09:12:16 +00:00
def escape_html(text):
return cgi.escape(text, quote=True)
def subprocess_execute(cmd):
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
stdout, stderr = p.communicate()
output = stdout.splitlines()
return output, stderr
2018-08-01 08:06:09 +00:00
def show_backends(serv, **kwargs):
import json
2018-08-17 04:41:50 +00:00
import sql
haproxy_sock_port = sql.get_setting('haproxy_sock_port')
cmd='echo "show backend" |nc %s %s' % (serv, haproxy_sock_port)
output, stderr = subprocess_execute(cmd)
2018-08-01 08:06:09 +00:00
ret = ""
for line in output:
if "#" in line or "stats" in line:
continue
if line != "":
back = json.dumps(line).split("\"")
2018-08-01 08:06:09 +00:00
if kwargs.get('ret'):
ret += back[1]
ret += "<br />"
else:
print(back[1]+"<br>")
if kwargs.get('ret'):
return ret
2018-07-16 04:52:43 +00:00
2018-08-09 12:11:10 +00:00
def get_files(**kwargs):
2018-07-16 04:52:43 +00:00
import glob
file = set()
return_files = set()
2018-08-09 12:11:10 +00:00
if kwargs.get('dir'):
dir = kwargs.get('dir')
else:
dir = get_config_var('configs', 'haproxy_save_configs_dir')
if kwargs.get('format'):
format = kwargs.get('format')
else:
format = 'cfg'
2018-07-16 04:52:43 +00:00
2018-08-09 12:11:10 +00:00
for files in glob.glob(os.path.join(dir,'*.'+format)):
file.add(files.split('/')[-1])
2018-07-16 04:52:43 +00:00
files = sorted(file, reverse=True)
2018-08-09 12:11:10 +00:00
if format == 'cfg':
for file in files:
ip = file.split("-")
if serv == ip[0]:
return_files.add(file)
return sorted(return_files, reverse=True)
else:
return files
2018-07-25 15:57:42 +00:00