# 批量ping def pingBatch(ips): if ips is not None and type(ips) == list: for ip in ips[:]: # 使用[:]复制ips列表,以避免在迭代时修改原列表 result = pingIp(ip) if not result: ips.remove(ip)
origin = "" with open(hostFile, "r", encoding="utf-8") as f: # 之前是否已经写过dns信息 flag = False for eachLine in f.readlines(): if r"###start###"in eachLine: flag = True elif r"###end###"in eachLine: flag = False else: if not flag: origin = origin + eachLine # 写入新的host记录 origin = origin.strip() origin = origin + "\n###start###\n" for eachHost in hostDic: for eachIp in hostDic[eachHost]: origin = origin + eachIp + "\t" + eachHost + "\n" origin = origin + "###最后更新时间:%s###\n" % datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') origin = origin + "###end###\n"
with open(hostFile, "w", encoding="utf-8") as f: f.write(origin)
if __name__ == '__main__': resultDic = {} for host in hosts: for dns in dnsProvider: records = analysis(host, dns) pingBatch(records) if records is not None and len(records) > 0: if host not in resultDic: resultDic[host] = records else: resultDic[host] += records hostWritor(resultDic) EOF