使用Python查找局域网上的活动节点

5
我正在使用Python 2.7和Windows创建一个Messenger,与IP Messenger相同。
我希望实现与IP Messenger相同的功能,在局域网中查找运行相同软件的系统,但我无法理解技术方法。
请有经验的人用Python 2.7和Sockets库帮我解决以下问题:查找在局域网上运行相同软件的计算机的IP地址或主机名。
请提供一些可以在Windows上实现的建议,而不是像Nmap(仅限于Linux),如果能提供Python Socket Library代码,将非常有帮助。

我猜可以使用nmap来定位局域网中的主机,然后尝试连接给定主机上的特定端口。这个SO线程可能会有所帮助https://dev59.com/m3VC5IYBdhLWcg3w1E_w - Ifthikhan
你所说的Nmap是Python-Nmap或Nmap软件,请问你能否详细介绍一下我可以在Windows上实现的nmap? - aki92
5个回答

10

"net view"命令解决了我在问题中提出的问题。通过这个命令,我能够找到所有通过局域网连接到我的计算机的计算机,然后我将向所有计算机发送数据包,而回复我的数据包的计算机将是运行与我相同软件的系统,这完全解决了我的问题。 这段代码列出了所有通过局域网连接到我的计算机的计算机主机名。

import os
os.system('net view > conn.tmp')
f = open('conn.tmp', 'r')
f.readline();f.readline();f.readline()

conn = []
host = f.readline()
while host[0] == '\\':
    conn.append(host[2:host.find(' ')])
    host = f.readline()

print conn
f.close()    

你的解决方案很棒,但是当我尝试将“conn.tmp”附加到这样格式化的文件夹中时出现了错误:“2013-11-22 - MyProjectName”,因为有“ - ”(带空格)。你有解决这个问题的方法吗? - RPDeshaies
@Tareck117 试着更改文件夹名称,因为这似乎是文件夹的问题。 - aki92

2
您想要做的是对本地网络进行ping以查找活动节点。您可以使用类似于此脚本,使用Scapy可能已经足够了。另一个更轻量级的选择是纯Python实现
为了获取当前IP地址,您可能需要遵循此问题中给出的解决方案之一。
前面提到的Ping类的扩展可以让您拉回结果以供阅读:
# TODO: This is a quick hack to retrieve the results 
# of the ping, you should probably do something a bit more elegant here!
class PingQuery(Ping):
    def __init__():
        super().__init__()
        result = false

    def print_success(self, delay, ip, packet_size, ip_header, icmp_header):
        result = ip

你可以循环遍历子网中的地址以找到活跃机器的列表:

subnet = "192.168.0." # TODO: Trim the last number off the IP address retrieved earlier
for i in range(1, 255):
    hostname = subnet + i
    p = PingQuery(hostname, 500, 55) # Timeout after 500ms per node
    p.run(1)
    if (p.result):
        print p.result + " is live"

之后,您可以通过尝试使用所选端口连接到每台机器,并检查特定的TCP数据包来查询活动机器,以证明监听程序实际上是您的软件。


我想要一个可以在Windows上运行的东西。你的第一个解决方案仅限于Linux,而第二个代码是将输入作为主机名并检查主机名是否存在,但我想要的功能是,如果我运行一段代码并且我通过局域网连接了5台计算机,则它应该列出所有5台计算机的IP地址,并且代码不应该需要任何输入。 - aki92
我第一条建议中的代码不仅限于Linux,它支持Scapy支持的所有平台。第二个链接提供了一个Scapy的替代方案,但您仍需要从neighbourhood.py中复制扫描循环逻辑。 - seanhodges
我认为解决我的问题的方法可能非常简单,因为我只需要按照我在上面评论中所述的方式执行即可。例如,在5台计算机中,我认为将静态IP分配给以太网可以解决我的问题,但是我仍然无法解决它。 - aki92
非常感谢seanhodges的帮助,我的问题通过net view命令得到了解决。 - aki92
没问题,很高兴你解决了它。现在你应该能够将自己的答案标记为已解决 - 只需点击你的答案左侧的勾号即可。这将帮助其他有类似问题的人更快地找到他们的解决方案。 - seanhodges
显示剩余2条评论

0

基于aki92的回答...

import re
import subprocess
# ...

nodes = re.findall(r'\\(.+?)(?: .*)?\n',subprocess.check_output('net view'))

0

使用命令行arp -a并结合numpy解析的Mac解决方案。也可以使用此方法找到MAC地址。

import os
import numpy as np

# Perform LAN scan
os.system('arp -a > scan.tmp')
scan = np.loadtxt('scan.tmp', dtype='str', delimiter='nodelimiter')

# Discard empty nodes
empty_nodes = np.where(np.char.find(scan, 'incomplete') > 0)[0]
scan = np.delete(scan, empty_nodes)

# Parse IP address (solution for parsing mac address commented out)
for i, node in enumerate(scan):
    left, right = np.char.find(node,'(') + 1, np.char.find(node,')')
    # left, right = np.char.find(node,'at') + 3, np.char.find(node,'on') - 1
    scan[i] = node[left:right]

print(scan)

0

使用Simple HttpServer添加了HTTP层,返回JSON响应。

import time
import socket
import struct
import select
import random
import json
import asyncore
from netaddr import IPNetwork
import BaseHTTPServer


# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.

ICMP_CODE = socket.getprotobyname('icmp')
ERROR_DESCR = {
    1: ' - Note that ICMP messages can only be '
       'sent from processes running as root.',
    10013: ' - Note that ICMP messages can only be sent by'
           ' users or processes with administrator rights.'
    }

__all__ = ['create_packet', 'do_one', 'verbose_ping', 'PingQuery',
           'multi_ping_query']


HOST_NAME = '0.0.0.0' # !!!REMEMBER TO CHANGE THIS!!!
PORT_NUMBER = 9000 # Maybe set this to 9000.
SUBNET = '10.10.20.1/24'
host_list = []
"""
Below class would handle all rest requests
"""
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
     def do_HEAD(self,s):
         s.send_response(200)
         s.send_header("Content-type", "text/html")
         s.end_headers()
     def do_GET(s):
        """Respond to a GET request."""  
        s.send_response(200)
        s.send_header("content_disposition", "attachment; filename=serverstatus.json")
        s.send_header("Content-type", "text/json")
        s.end_headers()

        for ip in IPNetwork(SUBNET):
            host_list.append(ip.format(None))

        #Create Object of SubnetMonitor
        monitor =  SubnetMonitor()

        responseData = {}
        for host, ping in monitor.multi_ping_query(host_list).iteritems():

            if ping is not None:
                print(host,'()',socket.gethostbyname(host)   , '=', ping)   
                responseData[host] = 'Is Up'    
            else:
                responseData[host] = 'Is Down'

        json_data = json.dumps(responseData, sort_keys=True, indent=4, separators=(',', ': '))

        s.wfile.write(json_data)


"""
Below class is used to send/receive all ping/icmp requests 
"""     
class PingQuery(asyncore.dispatcher):


    def __init__(self, host, p_id, timeout=0.5, ignore_errors=False,monitor=None):
        """
       Derived class from "asyncore.dispatcher" for sending and
       receiving an icmp echo request/reply.

       Usually this class is used in conjunction with the "loop"
       function of asyncore.

       Once the loop is over, you can retrieve the results with
       the "get_result" method. Assignment is possible through
       the "get_host" method.

       "host" represents the address under which the server can be reached.
       "timeout" is the interval which the host gets granted for its reply.
       "p_id" must be any unique integer or float except negatives and zeros.

       If "ignore_errors" is True, the default behaviour of asyncore
       will be overwritten with a function which does just nothing.

       """
        self.monitor = monitor
        asyncore.dispatcher.__init__(self)
        try:
            self.create_socket(socket.AF_INET, socket.SOCK_RAW, ICMP_CODE)
        except socket.error as e:
            if e.errno in ERROR_DESCR:
                # Operation not permitted
                raise socket.error(''.join((e.args[1], ERROR_DESCR[e.errno])))
            raise # raise the original error
        self.time_received = 0
        self.time_sent = 0
        self.timeout = timeout
        # Maximum for an unsigned short int c object counts to 65535 so
        # we have to sure that our packet id is not greater than that.
        self.packet_id = int((id(timeout) / p_id) % 65535)
        self.host = host
        self.packet = self.monitor.create_packet(self.packet_id)
        if ignore_errors:
            # If it does not care whether an error occured or not.
            self.handle_error = self.do_not_handle_errors
            self.handle_expt = self.do_not_handle_errors

    def writable(self):
        return self.time_sent == 0

    def handle_write(self):
        self.time_sent = time.time()
        while self.packet:
            # The icmp protocol does not use a port, but the function
            # below expects it, so we just give it a dummy port.
            sent = self.sendto(self.packet, (self.host, 1))
            self.packet = self.packet[sent:]

    def readable(self):
        # As long as we did not sent anything, the channel has to be left open.
        if (not self.writable()
            # Once we sent something, we should periodically check if the reply
            # timed out.
            and self.timeout < (time.time() - self.time_sent)):
            self.close()
            return False
        # If the channel should not be closed, we do not want to read something
        # until we did not sent anything.
        return not self.writable()

    def handle_read(self):
        read_time = time.time()
        packet, addr = self.recvfrom(1024)
        header = packet[20:28]
        type, code, checksum, p_id, sequence = struct.unpack("bbHHh", header)
        if p_id == self.packet_id:
            # This comparison is necessary because winsocks do not only get
            # the replies for their own sent packets.
            self.time_received = read_time
            self.close()

    def get_result(self):
        """Return the ping delay if possible, otherwise None."""
        if self.time_received > 0:
            return self.time_received - self.time_sent

    def get_host(self):
        """Return the host where to the request has or should been sent."""
        return self.host

    def do_not_handle_errors(self):
        # Just a dummy handler to stop traceback printing, if desired.
        pass

    def create_socket(self, family, type, proto):
        # Overwritten, because the original does not support the "proto" arg.
        sock = socket.socket(family, type, proto)
        sock.setblocking(0)
        self.set_socket(sock)
        # Part of the original but is not used. (at least at python 2.7)
        # Copied for possible compatiblity reasons.
        self.family_and_type = family, type

    # If the following methods would not be there, we would see some very
    # "useful" warnings from asyncore, maybe. But we do not want to, or do we?
    def handle_connect(self):
        pass

    def handle_accept(self):
        pass

    def handle_close(self):
        self.close()

class SubnetMonitor:

    def __init__(self):
        print("Subnet Monitor Started")     

    def checksum(self,source_string):
        # I'm not too confident that this is right but testing seems to
        # suggest that it gives the same answers as in_cksum in ping.c.
        sum = 0
        count_to = (len(source_string) / 2) * 2
        count = 0
        while count < count_to:
            this_val = ord(source_string[count + 1])*256+ord(source_string[count])
            sum = sum + this_val
            sum = sum & 0xffffffff # Necessary?
            count = count + 2
        if count_to < len(source_string):
            sum = sum + ord(source_string[len(source_string) - 1])
            sum = sum & 0xffffffff # Necessary?
        sum = (sum >> 16) + (sum & 0xffff)
        sum = sum + (sum >> 16)
        answer = ~sum
        answer = answer & 0xffff
        # Swap bytes. Bugger me if I know why.
        answer = answer >> 8 | (answer << 8 & 0xff00)
        return answer


    def create_packet(self,id):
        """Create a new echo request packet based on the given "id"."""
        # Header is type (8), code (8), checksum (16), id (16), sequence (16)
        header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, 0, id, 1)
        data = 192 * 'Q'
        # Calculate the checksum on the data and the dummy header.
        my_checksum = self.checksum(header + data)
        # Now that we have the right checksum, we put that in. It's just easier
        # to make up a new header than to stuff it into the dummy.
        header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0,
                             socket.htons(my_checksum), id, 1)
        return header + data


    def do_one(self,dest_addr, timeout=1):
        """
        Sends one ping to the given "dest_addr" which can be an ip or hostname.
        "timeout" can be any integer or float except negatives and zero.
        Returns either the delay (in seconds) or None on timeout and an invalid
        address, respectively.
        """
        try:
            my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, ICMP_CODE)
        except socket.error as e:
            if e.errno in ERROR_DESCR:
                # Operation not permitted
                raise socket.error(''.join((e.args[1], ERROR_DESCR[e.errno])))
            raise # raise the original error
        try:
            host = socket.gethostbyname(dest_addr)
        except socket.gaierror:
            return
        # Maximum for an unsigned short int c object counts to 65535 so
        # we have to sure that our packet id is not greater than that.
        packet_id = int((id(timeout) * random.random()) % 65535)
        packet = self.create_packet(packet_id)
        while packet:
            # The icmp protocol does not use a port, but the function
            # below expects it, so we just give it a dummy port.
            sent = my_socket.sendto(packet, (dest_addr, 1))
            packet = packet[sent:]
        delay = self.receive_ping(my_socket, packet_id, time.time(), timeout)
        my_socket.close()
        return delay


    def receive_ping(self,my_socket, packet_id, time_sent, timeout):
        # Receive the ping from the socket.
        time_left = timeout
        while True:
            started_select = time.time()
            ready = select.select([my_socket], [], [], time_left)
            how_long_in_select = time.time() - started_select
            if ready[0] == []: # Timeout
                return
            time_received = time.time()
            rec_packet, addr = my_socket.recvfrom(1024)
            icmp_header = rec_packet[20:28]
            type, code, checksum, p_id, sequence = struct.unpack(
                'bbHHh', icmp_header)
            if p_id == packet_id:
                return time_received - time_sent
            time_left -= time_received - time_sent
            if time_left <= 0:
                return


    def verbose_ping(self,dest_addr, timeout=2, count=4):
        """
        Sends one ping to the given "dest_addr" which can be an ip or hostname.
        "timeout" can be any integer or float except negatives and zero.
        "count" specifies how many pings will be sent.
        Displays the result on the screen.

        """
        for i in range(count):
            print('ping {}...'.format(dest_addr))
            delay = self.do_one(dest_addr, timeout)
            if delay == None:
                print('failed. (Timeout within {} seconds.)'.format(timeout))
            else:
                delay = round(delay * 1000.0, 4)
                print('get ping in {} milliseconds.'.format(delay))
        print('')


    def multi_ping_query(self,hosts, timeout=1, step=512, ignore_errors=False):
        """
        Sends multiple icmp echo requests at once.
        "hosts" is a list of ips or hostnames which should be pinged.
        "timeout" must be given and a integer or float greater than zero.
        "step" is the amount of sockets which should be watched at once.
        See the docstring of "PingQuery" for the meaning of "ignore_erros".
        """
        results, host_list, id = {}, [], 0
        for host in hosts:
            try:
                host_list.append(socket.gethostbyname(host))
            except socket.gaierror:
                results[host] = None
        while host_list:
            sock_list = []
            for ip in host_list[:step]: # select supports only a max of 512
                id += 1
                sock_list.append(PingQuery(ip, id, timeout, ignore_errors,self))
                host_list.remove(ip)
            # Remember to use a timeout here. The risk to get an infinite loop
            # is high, because noone can guarantee that each host will reply!
            asyncore.loop(timeout)
            for sock in sock_list:
                results[sock.get_host()] = sock.get_result()
        return results      


if __name__ == '__main__':
     server_class = BaseHTTPServer.HTTPServer
     httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
     print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
     try:
         httpd.serve_forever()
     except KeyboardInterrupt:
         pass
     httpd.server_close()
     print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接