-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_device_status.py
130 lines (107 loc) · 4.36 KB
/
check_device_status.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
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
import sqlite3
import datetime
import socket
import threading
import queue
import time
import sys
path_to_db = r"/home/admin/collect_config/db.sqlite3"
start = datetime.datetime.now()
print("\n========================================\r\n"
"{0}\r\n"
"===========================================\n".format(start))
def TcpConnect(ip, telnet_port=23, ssh_port=22):
"""Check availability telnet or ssh"""
# print("Start check available device port 22-23")
session = socket.socket()
session.settimeout(2)
result = session.connect_ex((ip, ssh_port))
session.close()
# print("Result connect SSH {0}".format(result))
if result == 0:
print('Device: {0} OK'.format(ip))
status = 'OK'
else:
session = socket.socket()
session.settimeout(2)
result = session.connect_ex((ip, telnet_port))
session.close()
# print("Result connect Telnet {0}".format(result))
if result == 0:
print('Device: {0} OK'.format(ip))
status = 'OK'
else:
print('Device {0} unreachable'.format(ip))
status = 'Unreachable'
return status
def update_data_in_database(device_id, old_status, status):
date_added = datetime.datetime.now()
""" Для каждого потока требуется свое подключение к базе, нельязя использовать одно подключения,
которое создано ранее"""
if status != old_status:
try:
con = sqlite3.connect(path_to_db, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
# print('Connect to db sucess')
except sqlite3.Error as e:
print("Error connect to DB: {0}".format(e))
cur = con.cursor()
cur.execute(
'UPDATE collect_configs_device SET status = ?, date_last_change_state = ? WHERE Id = ?',
(status, date_added, device_id)
)
con.commit()
print(cur.lastrowid)
con.close()
else:
pass
def check_status_device(work_queue):
"""Device status check"""
while True:
# Если заданий нет - закончим цикл
if work_queue.empty():
sys.exit()
# Получаем задание из очереди
i = work_queue.get()
# print('DEVICE: ', i)
# из строки вида xx.xx.xx.xx;11;OK получаем массив в котором содержится ip adress, device id, OK
# разделяя строку по ";"
data = i.split(";")
ip = data[0]
device_id = int(data[1])
old_status = data[2]
status = TcpConnect(ip, telnet_port=23, ssh_port=22)
update_data_in_database(device_id, old_status, status)
# Сообщаем о выполненном задании
work_queue.task_done()
# print(u'Очередь: %s завершилась' % i)
try:
con = sqlite3.connect(path_to_db, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
# print('Connect sucess')
# print(con)
except sqlite3.Error as e:
print("Error connect to DB: {0}".format(e))
cur = con.cursor()
cur.execute('SELECT * FROM collect_configs_device')
res = cur.fetchall()
con.close()
work_queue = queue.Queue() # Создаем FIFO очередь
for i in res:
print('\n============== {0} - {1} - {2} - {3} ==================='.format(i[0], i[1], i[10], i[11]))
ip = i[1]
device_id = int(i[0])
old_status = i[11]
"""Заполняем очеред строками, состоящими из ip, device_id, old_status"""
work_queue.put('{0};{1};{2}'.format(ip, device_id, old_status))
# Создаем и запускаем потоки, которые будут обслуживать очередь
for i in range(7):
# print(u'Поток', str(i), u'стартовал')
# print("kolichestvo activnyh potokov: ", threading.activeCount())
t1 = threading.Thread(target=check_status_device, args=(work_queue,))
t1.setDaemon(True)
t1.start()
time.sleep(0.1)
work_queue.join() # Ставим блокировку до тех пор пока не будут выполнены все задания
end = datetime.datetime.now()
print("Lead time: {0}".format(end-start))