IP 地址归属地批量查询任务:使用创建子类的方式实现多线程任务
# 代码
"""
创建子类
"""
import json
import requests
from threading import Thread
class GetHostAliveThread(Thread):
"""
创建子线程, 执行的任务:判断指定的IP是否存活
"""
def __init__(self, ip):
super(GetHostAliveThread, self).__init__()
self.ip = ip
def run(self):
# # 重写run方法: 判断指定的IP是否存活
# """
# >>> # os.system() 返回值如果为0, 代表命令正确执行,没有报错; 如果不为0, 执行报错;
# ...
# >>> os.system('ping -c1 -w1 172.25.254.49 &> /dev/null')
# 0
# >>> os.system('ping -c1 -w1 172.25.254.1 &> /dev/null')
# 256
# """
import os
# 需要执行的shell命令
url = 'http://ip-api.com/json/%s' % (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
# 将页面的json字符串转换成便于处理的字典;
data_dict = json.loads(contentPage)
# 获取对应的城市和国家
city = data_dict.get('city', 'null') # None
country = data_dict.get('country', 'null')
print(ip, city, country)
if __name__ == '__main__':
print("IP 地址归属地批量查询任务".center(50, '*'))
for i in range(1, 10):
ip = '1.1.1.' + str(i)
thread = GetHostAliveThread(ip)
thread.start()
# 运行结果
******************IP 地址归属地批量查询任务******************
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia
1.1.1.9 Sydney Australia