多任务管理作业

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值