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 列表之后可以进一步去操作设备。


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容