diff --git a/.idea/workspace.xml b/.idea/workspace.xml index ae1c5fc..97cf2a0 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,14 +2,20 @@ - - - + + + - + + - - + + + + + + + @@ -155,25 +160,29 @@ - - - - + + + + - + @@ -409,6 +431,7 @@ + @@ -421,7 +444,6 @@ - @@ -438,7 +460,8 @@ - @@ -447,22 +470,6 @@ - - - - - - - - - - - - - - - - @@ -484,11 +491,11 @@ - - - - - + + + + + @@ -498,8 +505,7 @@ - - + @@ -533,7 +539,7 @@ - + @@ -543,11 +549,11 @@ - - - - - + + + + + @@ -557,8 +563,7 @@ - - + @@ -584,11 +589,11 @@ - - - - - + + + + + @@ -598,8 +603,7 @@ - - + @@ -625,11 +629,11 @@ - - - - - + + + + + @@ -639,8 +643,7 @@ - - + @@ -666,11 +669,11 @@ - - - - - + + + + + @@ -680,8 +683,7 @@ - - + @@ -699,11 +701,11 @@ - - - - - + + + + + @@ -713,8 +715,7 @@ - - + @@ -724,11 +725,11 @@ - - - - - + + + + + @@ -746,8 +747,7 @@ - - + @@ -757,11 +757,11 @@ - - - - - + + + + + @@ -779,8 +779,7 @@ - - + @@ -790,11 +789,11 @@ - - - - - + + + + + @@ -804,8 +803,7 @@ - - + @@ -815,11 +813,11 @@ - - - - - + + + + + @@ -829,11 +827,11 @@ - - - - - + + + + + @@ -852,42 +850,82 @@ - + - - + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - + - - + + - + - + + + + + + + + + @@ -900,66 +938,41 @@ - + - - - - - + + + - + - - - - - - + + + - + - - + + - - - - - + - - + + - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SetupMinersClass.py b/SetupMinersClass.py index 8ae41bf..a434ee5 100644 --- a/SetupMinersClass.py +++ b/SetupMinersClass.py @@ -32,7 +32,7 @@ class SSHSetup: def send(self, command): self.ssh.send(command + '\n') time.sleep(1) - print(self.ssh.recv(10000).decode()) + self.ssh.recv(10000).decode() def sendall(self, commlist=[]): for command in commlist: @@ -61,15 +61,15 @@ class TelnetSetup: self.close() def login(self): - print(self.tn.read_until(b'login:')) + self.tn.read_until(b'login:') self.tn.write(self.user.encode('utf8') + b'\n') - print(self.tn.read_until(b'Password:')) + self.tn.read_until(b'Password:') self.tn.write(self.passwd.encode('utf8') + b'\n') self.tn.read_until(self.user.encode('utf8')) def send(self, command): self.tn.write(command.encode('utf8') + b'\n') - print(self.tn.read_until(self.user.encode('utf8')).decode('utf8')) + self.tn.read_until(self.user.encode('utf8')) def sendall(self, comlist=[]): for command in comlist: @@ -84,22 +84,27 @@ class SetupMiner: self.host = host self.conf = conf if len(telnets) == 0: - self.telnets = ["uname -a", "ps -A", "exit"] + self.telnets = ["exit"] else: self.telnets = telnets if len(sshs) == 0: - self.sshs = ["uname -a", "ps -A", "exit"] + self.sshs = ["exit"] else: self.sshs = sshs try: TelnetSetup(self.host, self.conf['telnetport'], self.conf['telnetuser'], self.conf['telnetpass'], self.telnets) + self.result = "telnet OK; " except Exception as exc: - print(exc) + self.result = "{}; ".format(exc) try: SSHSetup(self.host, self.conf['sshport'], self.conf['sshuser'], conf['sshpass'], self.sshs) + self.result += '\n ssh OK' except Exception as exc: - raise exc + self.result += '\n {}; '.format(exc) + + def ret_result(self): + return self.result def read_conf(): @@ -117,10 +122,8 @@ def main(): "telnetpass": conf["telnetpass"], "telnetport": conf["telnetport"]} comlist = ["uname -a", "ps -A", "exit"] - try: - SetupMiner('10.100.0.48', minerconf) - except Exception as exc: - print(exc) + s = SetupMiner('10.100.4.10', minerconf) + print(s.result) if __name__ == '__main__': diff --git a/sshs.json b/commands/sshs.json similarity index 100% rename from sshs.json rename to commands/sshs.json diff --git a/telnets.json b/commands/telnets.json similarity index 100% rename from telnets.json rename to commands/telnets.json diff --git a/kea_host_wacher.py b/kea_host_wacher.py index 5f03830..88bfdff 100644 --- a/kea_host_wacher.py +++ b/kea_host_wacher.py @@ -81,15 +81,12 @@ def main(): seen_list.append(seen_h['id_1c_import']) for online_host in online_hosts: if online_host['1c_id'] in seen_list: - # print('need to update host 1c_id = %s' % online_host['1c_id']) update_seen(qupdate_last_seen, online_host['1c_id'], *dbconf) elif online_host not in seen: - # print('need to add host 1c_id = %s' % online_host['1c_id']) update_seen(qinsert_last_seen, online_host['1c_id'], *dbconf) seen = read_table(qselect_last_seen, *dbconf) for seen_host in seen: if seen_host['datetime'] < (datetime.datetime.now() - datetime.timedelta(minutes=1)): - # print('need to remove host 1c_id = %s' % seen_host['id_1c_import']) update_hosts(qdelete_host, seen_host['id_1c_import'], *dbconf) update_seen(qdelete_last_seen, seen_host['id_1c_import'], *dbconf) diff --git a/kea_hosts_generane.py b/kea_hosts_generane.py index 1a34a56..e48079e 100644 --- a/kea_hosts_generane.py +++ b/kea_hosts_generane.py @@ -2,8 +2,6 @@ # coding=utf-8 -import time -import paramiko import MySQLdb import json from SetupMinersClass import SetupMiner @@ -48,6 +46,38 @@ qinsert_hosts = "START TRANSACTION; " \ qupdate_1c = "update 1c_import set imported = 1 where serial = '%s';" +class ConfigClass: + def __init__(self): + self.conffile = 'config.json' + self.sshsfile = 'commands/sshs.json' + self.telnetsfile = 'commands/telnets.json' + self.config = list + self.minerconf = dict + self.dbconf = dict + self.sshs = list + self.telnets = list + + def read_json(self, file): + with open(file) as f: + conf = json.load(f) + return conf + + def readall(self): + conf = self.read_json(self.conffile) + self.sshs = self.read_json(self.sshsfile) + self.telnets = read_conf(self.telnetsfile) + self.minerconf = {"sshuser": conf["sshuser"], + "sshpass": conf["sshpass"], + "sshport": conf["sshport"], + "telnetuser": conf["telnetuser"], + "telnetpass": conf["telnetpass"], + "telnetport": conf["telnetport"]} + self.dbconf = {"dbhost": conf['dbhost'], + "dbuser": conf['dbuser'], + "dbpass": conf['dbpass'], + "dbbase": conf['dbbase']} + + def read_table(sql, dbhost, dbuser, dbpass, dbbase): try: conn = MySQLdb.connect(host=dbhost, user=dbuser, @@ -124,11 +154,8 @@ def read_conf(file): def main(): conf = read_conf('config.json') - sshs = read_conf('sshs.json') - telnets = read_conf('telnets.json') - print(sshs) - print(telnets) - telnets = read_conf('telnets.json') + sshs = read_conf('commands/sshs.json') + telnets = read_conf('commands/telnets.json') minerconf = {"sshuser": conf["sshuser"], "sshpass": conf["sshpass"], "sshport": conf["sshport"], diff --git a/tpl/a_add_hosts.tpl b/tpl/a_add_hosts.tpl new file mode 100644 index 0000000..ec144bb --- /dev/null +++ b/tpl/a_add_hosts.tpl @@ -0,0 +1,16 @@ + + + DHCP web-viewer + + + +

Таблица импорта обновлена.

+Если устройства не перезагружены автоматически, это необходимо сделать вручную.
+Лог действий:

+%for a in A: +{{a}}
+

+%end +Назад + + \ No newline at end of file diff --git a/tpl/add_hosts.tpl b/tpl/add_hosts.tpl new file mode 100644 index 0000000..a4ab7b5 --- /dev/null +++ b/tpl/add_hosts.tpl @@ -0,0 +1,40 @@ + + + DHCP web-viewer + + + + отчет по хостам в статическом адресном пространстве
+ отчет по занятым хостам в динамическом адресном пространстве +

Добавление хостов

+

+
+ + + + + + + + + + + + + %i = 0 + %for a in A: + %i = i + 1 + + + + + + + + + %end + +
Таблица аренды динамических адресов
Дата истеченияIP адресMac адресИмя хостаНовое имя№ сетиИмпортировать
{{a[0]}}{{a[1]}}{{a[2]}}{{a[3]}}
+
+ + diff --git a/tpl/hosts.tpl b/tpl/hosts.tpl index ce14040..5a64173 100644 --- a/tpl/hosts.tpl +++ b/tpl/hosts.tpl @@ -7,7 +7,7 @@ отчет по занятым хостам в динамическом адресном пространстве

Статические адреса



-
+ diff --git a/tpl/import_hosts.tpl b/tpl/import_hosts.tpl deleted file mode 100644 index 589e47d..0000000 --- a/tpl/import_hosts.tpl +++ /dev/null @@ -1,26 +0,0 @@ - - - DHCP web-viewer - - - -

Таблица импорта обновлена.

-Если устройства не перезагружены автоматически, это необходимо сделать вручную. -
Таблица аренды статических адресов
- - - - - - - %for a in A: - - - - - %end - -
Добавленные хосты
IP адресMac адресИмя хоста
{{a[0]}}{{a[1]}}{{a[2]}}
-Назад - - \ No newline at end of file diff --git a/tpl/main.tpl b/tpl/main.tpl index e98573d..79b5d6f 100644 --- a/tpl/main.tpl +++ b/tpl/main.tpl @@ -4,10 +4,11 @@ - отчет по хостам в статическом адресном пространстве + отчет по хостам в статическом адресном пространстве
+ Добавление хостов

Динамические адреса



- + @@ -16,9 +17,7 @@ - - - + %i = 0 %for a in A: @@ -28,9 +27,7 @@ - - - + %end
Таблица аренды динамических адресов
IP адрес Mac адрес Имя хостаНовое имя№ сетиИмпортироватьПерезагрузить
{{a[1]}} {{a[2]}} {{a[3]}}
diff --git a/tpl/reboot_hosts.tpl b/tpl/reboot_hosts.tpl new file mode 100644 index 0000000..1538644 --- /dev/null +++ b/tpl/reboot_hosts.tpl @@ -0,0 +1,15 @@ + + + DHCP web-viewer + + + +

Хосты перезагружены.

+Если устройства не перезагружены автоматически, это необходимо сделать вручную.
+ Лог операций:

+%for a in A: +{{a}}
+

+Назад + + \ No newline at end of file diff --git a/tpl/remove_hosts.tpl b/tpl/remove_hosts.tpl index db99a5c..513b597 100644 --- a/tpl/remove_hosts.tpl +++ b/tpl/remove_hosts.tpl @@ -6,6 +6,6 @@

Хосты удалены.

Если устройства в сети, их нужно перезагрузить вручную. -Назад +Назад \ No newline at end of file diff --git a/web-leases.py b/web-leases.py index 9fb0935..4c6066b 100644 --- a/web-leases.py +++ b/web-leases.py @@ -1,29 +1,17 @@ #!/usr/bin/python3 # coding=utf-8 -from bottle import route, run, static_file, template, post, request -import json +from bottle import route, run, template, post, request import MySQLdb - - -def read_conf(): - with open('config.json') as f: - conf = json.load(f) - return conf - - -@route('/static/') -def server_static(filepath): - return static_file(filepath, root='/home/mix/PycharmProjects/kea_for_miners/static/') +from SetupMinersClass import SetupMiner +from kea_hosts_generane import ConfigClass +import kea_hosts_generane @route('/') def server_homepage(): - conf = read_conf() - dbhost = conf['dbhost'] - dbuser = conf['dbuser'] - dbpass = conf['dbpass'] - dbbase = conf['dbbase'] + conf = ConfigClass() + conf.readall() sql = "SELECT " \ " expire, " \ " INET_NTOA(address) as ip4, " \ @@ -32,9 +20,10 @@ def server_homepage(): " FROM lease4 " \ "where INET_NTOA(address) like '%.%.0.%'" \ " ORDER BY expire DESC;" + print(conf.dbconf) try: - conn = MySQLdb.connect(host=dbhost, user=dbuser, - passwd=dbpass, db=dbbase) + conn = MySQLdb.connect(host=conf.dbconf['dbhost'], user=conf.dbconf['dbuser'], + passwd=conf.dbconf['dbpass'], db=conf.dbconf['dbbase']) except MySQLdb.Error as err: print("Connection error: {}".format(err)) conn.close() @@ -53,12 +42,57 @@ def server_homepage(): @post('/') +def reboot_hosts(): + conf = ConfigClass() + conf.readall() + i = 1 + data = [] + while request.POST.get("reboot_%s" % i, default=False): + hostname = request.POST.getall('reboot_%s' % i) + print(hostname) + sm = SetupMiner(hostname[0], conf.minerconf, telnets=['/sbin/reboot'], sshs=['/sbin/reboot']) + print(sm.result) + data.append("host {} log : {}".format(hostname, sm.result)) + i += 1 + return template('tpl/reboot_hosts.tpl', A=data) + + +@route('/add_hosts') +def server_add_hosts(): + conf = ConfigClass() + conf.readall() + sql = "SELECT " \ + " expire, " \ + " INET_NTOA(address) as ip4, " \ + " HEX(hwaddr)as hw_addr, " \ + " hostname " \ + " FROM lease4 " \ + "where INET_NTOA(address) like '%.%.0.%'" \ + " ORDER BY expire DESC;" + try: + conn = MySQLdb.connect(host=conf.dbconf['dbhost'], user=conf.dbconf['dbuser'], + passwd=conf.dbconf['dbpass'], db=conf.dbconf['dbbase']) + except MySQLdb.Error as err: + print("Connection error: {}".format(err)) + conn.close() + try: + cur = conn.cursor(MySQLdb.cursors.DictCursor) + cur.execute(sql) + data = cur.fetchall() + except MySQLdb.Error as err: + print("Query error: {}".format(err)) + conn.close() + data_list = [] + for row in data: + temp = [row['expire'], row['ip4'], row['hw_addr'], row['hostname']] + data_list.append(temp) + return template('tpl/add_hosts.tpl', A=data_list) + + +@post('/add_hosts') def adding_hosts(): - conf = read_conf() - dbhost = conf['dbhost'] - dbuser = conf['dbuser'] - dbpass = conf['dbpass'] - dbbase = conf['dbbase'] + conf = ConfigClass() + conf.readall() s_select = "SELECT " \ " expire, " \ " INET_NTOA(address) as ip4, " \ @@ -75,34 +109,30 @@ def adding_hosts(): hostname = request.POST.getall('hostname_%s' % i) print(request.POST.getall('hostname_%s' % i)) if len(hostname) == 3: - data.append(request.POST.getall('hostname_%s' % i)) try: - conn = MySQLdb.connect(host=dbhost, user=dbuser, - passwd=dbpass, db=dbbase) + conn = MySQLdb.connect(host=conf.dbconf['dbhost'], user=conf.dbconf['dbuser'], + passwd=conf.dbconf['dbpass'], db=conf.dbconf['dbbase']) except MySQLdb.Error as err: - print("Connection error: {}".format(err)) + data.append("connection error: {}
".format(err)) conn.close() try: cur = conn.cursor(MySQLdb.cursors.Cursor) - print(s_insert % tuple(hostname)) - cur.execute(s_insert % tuple(hostname)) + sql = s_insert % tuple(hostname) + cur.execute(sql) conn.commit() + data.append("host {} proceed with request : {}
".format(hostname[0], sql)) except MySQLdb.Error as err: - print("Query error: {}".format(err)) + data.append("host {} Query error: {}
".format(hostname[0], err)) conn.close() - i += 1 - - return template('tpl/import_hosts.tpl', A=data) + kea_hosts_generane.main() + return template('tpl/a_add_hosts.tpl', A=data) -@route('/hosts/') +@route('/hosts') def server_hosts_repo(): - conf = read_conf() - dbhost = conf['dbhost'] - dbuser = conf['dbuser'] - dbpass = conf['dbpass'] - dbbase = conf['dbbase'] + conf = ConfigClass() + conf.readall() sql = "SELECT " \ "INET_NTOA(hosts.ipv4_address) AS ip4," \ " hosts.hostname," \ @@ -116,8 +146,8 @@ def server_hosts_repo(): " dhcp_identifier = hwaddr " \ "ORDER BY ip4;" try: - conn = MySQLdb.connect(host=dbhost, user=dbuser, - passwd=dbpass, db=dbbase) + conn = MySQLdb.connect(host=conf.dbconf['dbhost'], user=conf.dbconf['dbuser'], + passwd=conf.dbconf['dbpass'], db=conf.dbconf['dbbase']) except MySQLdb.Error as err: print("Connection error: {}".format(err)) conn.close() @@ -130,7 +160,7 @@ def server_hosts_repo(): conn.close() data_list = [] for row in data: - temp = [] + temp = list() temp.append(row['ip4']) temp.append(row['hostname']) temp.append(row['hw_addr']) @@ -139,20 +169,16 @@ def server_hosts_repo(): return template('tpl/hosts.tpl', A=data_list) -@post('/hosts/') +@post('/hosts') def remove_host(): - conf = read_conf() - dbhost = conf['dbhost'] - dbuser = conf['dbuser'] - dbpass = conf['dbpass'] - dbbase = conf['dbbase'] + conf = ConfigClass() s_remove1c = "delete from 1c_import where replace(hw_addr, ':', '') = '%s';" s_removehost = "delete from hosts where dhcp_identifier = unhex('%s');" hosts_del = request.forms.getall('remove_host') del_1c = request.forms.getall('remove_import') try: - conn = MySQLdb.connect(host=dbhost, user=dbuser, - passwd=dbpass, db=dbbase) + conn = MySQLdb.connect(host=conf.dbconf['dbhost'], user=conf.dbconf['dbuser'], + passwd=conf.dbconf['dbpass'], db=conf.dbconf['dbbase']) except MySQLdb.Error as err: print("Connection error: {}".format(err)) conn.close()