多线程练习

  1. IP 地址归属地批量查询任务(用构造子类的方法)

     from threading import Thread
     import  requests
     import json
     class Ip_Addr(Thread):
         def __init__(self,ip):
             super(Ip_Addr, self).__init__()
             self.ip = ip
         def run(self):
             #print(self.ip)
             url = 'http://ip-api.com/json/%s' % (self.ip)
             try:
                 response = requests.get(url)
             except Exception as e:
                 print("网页获取错误:", e)
             else:
                 contentPage = response.text
                 data_dict = json.loads(contentPage)
                 city = data_dict.get('city', 'null')
                 country = data_dict.get('country', 'null')
    
                 print(self.ip, city, country)
     if __name__ == '__main__':
         print("IP地址的批量查询结果" .center(50,'*'))
          for i in range(1,255):
            ip ='1.1.1.' + str(i)
            thread = Ip_Addr(ip)
            thread.start()
    

2.基于多线程的批量主机存活探测
注意: 使用实例化对象的方式实现多线程任务
项目描述: 如果要在本地网络中确定哪些地址处于活动状态或哪些计算机处于活动状态, 则可以使用此脚本。我们将依次 ping 地址, 每次都要等几秒钟才能返回值。
项目瓶颈: 没有线程的解决方案效率非常低,因为脚本必须等待每次 ping。

实验代码:

import threading
import os


def task(ip):
    cmd = 'ping -c1 -w1 %s &>/dev/null' % (ip)
    result = os.system(cmd)
    if result != 0:
        print("%s 主机没有ping通" % (ip))


if __name__ == '__main__':
    threads = []
    for i in range(1, 255):
        ip = '172.25.254.' + str(i)
        t = threading.Thread(target=task, args=(ip,))
        t.start()
        threads.append(t)
    [thread.join() for thread in threads]

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值