本文共 5073 字,大约阅读时间需要 16 分钟。
在本项目中主要实现了一个基于SNMP协议的手动监控客户端存活时间的系统。该系统由客户端和服务器端各一个脚本组成,通过SNMP协议完成通信。以下是系统的设计与实现步骤。
设计并实现一个手动监控客户端存活时间的系统,能够实时追踪每个客户端与服务器之间的通信状态及时间间隔,确保客户端服务的稳定性。
datetime
模块来计算客户端的存活时间间隔。snmpclenit.py
#!/usr/bin/python-- coding:utf-8 --import sockethost, port = '192.168.72.130', 18000s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((host, port))s.send('up')s.close()
snmpserver.py
#!/usr/bin/python-- coding:utf-8 --import datetimeimport pickleimport socketfrom socketserver import threading# 定义pickle文件pfile = 'h_dic.pkl'# 打开白名单文件读取IP地址with open('celie.txt') as f: for line in f: host = line.strip() host_status[host] = []class MyMonitorHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(1024) if not data: return client_ip = self.client_address[0] # 验证IP是否为本机IP if client_ip == '192.168.72.130': # 写入pickle文件 with open(pfile, 'w') as f: pickle.dump(host_status, f) print(f"写入文件:{pfile}") else: # 检查是否在白名单中 if client_ip in host_status: # 添加或更新时间 current_time = datetime.datetime.now() # 检查是否有存在可用的数据 if host_status[client_ip]: last_time = host_status[client_ip][-1][0] time_diff = (current_time - last_time).seconds print(f"From {client_ip}:第(t).{time_diff}秒") else: print(f"From {client_ip}:第一次连接") # 添加新的记录 host_status[client_ip].append((current_time, data.decode())) print(f"From {client_ip}:成功接收数据:{data.decode()}") else: print(f"抱歉,IP {client_ip} 不在白名单中。")if __name__ == "__main__": host, port = '192.168.72.130', 18000 # 创建TCPServer并设置多线程处理 server = SocketServer.ThreadingTCPServer((host, port), MyMonitorHandler) server.serve_forever()
socketserver
创建服务器,监听指定端口。MyMonitorHandler
处理收到的数据。host_status
字典。m_handle.py
#!/usr/bin/python-- coding:utf-8 --import socketfrom datetime import datetimeimport pickleimport sysdef trigger_dump(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, port)) s.send('up') s.close() except Exception as e: print(f"连接错误:{str(e)}")trigger_dump('192.168.72.130', 18000)# 读取目录下的celie.txt文件并添加到白名单with open('celie.txt') as f: for line in f: host = line.strip() print(f"将{host}添加到白名单中。")# 遍历hibruccbolic.pkl中的存储数据f = file('h_dic.pkl', 'rb')try: host_status = pickle.load(f)except Exception as e: print(f"读取haha.pkl文件错误:{str(e)}") sys.exit(1)# 遍历字典,检测每个客户端的存活时间for h in host_status: m = host_status[h] if not m: print(f"无数据接收:{h}") continue old_time = m[-1][0] current_time = datetime.now() time_diff = (current_time - old_time).seconds if time_diff > 30: print(f"No data received from {h} for {time_diff} seconds, please check!") else: print(f"{h}:{time_diff}秒")if __name__ == '__main__': # 合并client.py脚本 if __name__ == '__main__': trigger_dump('192.168.72.130', 18000) # 运行处理脚本 # 需要用户指定目标IP地址 target_ip = sys.argv[1] if len(sys.argv) > 1 else None if target_ip: trigger_dump(host=target_ip, port=18000) # 执行主处理 with file('h_dic.pkl', 'rb') as f: host_status = pickle.load(f) for h, m in host_status.items(): if not m: continue old_time = m[-1][0] current_time = datetime.now() time_diff = (current_time - old_time).seconds if time_diff > 30: print(f"No data received from {h} for {time_diff} seconds, please check!") else: print(f"{h},{time_diff}秒")
trigger_dump
函数模拟客户端连接服务器发送"up"消息。将客户端脚本(snmpclenit.py)在相应的设备上运行:
./snmpclenit.py
确保脚本能够成功连接到服务器并发送"up"消息。
在服务器端运行服务器脚本(snmpserver.py):
python snmpserver.py 192.168.72.129
注意:IP地址应与celie.txt文件中的IP地址一致。
通过tail -f snmpserver.log
查看服务器端的日志输出,确保客户端连接成功并被正确记录。
运行处理脚本(m_handle.py),指定目标IP地址:
python m_handle.py 192.168.72.129
查看输出结果,确保能够正确计算客户端的存活时间,并识别超时情况。
部署上述脚本到相应的环境中,监控系统运行状态。定期检查h_dic.pkl
文件的大小和内容,确保数据存储正确。同时监控snmpserver.py
进程,确保其正常运行。
snmpserver.py
中的数据读写和处理逻辑,避免性能瓶颈。通过以上步骤,可以实现一个稳定、可靠的手动监控客户端存活时间的SNMP系统,确保网络设备和服务的稳定运行。
转载地址:http://bwhpz.baihongyu.com/