1 Star 0 Fork 0

wly496/pingsvr

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
pingsvr.py 2.02 KB
一键复制 编辑 原始数据 按行查看 历史
wly496 提交于 2021-11-09 22:21 . v1.0
#coding:utf-8
import sys
import threading
import sqlite3
from ping3 import ping
import time
def ping_host(ip):
"""
获取节点的延迟的作用
:param node:
:return:
"""
ip_address = ip
response = ping(ip_address,ttl=128)
if response is not None:
delay = float(response * 1000)
return {'result':'OK','average':delay,'ip':ip,'lost':0}
else :
delay=100
return {'result':'ERROR','average':delay,'ip':ip,'lost':100}
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
def main(ips):
messages={}
threads={}
for ip in ips:
# 循环 实例化2个Thread类,传递函数及其参数,并将线程对象放入一个列表中
t = MyThread(ping_host, (ip,), 'thread_'+ip)
threads[ip] = t
t.start() # 循环 开始线程
for ip in threads.keys():
threads[ip].join() # 循环 join()方法可以让主线程等待所有的线程都执行完毕。
messages[ip] = threads[ip].get_result()
print(ip,messages[ip])
return messages
if __name__ == '__main__':
con=sqlite3.connect('./ping.db')
cur = con.cursor()
sql = "CREATE TABLE IF NOT EXISTS ping(host TEXT,ip TEXT,average FLOAT,lost FLOAT,time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
cur.execute(sql)
sql= "INSERT INTO ping (host,ip,average,lost) values ('%s','%s',%f,%f)"
try:
while True:
messages=main(sys.argv[1:])
time.sleep(1)
for ip in messages.keys():
cur.execute(sql%(ip,messages[ip]['ip'],messages[ip]['average'],messages[ip]['lost']))
con.commit()
except KeyboardInterrupt:
cur.close()
con.close()
print('terminated...')
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wly496/pingsvr.git
git@gitee.com:wly496/pingsvr.git
wly496
pingsvr
pingsvr
master

搜索帮助