一. IP 地址归属地批量查询任务
使用创建子类的方式实现多线程任务
from threading import Thread,Lock
import requests
import json
class GetHost(Thread):
def __init__(self, ip):
super(GetHost, self).__init__()
self.ip = ip
def run(self):
url = 'http://ip-api.com/json/%s' % self.ip
page = requests.get(url).text
dict_data = json.loads(page)
lock.acquire()
city = dict_data.get('city')
country = dict_data.get('country')
# print(self.ip,city,country)
print("IP:%s City:%s Country:%s"%(self.ip, city, country))
lock.release()
if __name__ == '__main__':
threads = []
lock=Lock()
for i in range(1, 10):
ip ='1.1.1.' + str(i)
t = GetHost(ip)
t.start()
threads.append(t)
[thread.join() for thread in threads]
二.基于多线程的批量主机存活探测
注意:使用实例化对象的方式实现多线程任务
项目描述: 如果要在本地网络中确定哪些地址处于活动状态或哪些计算机处于活动状态,
则可以使用此脚本。我们将依次 ping 地址, 每次都要等几秒钟才能返回值。这可以在 Python
中编程,在 IP 地址的地址范围内有一个 for 循环和一个 os.popen(“ping -q -c2”+ ip)。
项目瓶颈: 没有线程的解决方案效率非常低,因为脚本必须等待每次 ping。
from threading import Lock
import threading
import os
def activ_ip(ip):
cmd = 'ping -c1 -w1 %s &> /dev/null' %(ip)
result = os.system(cmd)
lock.acquire()
if result != 0:
print("%s主机处于活动状态" %(ip))
lock.release()
if __name__ == '__main__':
lock=Lock()
threads = []
for i in range(1, 255):
ip = '172.25.254.' + str(i)
thread=threading.Thread(target=activ_ip, args=(ip,))
thread.start()
[thread.join() for thread in threads]