|
定时监测服务器端口,然后将结果入写数据库。
监测用NC命令,入库就用PYTHON的MYSQL模块
再调一个基于函数的多线程。。。
妥妥的。。
是网上两个功能的合成。。
俺不生产代码,俺只是BAIDU的搬运工!
#!/usr/bin/env python
import multiprocessing
import subprocess
import MySQLdb
host_list = []
for line in open("/xxx/data_ip_port"):
host_list.append(line.strip('\n'))
if len(host_list) > 10:
process_number = 10
else:
process_number = len(host_list)
def insert_mysql(sql_str):
try:
conn=MySQLdb.connect(host='xxxx',user='xxxx',passwd=xxxxxxx',db='xxxx',port=xxxx)
cur=conn.cursor()
cur.execute(sql_str)
cur.close()
conn.commit()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
def ping_host(ipaddr):
if subprocess.call('nc -vz -w 2 %s > /dev/null' % ipaddr, shell=True) == 0:
print '%s is OK' % ipaddr
ip = ipaddr.split()[0]
port = int(ipaddr.split()[1])
sqlstr = "INSERT INTO monitor_crawler (ip,port,status) VALUES ('%s',%d,0)" % (ip, port)
insert_mysql(sqlstr)
else:
print '%s is DOWN' % ipaddr
ip = ipaddr.split()[0]
port = int(ipaddr.split()[1])
sqlstr = "INSERT INTO monitor_crawler (ip,port,status) VALUES ('%s',%d,1)" % (ip, port)
insert_mysql(sqlstr)
pool = multiprocessing.Pool(processes=process_number)
for ip in host_list:
pool.apply_async(ping_host,(ip,))
pool.close()
pool.join()
|
|
|