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