我编写脚本的脚本,在日志中写入ping活着或没有活着。
但是所有时间都要记录ping活着。
为什么?
代码:
import os
import re
import time
import sys
from threading import Thread
from time import gmtime, strftime
class IntTools:
def PingTool(self):
ipconf = open('ip.conf', 'r')
ipstrip = ipconf.readlines()
ip = ipstrip[2].strip()
ip2 = ipstrip[3].strip()
ip3 = ipstrip[4].strip()
ip4 = ipstrip[5].strip()
ip5 = ipstrip[6].strip()
class testit(Thread):
def __init__ (self,ip):
Thread.__init__(self)
self.ip = ip
self.status = -1
def run(self):
pingaling = os.popen("ping "+self.ip+" -n 1","r")
while 1:
line = pingaling.readline()
#print line
if not line: break
igot = re.findall(testit.lifeline,line)
if igot:
self.status = int(igot[0])
testit.lifeline = re.compile(r"(\d) received")
report = ("No response","Partial Response","Alive")
print time.ctime()
pinglist = []
current = testit(ip)
pinglist.append(current)
current.start()
for pingle in pinglist:
pingle.join()
pinglog = open('ping.log', 'a')
pinglog.write('Status from '+pingle.ip+" is "+report[pingle.status]+'\n')
pinglog.close()
def ReadPingLog(self):
pinglog = open('ping.log', 'r+')
print pinglog.read()
pinglog.close()
IntTools = IntTools()
IntTools.PingTool()
答案 0 :(得分:0)
因为如果ping失败,您失败的testit
个对象的status
为-1
,则这对应于report
的最后一项,即"Alive"
尝试将状态设置为None
,或在编制status
索引之前检查-1
是否为report
。