Tag: Hat COM scan writes except time fail long txt
Played Hostmonitor, the foreigner wrote very well. But not in accordance with national conditions, only mail suitable for sending.
Use Python today to write a program that automatically discovers ip,ping failure alarms. (and email alerts)
Previously written in Python, send mail directly to import.
#-*-Coding:utf-8-*-# ping for windowsimport osimport sysimport socketimport structimport selectimport timeimport Confi Gparserimport weixinimport mailclass getcfg (object):d EF __init__ (self,filename): self.filename=filenameself.cfg= Configparser.configparser () self.cfg.read (Self.filename) #self. Allip=self.cfg.items (' Allip ') self.retry= Self.cfg.get (' rule ', ' Retry ') self.timeout=self.cfg.get (' rule ', ' timeout ') self.reload=self.cfg.get (' rule ', ' next_ Check ') self.scan=self.cfg.items (' Scan_network ') Self.mailto=self.cfg.items (' Mail ', ' mail_to ') #发送邮件报警def SendMessage (Self,failip): Weixin.sendmessage (' @all ', ' ping%s failed. ' % failip) for Key,value in Self.mailto:mail.send (value, "ping%s failed."% failip, ' python ping fail ') #判断要扫描ipdef SCAN_NETW Ork (self): Self.scan.sort () allip=self.cfg.items (' Allip ') I=0while i < Len (self.scan): Ipbegin=int (self.scan[i][1) . Split ('. ') [-1]) Ipend=int (self.scan[i+1][1]) +1for x in range (ipbegin,ipend): Ipvalue=self.scan[i][1].split ('. ') [0]+ '. ' +self.scan[i][1].split ('. ') [1]+ '. ' +sElf.scan[i][1].split ('. ') [2]+ '. ' +STR (x) ip_dict=[]for k,v in Allip:ip_dict.append (v) if ipvalue in Ip_dict:passelse: #执行扫描self. to_ping (Ipvalue,int ( Self.timeout)) i=i+2# perform scan def to_ping (self,ip_addr,timeout):p rint ' scan ip ' + ip_addr,try:delay = ping (self.filename). Ping_once (IP_ADDR, timeout) if delay = = None:print ' failed. (Timeout within%s second.) ' % Timeoutelse:print ' Get reply in%0.4f ms '% (Delay *) Self.scan_resule (ip_addr) except Socket.gaierror, e:print "fail ed. (Socket Error: '%s ') "% e[1] #判断扫描结果, if a newly scanned IP is saved to the config file Def scan_resule (self,ip_addr): Allip=self.cfg.items (' Allip ' ) Ip_dict=[]for k,v in Allip:ip_dict.append (v) if ip_addr in Ip_dict:passelse:self.cfg_write (IP_ADDR) #保存扫描到的ip到配置文件def Cfg_write (self,ipvalue): ipkey= ' auto_ ' +str (Time.time ()) self.cfg.set (' Allip ', Ipkey,ipvalue) self.cfg.write (open (' Ping_monitor.txt ', ' W ')) #去执行ping类def to_ping (self): Allip=self.cfg.items (' Allip ') for k,v in Allip:if Len (v) >0:ping (Self.filename). Icmp_ping (V,int (self.timeout), int (self.retry)) #下次执行扫描时Between Def Next_check (self): while True:self.to_ping () print ('---------------------------------------------------------- --') Nextcheck=0while Nextcheck < int (self.reload): Sys.stdout.write (' Next check%s second\r '% (int (self.reload)- Nextcheck)) Sys.stdout.flush () time.sleep (1) nextcheck=nextcheck+1self.scan_network () print ('--------------------- ---------------------------------------') class Ping (object):d EF __init__ (self,filename): self. Icmp_echo_request = 8self.filename=filenamedef receive_ping (self,my_socket, ID, timeout): Start_time = Timeoutwhile True:start_select = Time.clock () What_ready = Select.select ([My_socket], [], [], start_time) How_long = (Time.clock ()-STA Rt_select) if what_ready[0] = = []: #timeoutreturntime_received = Time.clock () rec_packet, addr = My_socket.recvfrom (1024) Icmp_header = rec_packet[20:28]ip_type, code, checksum, packet_id, sequence = Struct.unpack ("Bbhhh", Icmp_header) if ip_t Ype! = 8 and packet_id = = ID: # ip_type should be 0byte_in_double = Struct.calcsize ("D") time_Sent = Struct.unpack ("D", rec_packet[28:28 + byte_in_double]) [0]return time_received-time_sentstart_time = start_time -How_longif start_time <= 0:returndef get_checksum (self,source): checksum = 0count = (len (source)/2) * 2i = 0while I < Count:temp = Ord (source[i + 1]) * + ord (source[i]) # = 2^8checksum = checksum + Tempchecksum = checksum & 0xFFFFFFFF # 4,294,967,296 (2^32) i = i + 2if i < len (source): checksum = checksum + ord (Source[len (source)-1]) Checksu m = checksum & 0xffffffff# 32-bit to 16-bitchecksum = (checksum >> +) + (checksum & 0xffff) checksum = check Sum + (checksum >> answer) = ~checksumanswer = Answer & 0xffff# why? Ans[9:16 1:8]answer = Answer >> 8 | (Answer << 8 & 0xff00) return answerdef send_ping (Self,my_socket, Ip_addr, ID): IP = socket.gethostbyname (ip_ Addr) My_checksum = 0header = Struct.pack (' bbhhh ', self. Icmp_echo_request, 0, My_checksum, ID, 1) byte_in_double = Struct.calcsize ("D") # C Type:doubledata = (192-byte_in_double) * "P" # any char are OK, any length is okdata = Struct.pack ("D", Time.clock ()) + Datamy_check sum = self.get_checksum (header + data) Header = Struct.pack ("Bbhhh", self. Icmp_echo_request, 0, Socket.htons (my_checksum), ID, 1) packet = header + datamy_socket.sendto (packet, (IP)) # It seems That 0~65535 is OK (port?) def ping_once (self,ip_addr, timeout): ICMP = socket.getprotobyname (' ICMP ') Try:my_socket = Socket.socket (socket.af_ INET, Socket. Sock_raw, ICMP) except Socket.error:raisemy_ID = Os.getpid () & 0xffffself.send_ping (My_socket, IP_ADDR, my_id) delay = Self.receive_ping (My_socket, my_id, timeout) my_socket.close () return delaydef icmp_ping (self,ip_addr,timeout,count ): Number=1for I in range (count):p rint ' ping ' + ip_addr,try:delay = self.ping_once (ip_addr, timeout) if delay = = None:print ' Failed. (Timeout within%s second.) ' % timeoutif Number==count:print (' The request has failed%s Times,email alerts is being sent '% count) getcfg (self.filename ). SendMessage(ip_addr) Else:print ' get reply in%0.4f ms '% (Delay *) breakexcept Socket.gaierror, E:print "failed. (Socket error: '%s ') "% e[1]breaknumber=number+1if __name__ = = ' __main__ ': weixin=weixin. WeChat () mail=mail.sendmail () cfgname= ' ping_monitor.txt ' ping (cfgname) pingcfg=getcfg (cfgname) Pingcfg.next_check ()
Configuration file
[rule]retry = 4timeout = 1next_check = 300# units are seconds [scan_network]3paragraph_begin = 10.1.3.1983paragraph_end = 2022paragraph_begin = 10.1.2.12paragraph_end = 10[mail][email protected][email Protected][allip] #这里会自动把扫描到的ip写入
Python2 Write ping monitoring, auto-discovery IP