代码之家  ›  专栏  ›  技术社区  ›  Josh Hunt bstahlhood

Python中本地网络的IP地址/主机名列表

  •  34
  • Josh Hunt bstahlhood  · 技术社区  · 18 年前

    如果它是多平台的,那将是最好的,但它需要先在MacOSX上工作,然后其他人也跟着工作。

    编辑: 我所说的本地人是指所有人 192.168.xxx.xxx .

    因此,如果我的计算机(在本地网络内)的IP地址是 192.168.1.1 ,我还有另外三台连接的计算机,我希望它返回IP地址 192.168.1.2 192.168.1.3 , 192.168.1.4 ,可能还有他们的主机名。

    7 回复  |  直到 16 年前
        1
  •  24
  •   Steve Moyer    18 年前

    如果“本地”是指在同一网段上,则必须执行以下步骤:

    1. 确定您自己的IP地址
    2. 确定网络范围
    3. 扫描所有地址(除了最低地址,即网络地址和最高地址,即广播地址)。
    4. 使用DNS的反向查找来确定响应扫描的IP地址的主机名。

    或者,您可以让Python在外部执行nmap,并将结果通过管道传回您的程序。

        2
  •  24
  •   Benedikt Waldvogel assylias    15 年前

    :脚本现在位于上 github .

    我写了一封信 small python script ,即利用 scapy arping() .

        3
  •  11
  •   Peter Mortensen Pieter Jan Bonestroo    16 年前

    如果您知道计算机的名称,则可以使用:

    import socket
    IP1 = socket.gethostbyname(socket.gethostname()) # local IP adress of your computer
    IP2 = socket.gethostbyname('name_of_your_computer') # IP adress of remote computer
    

        4
  •  8
  •   Santi Peñate-Vera    8 年前

    我从其他线程中收集了以下功能,它在Ubuntu中对我有效。

    import os
    import socket    
    import multiprocessing
    import subprocess
    import os
    
    
    def pinger(job_q, results_q):
        """
        Do Ping
        :param job_q:
        :param results_q:
        :return:
        """
        DEVNULL = open(os.devnull, 'w')
        while True:
    
            ip = job_q.get()
    
            if ip is None:
                break
    
            try:
                subprocess.check_call(['ping', '-c1', ip],
                                      stdout=DEVNULL)
                results_q.put(ip)
            except:
                pass
    
    
    def get_my_ip():
        """
        Find my IP address
        :return:
        """
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    
    
    def map_network(pool_size=255):
        """
        Maps the network
        :param pool_size: amount of parallel ping processes
        :return: list of valid ip addresses
        """
    
        ip_list = list()
    
        # get my IP and compose a base like 192.168.1.xxx
        ip_parts = get_my_ip().split('.')
        base_ip = ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] + '.'
    
        # prepare the jobs queue
        jobs = multiprocessing.Queue()
        results = multiprocessing.Queue()
    
        pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)]
    
        for p in pool:
            p.start()
    
        # cue hte ping processes
        for i in range(1, 255):
            jobs.put(base_ip + '{0}'.format(i))
    
        for p in pool:
            jobs.put(None)
    
        for p in pool:
            p.join()
    
        # collect he results
        while not results.empty():
            ip = results.get()
            ip_list.append(ip)
    
        return ip_list
    
    
    if __name__ == '__main__':
    
        print('Mapping...')
        lst = map_network()
        print(lst)
    
        5
  •  6
  •   trozzel    6 年前

    对于OSX(和Linux),一个简单的解决方案是使用os.popen或os.system并运行 arp -a 命令

    例如:

    devices = []
    for device in os.popen('arp -a'): devices.append(device)
    

        6
  •  4
  •   TheLizzard    5 年前

    我找到了这个 network scanner in python article

    linux: [20, 21, 22, 23, 25, 80, 111, 443, 445, 631, 993, 995]
    windows: [135, 137, 138, 139, 445]
    mac: [22, 445, 548, 631]
    
    import socket
    
    def connect(hostname, port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        result = sock.connect_ex((hostname, port))
        sock.close()
        return result == 0
    
    for i in range(0,255):
        res = connect("192.168.1."+str(i), 22)
        if res:
            print("Device found at: ", "192.168.1."+str(i) + ":"+str(22))
    

    编辑 作者:TheLizzard:

    使用上述代码并添加线程:

    from threading import Thread, Lock
    from time import perf_counter
    from sys import stderr
    from time import sleep
    import socket
    
    
    # I changed this from "192.168.1.%i" to "192.168.0.%i"
    BASE_IP = "192.168.0.%i"
    PORT = 80
    
    
    class Threader:
        """
        This is a class that calls a list of functions in a limited number of
        threads. It uses locks to make sure the data is thread safe.
        Usage:
            from time import sleep
    
            def function(i):
                sleep(2)
                with threader.print_lock:
                    print(i)
    
            threader = Threader(10) # The maximum number of threads = 10
            for i in range(20):
                threader.append(function, i)
            threader.start()
            threader.join()
    
        This class also provides a lock called: `<Threader>.print_lock`
        """
        def __init__(self, threads=30):
            self.thread_lock = Lock()
            self.functions_lock = Lock()
            self.functions = []
            self.threads = []
            self.nthreads = threads
            self.running = True
            self.print_lock = Lock()
    
        def stop(self) -> None:
            # Signal all worker threads to stop
            self.running = False
    
        def append(self, function, *args) -> None:
            # Add the function to a list of functions to be run
            self.functions.append((function, args))
    
        def start(self) -> None:
            # Create a limited number of threads
            for i in range(self.nthreads):
                thread = Thread(target=self.worker, daemon=True)
                # We need to pass in `thread` as a parameter so we
                # have to use `<threading.Thread>._args` like this:
                thread._args = (thread, )
                self.threads.append(thread)
                thread.start()
    
        def join(self) -> None:
            # Joins the threads one by one until all of them are done.
            for thread in self.threads:
                thread.join()
    
        def worker(self, thread:Thread) -> None:
            # While we are running and there are functions to call:
            while self.running and (len(self.functions) > 0):
                # Get a function
                with self.functions_lock:
                    function, args = self.functions.pop(0)
                # Call that function
                function(*args)
    
            # Remove the thread from the list of threads.
            # This may cause issues if the user calls `<Threader>.join()`
            # But I haven't seen this problem while testing/using it.
            with self.thread_lock:
                self.threads.remove(thread)
    
    
    start = perf_counter()
    # I didn't need a timeout of 1 so I used 0.1
    socket.setdefaulttimeout(0.1)
    
    def connect(hostname, port):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            result = sock.connect_ex((hostname, port))
        with threader.print_lock:
            if result == 0:
                stderr.write(f"[{perf_counter() - start:.5f}] Found {hostname}\n")
    
    threader = Threader(10)
    for i in range(255):
        threader.append(connect, BASE_IP%i, PORT)
    threader.start()
    threader.join()
    print(f"[{perf_counter() - start:.5f}] Done searching")
    input("Press enter to exit.\n? ")
    
        7
  •  3
  •   llllllllll    8 年前

    尝试:

    import socket
    
    print ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
    
        8
  •  0
  •   shashika11    6 年前

    我已经完成了以下代码,以获得MAC已知设备的IP。可以对其进行相应修改,以通过一些字符串操作获得所有IP。希望这对你有帮助。

    #running windows cmd line  statement and put output into a string
    cmd_out = os.popen("arp -a").read()
    line_arr = cmd_out.split('\n')
    line_count = len(line_arr)
    
    
    #search in all lines for ip
    for i in range(0, line_count):
        y = line_arr[i]
        z = y.find(mac_address)
    
        #if mac address is found then get the ip using regex matching
        if z > 0:
            ip_out= re.search('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', y, re.M | re.I)
    
        9
  •  -1
  •   Community Mohan Dere    9 年前

    答案之一 this question 也许对你有帮助。python似乎有一个平台无关的版本,但我还没有尝试过。

        10
  •  -1
  •   vivkv    7 年前

    这是一个小工具 斯堪尼普 这将帮助您获取网络中的所有ip地址及其相应的mac地址(在Linux上工作)。

    https://github.com/vivkv/scanip