-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatk_bot.py
executable file
·3968 lines (3628 loc) · 194 KB
/
atk_bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import traceback
import sys
import requests
import telebot
import os
import logging
import time
import re
import mysql.connector
import psycopg2
import gspread
from configparser import ConfigParser
from datetime import date, datetime, timezone
from contextlib import closing
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from pexpect import pxssh
from bs4 import BeautifulSoup
from pyzabbix import ZabbixAPI
from telebot import types
request_num = {}
request_str = {}
request = {}
multiple_zabbix_host = {}
multiple_op_host = {}
multiple_zabbix_graphs = {}
zabbix_num = {}
zabbix_hosts = {}
zabbix_graphs = {}
multiple_odf = {}
multiple_odf_num = {}
#грузим всё из конфига
config = ConfigParser()
config.read('config.ini')
bot_id = config.get('id', 'bot')
login = config.get('id', 'login')
password = config.get('id', 'password')
password2 = config.get('id', 'password2')
save_dir = config.get('vars', 'save_dir')
user_agent_val = config.get('vars', 'user_agent_val')
wait_time = int(config.get('vars', 'wait_time'))
access_list = dict(config.items('access_list'))
zabbix_host = config.get('zabbix', 'zabbix_host')
zabbix_login = config.get('zabbix', 'login')
zabbix_password = config.get('zabbix', 'password')
zabbix_domain = config.get('zabbix', 'zabbix_domain')
zabbix_graph_width = config.get('zabbix', 'width')
zabbix_graph_height = config.get('zabbix', 'height')
cam_login = config.get('cam', 'login')
cam_password = config.get('cam', 'password')
selenium_server = config.get('selenium', 'server')
selenium_username = config.get('selenium', 'username')
selenium_usernamecross = config.get('selenium', 'usernamecross')
selenium_password = config.get('selenium', 'password')
selenium_mo = config.get('selenium', 'mo')
selenium_it = config.get('selenium', 'it')
selenium_oe = config.get('selenium', 'oe')
selenium_root = config.get('selenium', 'root')
selenium_root_cross = config.get('selenium', 'root_cross')
selenium_cross_search = config.get('selenium', 'cross_search')
ping_hostname = config.get('ping', 'hostname')
ping_username = config.get('ping', 'username')
ping_password = config.get('ping', 'password')
google_oe = config.get('id', 'google_oe')
google_it = config.get('id', 'google_it')
log_chat_id = config.get('id', 'log')
sw_pass = config.get('id', 'sw_pass')
cacti_login = config.get('id', 'cacti_login')
cacti_password = config.get('id', 'cacti_password')
graph_port = config.get('id', 'graph_port')
url = {
'root_url': config.get('url', 'root_url'),
'ref_url_ref': config.get('url', 'ref_url_ref'),
'cookie': config.get('url', 'cookie'),
'host': config.get('url', 'host'),
'auth_page': config.get('url', 'auth_page'),
'search_url': config.get('url', 'search_url'),
'cacti_auth': config.get('url', 'cacti_auth'),
'cacti_search': config.get('url', 'cacti_search'),
'cacti': config.get('url', 'cacti'),
}
netdb_vars = {
'host': config.get('mysql_netdb', 'host'),
'user': config.get('mysql_netdb', 'login'),
'password': config.get('mysql_netdb', 'password'),
'database': config.get('mysql_netdb', 'database')
}
contacts = {
'oe1': config.get('contacts', 'oe1'),
'oe2': config.get('contacts', 'oe2'),
'oe3': config.get('contacts', 'oe3'),
'oe4': config.get('contacts', 'oe4'),
'oe5': config.get('contacts', 'oe5'),
'oe6': config.get('contacts', 'oe6'),
'it1': config.get('contacts', 'it1'),
'it2': config.get('contacts', 'it2'),
'it3': config.get('contacts', 'it3'),
'it4': config.get('contacts', 'it4'),
'it5': config.get('contacts', 'it5'),
'it6': config.get('contacts', 'it6'),
'it7': config.get('contacts', 'it7'),
'it8': config.get('contacts', 'it8'),
}
bazadb_vars = {
'host': config.get('mysql_baza', 'host'),
'user': config.get('mysql_baza', 'login'),
'password': config.get('mysql_baza', 'password'),
'database': config.get('mysql_baza', 'database')
}
etraxisdb_vars = {
'host': config.get('mysql_etraxis', 'host'),
'user': config.get('mysql_etraxis', 'login'),
'password': config.get('mysql_etraxis', 'password'),
'database': config.get('mysql_etraxis', 'database')
}
pg_atk_bot_vars = {
'host': config.get('pg_atk_bot', 'host'),
'user': config.get('pg_atk_bot', 'login'),
'password': config.get('pg_atk_bot', 'password'),
'database': config.get('pg_atk_bot', 'database')
}
#включаем логи в файл и в stdout
logging.basicConfig(filename=os.path.basename(sys.argv[0]) + '.log', \
level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
try:
bot = telebot.TeleBot(bot_id)
zapi = ZabbixAPI(zabbix_host)
zapi.login(zabbix_login, zabbix_password)
except Exception as e:
print (e)
msg = traceback.format_exc()
print (msg)
sys.exit(0)
#отлавливаем ошибки и постим в тележный канал под логи
def error_capture(**kwargs):
options = {
'e' : None,
'message' : None,}
options.update(kwargs)
e = options.get('e')
message = options.get('message')
if e is not None:
print (e)
msg = traceback.format_exc()
try:
bot.send_message(log_chat_id, msg)
except:
msg = '! telebot error log msg not send. ' + msg
if message is not None:
try:
bot.reply_to(message, e)
except:
pass
logging.error(msg)
try:
gc = gspread.service_account()
sh_oe = gc.open_by_url(google_oe)
sh_it = gc.open_by_url(google_it)
except Exception as e:
error_capture(e=e)
#каждую команду пишем в лог для истории запросов, включая неавторизованные
def cmd_log(message, auth):
_chat_id = str(message.chat.id)
_lng = ''
_username = ''
_first_name = ''
_last_name = ''
_title = ''
_user_id = str(message.from_user.id)
_language_code = ''
if _user_id != _chat_id:
_chat_id = _chat_id + ', from user id: ' + _user_id
if (message.chat.type == 'group' or message.chat.type == 'supergroup' \
or message.chat.type == 'channel'):
if message.chat.title is not None:
_title = message.chat.title
else:
_title = 'private message'
if message.from_user.username is not None:
_username = message.from_user.username
if message.from_user.last_name is not None:
_last_name = message.from_user.last_name
if message.from_user.first_name is not None:
_first_name = message.from_user.first_name
if message.from_user.language_code is not None:
_language_code = message.from_user.language_code
msg = 'request from chat id: ' + _chat_id + ', chat name: ' + _title \
+ ', username: @' + _username + ', first name: ' + _first_name \
+ ', last name: ' + _last_name + ', language code: ' \
+ _language_code + '. REQUEST: ' + message.text
if auth:
logging.info(msg)
else:
msg = '‼️ UNAUTORIZED ' + msg
logging.warning(msg)
bot.send_message(log_chat_id, msg)
#ищем в базе id здания
def search_ids(street, house):
bazadb = bazadb_connect()
cur = bazadb.cursor(buffered=True)
if house == '%':
_sql = """select b.id from buildings b
join streets s on s.id = b.street_id
where s.name like %s;"""
cur.execute(_sql, (street, ))
else:
_sql = """select b.id from buildings b
join streets s on s.id = b.street_id
where s.name like %s
and b.number like %s;"""
cur.execute(_sql, (street, house))
result = cur.fetchall()
cur.close()
bazadb.close()
return result
#постим графики трафика юриков
def jur_graph(args, message):
jid = 'Network traffic on jur' + str(args)
records = ''
conn = psycopg2.connect(dbname='zabbix', \
user='postgres', \
host='172.16.0.246')
cursor = conn.cursor()
_sql = """select graphid from graphs
where name = %s limit 1;"""
cursor.execute(_sql, (str(jid), ))
records = cursor.fetchall()
cursor.close()
conn.close()
if records:
h = zapi.host.get(search={'host': 'r-jurs'}, output=['hostid'])
_id = h[0].get('hostid')
_gid = str(records[0])[1:-2]
_name = save_dir + 'jur.png'
zabbix_get_graph(_name, _gid)
img = open(_name, 'rb')
bot.send_photo(message.chat.id, img)
img.close()
else:
bot.reply_to(message, "Нет такого графика юрика")
return
#ищем графики в заббиксе, захардкожен диапазон -- 3 дня
def zabbix_get_graph(n, gid):
h = zabbix_host + '/chart2.php?graphid=' + gid \
+ '&from=now-3d&to=now&profileIdx=web.graphs.filter&width=' \
+ zabbix_graph_width + '&height=' + zabbix_graph_height
f = open(n, "wb")
s = requests.Session()
r = s.get(zabbix_host, headers={'User-Agent': user_agent_val})
cookie = s.cookies.get('zbx_session', domain=zabbix_domain )
s.headers.update({'Referer': zabbix_host})
p = s.post(zabbix_host + '/index.php?login=1', {
'name': zabbix_login,
'password': zabbix_password,
'enter': 'Enter'
})
r = s.get(h, headers={'User-Agent': user_agent_val})
r.close()
f.write(r.content)
f.close()
#проверка на русский алфавит
def match(text, alphabet=set('абвгдеёжзийклмнопрстуфхцчшщъыьэюя')):
return not alphabet.isdisjoint(text.lower())
#достаём из базы инфу по коммутатору на основе id здания
def find_switch_by_address(args):
#return [[switch 1 of street 1, switch 2 of street 1], [switch 1 of street 2], [...]]
result = []
def search_vars(street_id):
netdb = netdb_connect()
cur = netdb.cursor(buffered=True)
_sql = ("""select c.name, c.status, c.address, c.comments, c.ip, str.city from commutators as c
join net.buildings as b on (c.building_id = b.id)
join net.streets as str on (str.id = b.street_id)
where c.building_id = %s""")
cur.execute(_sql, (street_id,))
result = cur.fetchall()
cur.close()
netdb.close()
return result
if match(args):
if args.find(', ') != -1:
house = ' '.join(args.split(', ')[-1:])
street = ' '.join(args.split(', ')[:-1])
if house.find('?') != -1:
house = house[:-1]
_ids = search_ids(street + '%', house + '%')
else:
_ids = search_ids(street + '%', house)
if _ids is not None:
result = []
for key in _ids:
result.append(search_vars(key[0]))
elif args.find(' ') != -1:
house = args.split(' ')[1]
street = args.split(' ')[0]
if house.find('?') != -1:
house = house[:-1]
_ids = search_ids(street + '%', house + '%')
else:
_ids = search_ids(street + '%', house)
if _ids is not None:
result = []
for key in _ids:
result.append(search_vars(key[0]))
else:
street = args
_ids = search_ids(street + '%', '%')
if _ids is not None:
result = []
for key in _ids:
result.append(search_vars(key[0]))
else:
result = []
name = args
netdb = netdb_connect()
cur = netdb.cursor(buffered=True)
_sql = ("""select name, status, address, comments, ip
from commutators where name like %s""")
cur.execute(_sql, (name + '%', ))
result.append(cur.fetchall())
cur.close()
netdb.close()
result = [x for x in result if x]
return result
#статус коммутаторов
def switch_status(args, message):
result = ''
_streets = find_switch_by_address(args)
_status = '❓'
if _streets is not None:
result = '💚 up, 💔 down, 🤍 stock\n\n'
for switches in _streets:
for key in switches:
if key[1] == "up":
_status = "💚 "
elif key[1] == "down":
_status = "💔 "
elif key[1] == "stock":
_status = "🤍 "
if key[0][:2] == ('A-') or key[0][:4] == ('MIK-'):
result += _status + key[0] + ' ' + key[2] + ' ' + key[3] + '\n'
else:
result += _status + key[0] + ' ' + key[4] + '\n'
send_msg_with_split(message, result, 4000)
#подключаемся к локальной базе, нужна для определения привязки по районам
def pg_connect():
# pg = psycopg2.connect(
pg = mysql.connector.connect(
host = pg_atk_bot_vars.get('host'),
user = pg_atk_bot_vars.get('user'),
password = pg_atk_bot_vars.get('password'),
# dbname = pg_atk_bot_vars.get('database')
database = pg_atk_bot_vars.get('database')
)
return pg
#база трекера
def etraxisdb_connect():
etraxisdb = mysql.connector.connect(
host = etraxisdb_vars.get('host'),
user = etraxisdb_vars.get('user'),
password = etraxisdb_vars.get('password'),
database = etraxisdb_vars.get('database')
)
return etraxisdb
#база коммутаторов
def netdb_connect():
netdb = mysql.connector.connect(
host = netdb_vars.get('host'),
user = netdb_vars.get('user'),
password = netdb_vars.get('password'),
database = netdb_vars.get('database')
)
return netdb
#схемы, здания
def bazadb_connect():
bazadb = mysql.connector.connect(
host = bazadb_vars.get('host'),
user = bazadb_vars.get('user'),
password = bazadb_vars.get('password'),
database = bazadb_vars.get('database')
)
return bazadb
#от малышева
def check_comm_aviability(ip):
netdb = netdb_connect()
#Получаем id коммутатора
comm_cur = netdb.cursor(buffered=True)
comm_cur.execute("select id from commutators where ip = %s", (ip, ))
comm_res = comm_cur.fetchall()
comm_cur.close()
netdb.close()
return len(comm_res)
#свободные порты в коммутаторах
def free_ports(message, args):
def fnd(ip):
netdb = netdb_connect()
comm_cur = netdb.cursor(buffered=True)
_sql =("""select id from commutators
where ip = %s""")
comm_cur.execute(_sql, (ip, ))
comm_res = comm_cur.fetchone()
comm_cur.close()
comm_cur = netdb.cursor(buffered=True)
comm_id = comm_res[0]
_sql =("""select p.number from net.ports p left outer
join UTM5.ip_groups g on p.commutator_id = g.switch_id
and p.number = g.port_id
where p.commutator_id = %s
and p.type = 'empty'
and g.account_id is null
and (p.comment = '' or p.comment is null)
order by p.number""")
comm_cur.execute(_sql, (str(comm_id), ))
rez = comm_cur.fetchall()
comm_cur.close()
netdb.close()
return rez
ip = check_IPV4(args)
if ip:
if check_comm_aviability(ip) > 0:
msg = "Свободные порты на коммутаторе " + ip + ":\n"
port_res = fnd(ip)
for port in port_res :
msg = msg + str(port[0]) + ", "
bot.reply_to(message, msg[:-2])
else:
bot.reply_to(message, "Коммутатора с ip адресом: " + ip + " нет в базе.")
else:
bot.reply_to(message, "Неправильный ip адрес.")
#ищем все схемы
def get_scheme(args, message, stype):
result = []
def link(street_id, stype):
bazadb = bazadb_connect()
cur = bazadb.cursor(buffered=True)
if stype != 'drs':
stype = '%'
_sql = """select CONCAT('https://atk.is/schemes/',
i.building_id, '/',
i.date_upd, '.',
i.fext) as link
from buildings b
join building_image i on b.id = i.building_id
join streets s on s.id = b.street_id
where b.id = %s and i.type like %s;"""
cur.execute(_sql, (street_id, stype))
_link = cur.fetchall()
_sql = """select i.title from buildings b
join building_image i on b.id = i.building_id
join streets s on s.id = b.street_id
where b.id = %s and i.type like %s;"""
cur.execute(_sql, (street_id, stype))
_name = cur.fetchall()
_sql = """select CONCAT(s.name, ' ', b.number) from buildings b
join building_image i on b.id = i.building_id
join streets s on s.id = b.street_id
where b.id = %s and i.type like %s;"""
cur.execute(_sql, (street_id, stype))
_address = cur.fetchall()
cur.close()
bazadb.close()
result = {'link': _link, 'name': _name, 'address': _address}
return result
if match(args):
if args.find(', ') != -1:
house = ' '.join(args.split(', ')[-1:])
street = ' '.join(args.split(', ')[:-1])
_ids = search_ids(street + '%', house)
if _ids is not None:
for street_id in _ids:
result.append(link(street_id[0], stype))
elif args.find(' ') != -1:
house = args.split(' ')[1]
street = args.split(' ')[0]
_ids = search_ids(street + '%', house)
if _ids is not None:
for street_id in _ids:
result.append(link(street_id[0], stype))
else:
name = args
netdb = netdb_connect()
cur = netdb.cursor(buffered=True)
_sql = ("""select name, status, address, comments, ip
from commutators where name like %s""")
cur.execute(_sql, (name + '%', ))
res = cur.fetchall()
cur.close()
netdb.close()
if res:
args = res[0][2]
if args.find(' ') != -1:
house = args.split(' ')[1]
street = args.split(' ')[0]
_ids = search_ids(street + '%', house)
if _ids is not None:
for street_id in _ids:
result.append(link(street_id[0], stype))
if result:
files = []
_name = []
_link = []
_address = []
for b in result:
lnk = b.get('link')
name = b.get('name')
address = b.get('address')
for k in range(len(lnk)):
_link.append(str(lnk[k]).replace('\'','')[1:-2])
for k in range(len(name)):
_name.append(str(name[k]).replace('\'','')[1:-2])
for k in range(len(address)):
_address.append(str(address[k]).replace('\'','')[1:-2])
_sum = [list(tup) for tup in zip(_name, _link, _address)]
for key in _sum:
if (key[1][-3:]) != 'vsd':
n = key[2] + ' (' + key[0] + ')' + key[1][-4:]
n = n.replace('/','-')
write_scheme(save_dir + 'scheme/' + n, key[1])
files.append(save_dir + 'scheme/' + n)
if (len(files) == 0):
bot.reply_to(message, "Нет файлов")
else:
count = len(files) // 10
bot.reply_to(message, "Файлов нашлось: " + str(len(files)))
for x in range(count + 1):
bot.send_media_group(message.chat.id, [telebot.types.InputMediaDocument(open(doc, 'rb')) for doc in files[x*10:x*10+10]])
time.sleep(wait_time)
else:
msg = "Ничего не нашлось."
bot.reply_to(message, msg)
return result
#инфа по зданию
def get_house_info(args, message):
res = ''
if match(args):
if args.find(', ') != -1:
house = ' '.join(args.split(', ')[-1:])
street = ' '.join(args.split(', ')[:-1])
_ids = search_ids(street + '%', house)
if _ids:
bazadb = bazadb_connect()
cur = bazadb.cursor(buffered=True)
street_id = _ids[0][0]
_sql = """select description, key_name from buildings b
join streets s on s.id = b.street_id
where b.id = %s;"""
cur.execute(_sql, (street_id,))
res = cur.fetchall()
cur.close()
bazadb.close()
_info = ''
_keys = ''
if res[0][0]:
_info = res[0][0]
if res[0][1]:
_keys = res[0][1]
if len(res) == 0:
res = '?'
elif len(res[0][0]) == 0:
res = '?'
else:
res = street + ', ' + house + '\n' + _info + '\n\n' + _keys
else:
res = '?'
else:
if args.find(' ') != -1:
street = args.split(' ')[0]
house = args.split(' ')[1]
_ids = search_ids(street + '%', house)
if _ids:
bazadb = bazadb_connect()
cur = bazadb.cursor(buffered=True)
street_id = _ids[0][0]
_sql = """select description, key_name from buildings b
join streets s on s.id = b.street_id
where b.id = %s;"""
cur.execute(_sql, (street_id,))
res = cur.fetchall()
_info1 = res[0][0]
_info2 = res[0][1]
if not _info1:
_info1 = ''
if not _info2:
_info2 = ''
res = street + ', ' + house + '\n' + _info1 + '\n\n' + _info2
cur.close()
bazadb.close()
else:
res = '?'
else:
res = "?"
else:
name = args
netdb = netdb_connect()
cur = netdb.cursor(buffered=True)
_sql = ("""select name, status, address, comments, ip
from commutators where name like %s""")
cur.execute(_sql, (name + '%', ))
res = cur.fetchall()
cur.close()
netdb.close()
args = res[0][2]
house = args.split(' ')[1]
street = args.split(' ')[0]
if args.find(' ') != -1:
_ids = search_ids(street + '%', house)
if _ids:
bazadb = bazadb_connect()
cur = bazadb.cursor(buffered=True)
street_id = _ids[0][0]
_sql = """select description, key_name from buildings b
join building_image i on b.id = i.building_id
join streets s on s.id = b.street_id
where b.id = %s;"""
cur.execute(_sql, (street_id,))
res = cur.fetchall()
if len(res) == 0:
res = '?'
elif len(res[0][0]) == 0:
res = '?'
else:
res = street + ', ' + house + '\n' + res[0][0] + '\n\n' + res[0][1]
else:
res = '?'
cur.close()
bazadb.close()
else:
res = "?"
msg = ""
if (res != "" and res != "?"):
msg = res
else:
msg = "Ничего не нашлось."
send_msg_with_split(message, msg, 4000)
#проверяем доступность команды для определённого чата
def check_command_allow(message, command):
full_cmd = access_list.get('command_list').split()
chat_id = message.chat.id
_auth = False
if command in full_cmd:
for key in access_list:
access = access_list.get(key).split()
if (str(chat_id) == key) and command in access:
_auth = True
cmd_log(message, _auth)
return _auth
#от малышева
def check_IPV4(ip):
def isIPv4(s):
try: return str(int(s)) == s and 0 <= int(s) <= 255
except: return False
if ip.count(".") == 3 and all(isIPv4(i) for i in ip.split(".")):
return ip
elif ip.count(".") == 1 and all(isIPv4(i) for i in ip.split(".")):
return "10.254." + ip
else:
return False
#отрезали команду, оставили всё остальное
def extract_arg(arg):
return arg.split(maxsplit=1)[1:]
#оставили команду, отрезали всё остальное
def get_command(arg):
return arg.split(' ', 1)[0]
#стартуем сессию для парсинга плд, притворяемся браузером, логинимся
def start_session():
s = requests.Session()
r = s.get(url.get('root_url'), headers={'User-Agent': user_agent_val})
cookie = s.cookies.get(url.get('cookie'), domain=url.get('host'))
s.headers.update({'Referer':url.get('ref_url_ref')})
s.headers.update({'User-Agent':user_agent_val})
r = s.get(url.get('auth_page'), headers={'User-Agent': user_agent_val})
p = s.post(url.get('auth_page'), {
'sectok': '',
'id': 'start',
'do': 'login',
'u': login,
'p': password,
'r': 1
})
return s
#стартуем сессию для кактуса, на данный момент нереализовано, можно выпилить
def start_cacti_session():
s = requests.Session()
r = s.get(url.get('cacti_auth'), headers={'User-Agent': user_agent_val})
#cookie = s.cookies.get(url.get('cookie'), domain=url.get('host'))
s.headers.update({'Referer':url.get('cacti_auth')})
s.headers.update({'User-Agent':user_agent_val})
r = s.get(url.get('cacti_auth'), headers={'User-Agent': user_agent_val})
p = s.post(url.get('cacti_auth'), {
'action': 'login',
'login_username': cacti_login,
'login_password': cacti_password,
})
return s
#поиск страничек в вики с плд
def search_pages(arg):
s = start_session()
r = s.get(url.get('search_url') + arg, \
headers={'User-Agent': user_agent_val})
c = r.content
soup = BeautifulSoup(c,'lxml')
svars = {}
for var in soup.findAll('a', class_="wikilink1"):
svars[var['title']] = var['href']
num = 0
msg = ""
for key in svars:
num += 1
key = key.replace('corp:pld:', '').replace('_', ' ')
key = key.replace('corp:','').replace('pld1:', '').replace('it:', '')
key = key.replace('tp:', '')
msg += "➡️ " + str(num) + " " + key + "\n"
msg = "Нашлось совпадений: " + str(num) + "\n\n" + msg
r.close()
return msg, num, svars
#это нужно скрестить с парсингом файлов
def search_files(arg):
s = s = start_session()
r = s.get(url.get('root_url') + arg, \
headers={'User-Agent': user_agent_val})
c = r.content
r.close()
return c
#получаем урл файла
def get_file(arg):
s = start_session()
r = s.get(url.get('root_url') + arg, \
headers={'User-Agent': user_agent_val})
r.close()
return r
#сохраняем файл на диск
def write_file(n, h):
f = open(n, "wb")
r = get_file(h)
f.write(r.content)
f.close()
#сохраняем схему на диск
def write_scheme(n, h):
s = requests.Session()
r = s.get('https://atk.is/', headers={'User-Agent': user_agent_val})
f = open(n, "wb")
r = s.get(h, headers={'User-Agent': user_agent_val})
f.write(r.content)
f.close()
r.close()
#поиск файлов на страничках с плд
def parse_pdf(arg):
files = []
soup = BeautifulSoup(arg,'lxml')
for var in soup.findAll('a', class_="media mediafile mf_pdf"):
n = var["title"]
h = var['href']
n = ('.pdf'.join(n.split('.pdf')[:-1]) + '.pdf')
n = n.replace('corp', '').replace('pld', '')
n = n.replace('corp:pld:', '').replace('_', ' ').replace('corp:','')
n = n.replace('pld1:', '').replace('it:', '').replace('tp:', '')
n = n.replace('/', '').replace('\\', '').replace(':', '')
path = (save_dir) + 'pld/' + n
write_file(path, h)
files.append(path)
return files
#получаем картинку с камер хиквижн и хайвотч
def send_camera_image(args, message):
ip = check_IPV4(args)
if ip:
link = 'http://' + cam_login + ':' + cam_password + '@' + ip \
+ '/ISAPI/Streaming/channels/101/picture/'
imageFile = save_dir + 'cams/' + ip + "_" \
+ str(datetime.timestamp(datetime.now())) + '.jpg'
os.system('wget '+link+' -O '+imageFile)
if os.path.getsize(imageFile) > 0:
img = open(imageFile, 'rb')
bot.send_photo(message.chat.id, img, caption = ip)
else:
link = 'http://' + cam_login + ':' + cam_password + '@' + ip \
+ '/cgi-bin/snapshot.cgi'
imageFile = save_dir + 'cams/' + ip + "_" \
+ str(datetime.timestamp(datetime.now())) + '.jpg'
os.system('wget '+link+' -O '+imageFile)
if os.path.getsize(imageFile) > 0:
img = open(imageFile, 'rb')
bot.send_photo(message.chat.id, img, caption = ip)
else:
bot.reply_to(message, "Изображение недоступно")
else:
bot.reply_to(message, "Неправильный ip.")
#график МО, разрешение экрана захардкожено!
def send_mo(message):
try:
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Remote(command_executor=selenium_server, \
options=chrome_options)
driver.set_window_size(1400, 600)
driver.get(selenium_root)
driver.find_element(By.ID, "login").send_keys(selenium_username)
driver.find_element(By.ID, "pwd").send_keys(selenium_password)
driver.find_element(By.ID, "loginButton").click()
driver.get(selenium_mo)
timeout = 60
try:
element_present = EC.presence_of_element_located((By.ID, \
'ws-canvas-graphic-overlay'))
WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
pass
finally:
time.sleep(2)
html_source = driver.page_source
driver.save_screenshot(save_dir + "screenshot.png")
driver.quit()
file = open(save_dir + 'screenshot.png', 'rb')
bot.send_photo(message.chat.id, file)
file.close()
except Exception as e:
error_capture(e=e, message=message)
try:
driver.quit()
bot.reply_to(message, e)
except:
pass
#график ИТ/ЦУС, разрешение экрана захардкожено!
def send_it(message):
send_work_graph("it", message)
#график ОЭ, разрешение экрана захардкожено!
def send_oe(message):
send_work_graph("oe", message)
def send_work_graph(type, message):
try:
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Remote(command_executor=selenium_server, options=chrome_options)
if type == "oe":
driver.set_window_size(1500, 1000)
driver.get(selenium_oe)
elif type == "it":
driver.set_window_size(1400, 500)
driver.get(google_it)
timeout = 60
try:
element_present = EC.presence_of_element_located((By.ID, 'goog-inline-block grid4-inner-container'))
WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
pass
finally:
time.sleep(1)
html_source = driver.page_source
driver.save_screenshot(save_dir + "screenshot.png")
driver.quit()
file = open(save_dir + 'screenshot.png', 'rb')
bot.send_photo(message.chat.id, file)
file.close()
except Exception as e:
error_capture(e=e, message=message)
try:
driver.quit()
bot.reply_to(message, e)
except:
pass
#поиск по карте оптики, самая жрущая ресурсы хрень, тут костыль на костыле, тайминги подстроены под быстродействие конкретного тазика
def send_map(message, text):
try:
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--incognito")
driver = webdriver.Remote(command_executor=selenium_server, options=chrome_options)
driver.set_window_size(1200, 910)
driver.get(selenium_root_cross)
timeout = 3
try:
element_present = EC.presence_of_element_located((By.ID, 'loginform'))
WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
pass
finally:
driver.find_element(By.NAME, "Login").send_keys(selenium_usernamecross)
driver.find_element(By.NAME, "Password").send_keys(selenium_password)
driver.find_element(By.NAME, "enter").click()
timeout = 3
try:
element_present = EC.presence_of_element_located((By.ID, 'loginform'))
WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
pass
except Exception as e:
error_capture(e=e, message=message)
finally:
driver.find_element(By.NAME, "SelectZone").click()
driver.get(selenium_cross_search)
timeout = 80