Python 用心跳(UDP包)探测不活动主机

计算机周期性的发送一个代表心跳的UDP包到服务器,服务器跟踪每台计算机在上次发送心跳之后尽力的时间并报告那些沉默时间太长的计算机。

客户端程序:HeartbeatClient.py

""" 心跳客户端,周期性的发送 UDP包 """

import socket, time

SERVER_IP = '192.168.0.15'; SERVER_PORT = 43278; BEAT_PERIOD = 5

print'Sending heartbeat to IP %s , port %d' % (SERVER_IP, SERVER_PORT)

print'press Ctrl-C to stop'

whileTrue:

hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

hbSocket.sendto('PyHB', (SERVER_IP, SERVER_PORT))

if _ _debug_ _:

print'Time: %s' % time.ctime( )

time.sleep(BEAT_PERIOD)

服务器程序接受ing跟踪“心跳”,她运行的计算机的地址必须和“客户端”程序中的 SERVER_IP一致。服务器必须支持并发,因为来自不同的计算机的心跳可能会同时到达。一个服务器有两种方法支持并发:多线程和异步操作。下面是一个多线程的ThreadbearServer.py,只使用了python标准库中的模块:

""" 多线程 heartbeat 服务器"""

import socket, threading, time

UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15

class Heartbeats(dict):

""" Manage shared heartbeats dictionary with thread locking """

def _ _init_ _(self):

super(Heartbeats, self)._ _init_ _( )

self._lock = threading.Lock( )

def _ _setitem_ _(self, key, value):

""" Create or update the dictionary entry for a client """

self._lock.acquire( )

try:

super(Heartbeats, self)._ _setitem_ _(key, value)

finally:

self._lock.release( )

def getSilent(self):

""" Return a list of clients with heartbeat older than CHECK_TIMEOUT """

limit = time.time( ) - CHECK_TIMEOUT

self._lock.acquire( )

try:

silent = [ip for (ip, ipTime) inself.items( ) if ipTime < limit]

finally:

self._lock.release( )

return silent

class Receiver(threading.Thread):

""" Receive UDP packets and log them in the heartbeats dictionary """

def _ _init_ _(self, goOnEvent, heartbeats):

super(Receiver, self)._ _init_ _( )

self.goOnEvent = goOnEvent

self.heartbeats = heartbeats

self.recSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

self.recSocket.settimeout(CHECK_TIMEOUT)

self.recSocket.bind(('', UDP_PORT))

def run(self):

whileself.goOnEvent.isSet( ):

try:

data, addr = self.recSocket.recvfrom(5)

if data == 'PyHB':

self.heartbeats[addr[0]] = time.time( )

except socket.timeout:

pass

def main(num_receivers=3):

receiverEvent = threading.Event( )

receiverEvent.set( )

heartbeats = Heartbeats( )

receivers = [ ]

for i in range(num_receivers):

receiver = Receiver(goOnEvent=receiverEvent, heartbeats=heartbeats)

receiver.start( )

receivers.append(receiver)

print'Threaded heartbeat server listening on port %d' % UDP_PORT

print'press Ctrl-C to stop'

try:

whileTrue:

silent = heartbeats.getSilent( )

print'Silent clients: %s' % silent

time.sleep(CHECK_PERIOD)

except KeyboardInterrupt:

print'Exiting, please wait...'

receiverEvent.clear( )

for receiver in receivers:

receiver.join( )

print'Finished.'

if _ _name_ _ == '_ _main_ _':

main( )

作为备选方案,线面给出异步的AsyBeatserver.py程序,这个程序接住了强大的twisted的力量:

import time

from twisted.application import internet, service

from twisted.internet import protocol

from twisted.python import log

UDP_PORT = 43278; CHECK_PERIOD = 20; CHECK_TIMEOUT = 15

class Receiver(protocol.DatagramProtocol):

""" Receive UDP packets and log them in the "client"s dictionary """

def datagramReceived(self, data, (ip, port)):

if data == 'PyHB':

self.callback(ip)

class DetectorService(internet.TimerService):

""" Detect clients not sending heartbeats for too long """

def _ _init_ _(self):

internet.TimerService._ _init_ _(self, CHECK_PERIOD, self.detect)

self.beats = { }

def update(self, ip):

self.beats[ip] = time.time( )

def detect(self):

""" Log a list of clients with heartbeat older than CHECK_TIMEOUT """

limit = time.time( ) - CHECK_TIMEOUT

silent = [ip for (ip, ipTime) inself.beats.items( ) if ipTime < limit]

log.msg('Silent clients: %s' % silent)

application = service.Application('Heartbeat')

# define and link the silent clients' detector service

detectorSvc = DetectorService( )

detectorSvc.setServiceParent(application)

# create an instance of the Receiver protocol, and give it the callback

receiver = Receiver( )

receiver.callback = detectorSvc.update

# define and link the UDP server service, passing the receiver in

udpServer = internet.UDPServer(UDP_PORT, receiver)

udpServer.setServiceParent(application)

# each service is started automatically by Twisted at launch time

log.msg('Asynchronous heartbeat server listening on port %d\n'

'press Ctrl-C to stop\n' % UDP_PORT)

python心跳包原理_Python 用心跳(UDP包)探测不活动主机相关推荐

  1. python scapy模块安装_Python scapy网络包嗅探模块(转载)

    1.窃取Email认证 1.1创建一个简单的嗅探器,捕获一个数据包,packet.show()函数解析了其中的协议信息并输出了包的内容. from scapy.all import * def pac ...

  2. python模块包教学_python模块和包

    模块和包 模块和包并不是新的语法,而是python中为了更好地对代码进行分块组织管理,所提供的一种代码规范.他们根据代码的功能将区别不大的代码放在一起管理,使大型程序的设计更加醒目,层次更加清晰. 1 ...

  3. python抓包拦截_python实现抓包、解析流程,超过瘾!

    importosimportdpktimportsocketimportdatetimeimportuuidfrom scapy.sendrecv importsnifffrom scapy.util ...

  4. 扯一扯HTTPS单向认证、双向认证、抓包原理、反抓包策略

    HTTP(HyperText Transfer Protocol,超文本传输协议)被用于在Web浏览器和网站服务器之间传递信息,在TCP/IP中处于应用层.这里提一下TCP/IP的分层共分为四层:应用 ...

  5. python程序的原理_Python程序的执行原理(转)

    1. 过程概述 Python先把代码(.py文件)编译成字节码,交给字节码虚拟机,然后虚拟机一条一条执行字节码指令,从而完成程序的执行. 2. 字节码 字节码在Python虚拟机程序里对应的是PyCo ...

  6. 简述python程序执行原理_Python程序的执行原理(1)

    test.py的指令序列 func函数的指令序列 第一列表示以下几个指令在py文件中的行号; 第二列是该指令在指令序列co_code里的偏移量; 第三列是指令opcode的名称,分为有操作数和无操作数 ...

  7. python解析器原理_Python程序运行原理图文解析

    本文研究的主要是Python程序运行原理,具体介绍如下. 编译型语言(C语言为例) 动态型语言 一个程序是如何运行起来的?比如下面的代码 #othermodule.py def add(a, b): ...

  8. python编写student类_Python艺术编程节——以趣味活动促进学生学习编程

    陈斌 近年来,Python逐渐成为最热门的计算机编程语言之一,如何开展Python语言的编程教学也成为了计算机基础教育领域的热门话题.面向中小学生的编程教学尤其需要激发并培养学生的学习兴趣.因此,在针 ...

  9. python pip工具命令_python 工具链 包管理工具 pip

    Installation mac下可以采用 brew,easy_install(python自带)等方式安装. centos下可以采用yum,easy_install等方式安装. 但是上面两种方式在系 ...

最新文章

  1. HDU1040简单排序题
  2. IIS上.Net 扩展中进行恢复
  3. php文件锁解锁是删除对应的文件_软件 | 文件解锁强制删除工具 Wise Force Deleter v1.49...
  4. 【转】Windows Server 2012 R2 双网卡绑定
  5. 关于solaris中 crontab -e 出现数字0的解决办法
  6. mysql随机姓名_mysql 随机生成姓名函数,及模拟大量测试数据
  7. python绘图苹果_如何使用python代码画一个苹果?
  8. 最好用的mac屏幕分辨率修改器:SwitchResX for Mac
  9. 渗透函数实现排序的函数层次聚类或者叫做凝
  10. exls表格搜索快捷键_excel表格快捷键大全_如何在EXCEL表格中快速查找
  11. 每日英语:Etiquette Catches On in China, Even in Government
  12. R语言 交互式绘图echarts4r包Pictorial深探
  13. C语言调试教程总结(以visual studio和Dev C++为例)
  14. java npv_java 实现Excel irr计算(改进版)
  15. r7 6800u核显相当于什么显卡
  16. 可编程中控 c 语言,LG-PGMIII可编程中控
  17. MySQL中的聚簇索引、非聚簇索引、联合索引和唯一索引
  18. 讨论 | 博士延期毕业?如何避免?
  19. Python——IDLE的安装步骤
  20. 内鬼黑客狂卖个人信息 “年产值”飙上千亿

热门文章

  1. [debug] “ImportError DLL load failed 找不到指定的程序”的解析和解决办法。
  2. k8s prometheus/grafana 监控系统建设
  3. Python: SystemError: Unknown opcode
  4. jsp java代码报错,求助!JSP代码中调java服务出参返回正常 weblogic报错BEA-101017
  5. 20145202马超《网络对抗》Exp8 Web基础
  6. 软件测试:homework2
  7. 通俗易懂JSONP讲解
  8. Asp.net MVC 搭建属于自己的框架(一)
  9. Oracle logmnr使用
  10. Android 如何才能捕获系统的恢复出厂设置事件