-
IP 地址归属地批量查询任务(用构造子类的方法)
from threading import Thread import requests import json class Ip_Addr(Thread): def __init__(self,ip): super(Ip_Addr, self).__init__() self.ip = ip def run(self): #print(self.ip) url = 'http://ip-api.com/json/%s' % (self.ip) try: response = requests.get(url) except Exception as e: print("网页获取错误:", e) else: contentPage = response.text data_dict = json.loads(contentPage) city = data_dict.get('city', 'null') country = data_dict.get('country', 'null') print(self.ip, city, country) if __name__ == '__main__': print("IP地址的批量查询结果" .center(50,'*')) for i in range(1,255): ip ='1.1.1.' + str(i) thread = Ip_Addr(ip) thread.start()
2.基于多线程的批量主机存活探测
注意: 使用实例化对象的方式实现多线程任务
项目描述: 如果要在本地网络中确定哪些地址处于活动状态或哪些计算机处于活动状态, 则可以使用此脚本。我们将依次 ping 地址, 每次都要等几秒钟才能返回值。
项目瓶颈: 没有线程的解决方案效率非常低,因为脚本必须等待每次 ping。
实验代码:
import threading
import os
def task(ip):
cmd = 'ping -c1 -w1 %s &>/dev/null' % (ip)
result = os.system(cmd)
if result != 0:
print("%s 主机没有ping通" % (ip))
if __name__ == '__main__':
threads = []
for i in range(1, 255):
ip = '172.25.254.' + str(i)
t = threading.Thread(target=task, args=(ip,))
t.start()
threads.append(t)
[thread.join() for thread in threads]
运行结果: