pyhton多线程练习

本文介绍了两个Python多线程实战应用:一是通过创建子类实现IP地址归属地的批量查询;二是利用多线程进行批量主机存活探测,提高效率。在主机存活探测中,通过for循环结合os.popen执行ping命令,但由于没有使用线程,效率较低。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. IP 地址归属地批量查询任务
使用创建子类的方式实现多线程任务

from threading import Thread,Lock
import requests
import json
class GetHost(Thread):
    def __init__(self, ip):
        super(GetHost, self).__init__()
        self.ip = ip
    def run(self):

        url = 'http://ip-api.com/json/%s' % self.ip
        page = requests.get(url).text
        dict_data = json.loads(page)
        lock.acquire()
        city = dict_data.get('city')
        country = dict_data.get('country')
        # print(self.ip,city,country)
        print("IP:%s  City:%s  Country:%s"%(self.ip, city, country))

        lock.release()
if __name__ == '__main__':
    threads = []
    lock=Lock()
    for i in range(1, 10):
        ip ='1.1.1.' + str(i)
        t = GetHost(ip)
        t.start()
        threads.append(t)
    [thread.join() for thread in threads]

在这里插入图片描述
二.基于多线程的批量主机存活探测
注意:使用实例化对象的方式实现多线程任务
项目描述: 如果要在本地网络中确定哪些地址处于活动状态或哪些计算机处于活动状态,
则可以使用此脚本。我们将依次 ping 地址, 每次都要等几秒钟才能返回值。这可以在 Python
中编程,在 IP 地址的地址范围内有一个 for 循环和一个 os.popen(“ping -q -c2”+ ip)。
项目瓶颈: 没有线程的解决方案效率非常低,因为脚本必须等待每次 ping。

from threading import Lock
import threading
import os
def activ_ip(ip):
    cmd = 'ping -c1 -w1 %s &> /dev/null' %(ip)
    result = os.system(cmd)
    lock.acquire()
    if result != 0:
        print("%s主机处于活动状态" %(ip))
    lock.release()
if __name__ == '__main__':
    lock=Lock()
    threads = []
    for i in range(1, 255):
        ip = '172.25.254.' + str(i)
        thread=threading.Thread(target=activ_ip, args=(ip,))
        thread.start()
    [thread.join() for thread in threads]

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值