1. 多线程实现批量 PDF 转换器工具
2.IP 地址归属地批量查询任务、
注意:使用创建子类的方式实现多线程任务
运行代码如下:
import threading
import requests
import json
class MyThread(threading.Thread):
def __init__(self,ip):
super(MyThread,self).__init__()
self.ip = ip
def run(self):
url = 'http://ip-api.com/json/%s' % (self.ip)
try:
response = requests.get(url)
except Exception as e:
print("网页获取错误:", e)
else:
# 默认返回的是字符串
"""
{"as":"AS174 Cogent Communications","city":"Beijing","country":"China","countryCode":"CN","isp":"China Unicom Shandong Province network","lat":39.9042,"lon":116.407,"org":"NanJing XinFeng Information Technologies, Inc.","query":"114.114.114.114","region":"BJ","regionName":"Beijing","status":"success","timezone":"Asia/Shanghai","zip":""}
"""
contentPage = response.text
print(contentPage)
# 将页面的json字符串转换成便于处理的字典;
data_dict = json.loads(contentPage)
print("""
%s
所在城市:%s
所在国家:%s
""" %(self.ip,data_dict['city'],data_dict['country']))
if __name__ == '__main__':
threads = []
for item in range(10):
ip = '1.1.1.' + str(item + 1)
t=MyThread(ip)
t.start()
threads.append(t)
[t.join() for t in threads]
print("任务执行结束.....")
运行结果如下:
3. 基于多线程的批量主机存活探测
注意: 使用实例化对象的方式实现多线程任务
项目描述: 如果要在本地网络中确定哪些地址处于活动状态或哪些计算机处于活动状态,
则可以使用此脚本。我们将依次 ping 地址, 每次都要等几秒钟才能返回值。这可以在 Python
中编程,在 IP 地址的地址范围内有一个 for 循环和一个 os.popen(“ping -q -c2”+ ip)。
项目瓶颈: 没有线程的解决方案效率非常低,因为脚本必须等待每次 ping。
运行代码如下:
import threading
def GetHostAliveThread(ip):
import os
cmd = 'ping -c1 -w1 %s &> /dev/null' %(ip)
result = os.system(cmd)
if result != 0:
print("%s主机没有ping 通" %(ip))
if __name__ == '__main__':
print("打印172.25.254.0网段没有使用的IP地址".center(50,"*"))
threads = []
for i in range(1,255):
ip = '172.25.254.' + str(i)
# thread = GetHostAliveThread(ip)
#实例化方法实现IP归属
t = threading.Thread(target=GetHostAliveThread(ip))
t.start()
threads.append(t)
[t.join() for t in threads]
print("任务结束......")
运行结果如下所示: