Python扫描局域网内指定端口的IP列表

最近在手撸一个基于Onvif协议的通用设备管理器,需要根据指定RTSP协议554端口来扫描局域网的所有设备列表及设备信息,废话不多说,直接上代码:

import threading
import socket

lock = threading.Lock()

class DeviceScan:
    routers = []

    def __init__(self, start_ip, end_ip):
        self.start_ip = start_ip
        self.end_ip = end_ip
        start_index = self.get_last_ip(start_ip)
        end_index = self.get_last_ip(end_ip)
        if start_index is not None and end_index is not None:
            self.scan(int(start_index), int(end_index))

    def get_last_ip(self, ip):
        if ip is not None and len(ip) > 0:
            ips = ip.split(".")
            if len(ips) == 4:
                return ips[3]
            else:
                return None
        else:
            return None

    def check_ip(self, new_ip):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # create socket
        s.settimeout(1)
        PORT = 554 #change it to the port you want
        result = s.connect_ex((new_ip, PORT))
        if result == 0:
            lock.acquire()  # get lock
            self.routers.append(new_ip)
            lock.release()

    def scan(self, start_index, end_index):
        local_ip = socket.gethostbyname_ex(socket.gethostname())
        all_threads = []
        for ip in local_ip[2]:
            for i in range(start_index, end_index):
                array = ip.split(".")  # split ip for dot
                array[3] = str(i)
                new_ip = '.'.join(array)
                t = threading.Thread(target=self.check_ip, args=(new_ip,))
                t.start()
                all_threads.append(t)
            for t in all_threads:
                t.join()

    def get_ips(self):
        return self.routers


if __name__ == '__main__':
    import time

    print('search for router,please wait......')
    print("start scan time: %s" % time.ctime())
    result = DeviceScan('192.168.0.0', '192.168.0.255').get_ips()
    print("end scan time %s" % time.ctime())
    print(result)

如上运行代码效果如下,得到IP 列表之后可以进一步去操作设备。
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值