-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheck_http_bak.py
More file actions
351 lines (293 loc) · 11.1 KB
/
Copy pathcheck_http_bak.py
File metadata and controls
351 lines (293 loc) · 11.1 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
FileName: check_http.py
Desc:
Author: 苦咖啡
Email: [email protected]
HomePage: http://blog.kukafei520.net
Version: 0.0.1
LastChange: 16/1/28 下午8:27
History:
"""
import sys, socket, select, struct, logging, smtplib, httplib, time, requests, urllib
import threading
from urlparse import urlparse
from email.MIMEText import MIMEText
import requests
from multiprocessing import Process, Queue, Pool
import os, time, random
# config
log_file_name = '%s.log' % sys.argv[0]
wx_message = []
monitor_api = "http://127.0.0.1:8000/api/monitor/http/"
url_timeout = 20
mailhost = 'mail.funshion.com'
mailpasswd = 'funshion321#@!'
mail_subject_prefix = '北京机房'
weixin_url = "http://127.0.0.1:8888/"
s = requests.get(monitor_api)
result = s.json()
url_list = result.get("retData")
logger = logging.getLogger()
hdlr = logging.FileHandler(log_file_name, 'w')
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
class HttpApi(threading.Thread):
# def __init__(self, **kwargs,url, ip, args):
def __init__(self, **kwargs):
threading.Thread.__init__(self)
self.data = kwargs
self.result = self.data.get("args")
self.url = self.data.get("url")
o = urlparse(self.url)
self.hostname = o.hostname
self.ip = self.data.get("ip")
self.payload = self.result.get("payload")
self.mail_status = self.result.get("mail_status")
self.mail = self.result.get("mail")
self.weixin_status = self.result.get("weixin_status")
self.weixin = self.result.get("weixin")
self.title = self.result.get("title")
self.result_code = self.result.get("result_code")
self.status = self.result.get("monitor_type")
if o.port:
self.port = o.port
else:
self.port = 80
if o.query == '':
if o.path == '':
self.request = '/'
self.path = '/'
else:
self.request = o.path
self.path = o.path
else:
self.request = o.path + '?' + o.query
self.path = o.path
def run(self):
try:
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
"Connection": "close",
"Accept-Encoding": "gzip, deflate",
"Host": self.hostname,
"Cache-Control": "no-cache",
}
http = httplib.HTTPConnection(self.ip, self.port, timeout=url_timeout)
if self.status:
params = urllib.urlencode(self.payload)
http.request("POST", self.request, params, headers)
else:
http.putrequest("GET", self.request, 1, 1)
http.putheader("User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36")
http.putheader("Connection", "close")
http.putheader("Accept-Encoding", "gzip, deflate")
http.putheader("Host", self.hostname)
http.putheader("Cache-Control", "no-cache")
http.endheaders() # endheaders()执行时才会开始建立尝试建立连接
r = http.getresponse()
if not r:
logger.error(
"%s-%s:%s Fatal Error: http.getresponse(), impossible? %s" % (
self.hostname, self.ip, self.port, self.title))
message = "%s %s:%s Response: '%s %s '%s" % (
self.hostname, self.ip, self.port, r.status, r.reason,
self.title)
if self.weixin_status:
send = SendWeixin(user=self.weixin, message=message)
send.push()
if r.status == 408:
logger.info("%s-%s:%s Response: '%s %s'" % (self.hostname, self.ip, self.port, r.status, r.reason))
elif r.status >= 400:
logger.error(
"%s%s-%s:%s Response: '%s %s' %s" % (
self.hostname, self.path, self.ip, self.port, r.status, r.reason,
self.title))
message = "%s %s:%s Response: '%s %s '%s" % (
self.hostname, self.ip, self.port, r.status, r.reason,
self.title)
if self.weixin_status:
send = SendWeixin(user=self.weixin, message=message)
send.push()
elif r.status == 301 or r.status == 302:
self.redirect = r.getheader('location')
logger.info("%s-%s:%s Response: '%s %s'. Location: %s" % (
self.hostname, self.ip, self.port, r.status, r.reason, self.redirect))
else:
logger.info("%s-%s:%s Response: '%s %s'" % (self.hostname, self.ip, self.port, r.status, r.reason))
message = "%s %s:%s Response: '%s %s '%s" % (
self.hostname, self.ip, self.port, r.status, r.reason,
self.title)
if self.weixin_status:
send = SendWeixin(user=self.weixin, message=message)
send.push()
except Exception, e:
logger.info("%s-%s:%s Fatal Error: %s" % (self.hostname, self.ip, self.port, e))
class WebServer(threading.Thread):
def __init__(self, **kwargs):
threading.Thread.__init__(self)
self.data = kwargs
self.url = self.data.get("url")
self.ips = self.data.get("ips")
self.args = self.data.get("args")
# 以下代码可将当前dns解析vip一同加入检测
"""
try:
addrs = socket.getaddrinfo(urlparse(self.url).hostname, 'http', socket.AF_INET, socket.SOCK_STREAM)
except Exception, e:
logger.error("%s-%s, need check dns server." % (urlparse(self.url).hostname, e))
addrs = []
for addr in addrs:
ip = addr[4][0]
if ip in self.ips:
pass
else:
self.ips.append(ip)
"""
def run(self):
threads = []
# 每个ip建立一个线程
for ip in self.ips:
g = HttpApi(url=self.url, ip=ip, args=self.args)
threads.append(g)
# 依次启动所有线程
for thread in threads:
thread.start()
# 等待所有线程退出
for thread in threads:
thread.join()
class Mail(object):
def __init__(self, filename, subject_prefix=''):
self.fromaddr = mailuser
self.toaddrs = ''
self.mailtype = 'ALL'
self.filename = filename
self.subject = ''
self.wxmessage = ''
self.subject_prefix = subject_prefix
def sendmail(self, toaddrs, mailtype):
f = open("%s" % self.filename, 'r')
text = f.readlines()
f.close()
message = ''
if mailtype == 'ERROR':
error_num = 0
for line in text:
if line.find('ERROR') >= 0:
message += line
error_num += 1
wx_message.append(line)
self.subject = '%s服务异常!%s/%s' % (self.subject_prefix, error_num, len(text))
else:
self.subject = '%s服务检查日志: %s' % (self.subject_prefix, len(text))
for line in text:
message += line
msg = MIMEText(message)
msg['From'] = self.fromaddr
msg['To'] = ','.join(toaddrs)
msg['Subject'] = self.subject
if len(message) != 0:
try:
server = smtplib.SMTP(mailhost)
server.login(mailuser, mailpasswd)
server.sendmail(self.fromaddr, toaddrs, msg.as_string())
server.quit()
except Exception, e:
logger.error(e)
class SendWeixin(object):
def __init__(self, **kwargs):
self.user = kwargs.get("user")
self.message = kwargs.get("message")
def push(self):
data = {
"user": self.user,
"message": self.message,
"token": "8d7e1693e9ad674f645b87032a66169a"
}
rst = requests.post(weixin_url, data=data)
print rst.json()
return True
def sendmail():
# SendMail
m = Mail(log_file_name, mail_subject_prefix)
# m.sendmail(mail_error_to, 'ERROR')
class Web(threading.Thread):
def __init__(self, **kwargs):
threading.Thread.__init__(self)
self.data = kwargs
self.url = self.data.get("url")
self.ips = self.data.get("ip")
self.args = self.data.get("args")
def run(self):
threads = []
# 每个ip建立一个线程
for ip in self.ips:
g = HttpApi(url=self.url, ip=ip, args=self.args)
threads.append(g)
# 依次启动所有线程
for thread in threads:
thread.start()
# 等待所有线程退出
for thread in threads:
thread.join()
def main():
threads = []
for domains in url_list.keys():
ips = url_list[domains]["ip"]
for domain in url_list[domains]["url"]:
g = WebServer(url=domain, ips=ips, args=url_list[domains])
threads.append(g)
# 依次启动所有线程
for thread in threads:
thread.start()
# 等待所有线程退出
for thread in threads:
thread.join()
def write(q):
# for value in ['A', 'B', 'C']:
# print 'Put %s to queue...' % value
# q.put(value)
# time.sleep(random.random())
# threads = []
for domains in url_list.keys():
q.put(url_list[domains])
# ips = url_list[domains]["ip"]
# for domain in url_list[domains]["url"]:
# g = WebServer(url=domain, ips=ips, args=url_list[domains])
# threads.append(g)
#
# # 依次启动所有线程
# for thread in threads:
# thread.start()
#
# # 等待所有线程退出
# for thread in threads:
# thread.join()
# 读数据进程执行的代码:
def read(q):
while True:
value = q.get(True)
# print 'Get %s from queue.' % value
# print value.get("url")
test = Web(url=value.get("uuid"), ip=value.get("ip"), args=value)
test.run()
if __name__ == "__main__":
main()
# sendmail()
q = Queue(10)
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 启动子进程pr,读取:
pr.start()
# 等待pw结束:
pw.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()