多任务管理作业

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("任务结束......")

运行结果如下所示:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值