>  기사  >  백엔드 개발  >  LAN에서 라이브 호스트를 검색하기 위해 python-nmap을 호출하는 방법(코드)

LAN에서 라이브 호스트를 검색하기 위해 python-nmap을 호출하는 방법(코드)

不言
不言원래의
2018-09-20 16:59:217393검색

이 문서의 내용은 LAN에서 살아남은 호스트(코드)를 검색하기 위해 python-nmap을 호출하는 방법에 대한 것입니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

사용 환경: Raspberry 3b+ +netifaces+python-nmap+nmap

netifaces를 호출하여 자동으로 IP 주소를 얻습니다:

def get_gateways():    
return netifaces.gateways()['default'][netifaces.AF_INET][0]

네트워크 세그먼트의 모든 IP 주소 목록에 IP 주소를 생성합니다:

def get_ip_lists(ip):
    ip_lists = []    
    for i in range(1, 256):
        ip_lists.append('{}{}'.format(ip[:-1], i))    
        return ip_lists

주로 코드 및 데이터 분할 구현:

def main(ip=None):
    ip=get_gateways()
    ip_lists=get_ip_lists(ip)
    nmScan,temp_ip_lists,hosts = nmap.PortScanner(),[],ip[:-1]+'0/24'
    ret = nmScan.scan(hosts=hosts, arguments='-sP')
    print('扫描时间:'+ret['nmap']['scanstats']['timestr']+'\n命令参数:'+ret['nmap']['command_line'])
    for ip in ip_lists:
        print('ip地址:'+ip+':')
        if ip not in ret['scan']:
            temp_ip_lists.append(ip)
            print('扫描超时')
        else:print('已扫描到主机,主机名:'+ret['scan'][ip]['hostnames'][0]['name'])
    print(str(hosts) +' 网络中的存活主机:')
    for ip in temp_ip_lists:ip_lists.remove(ip)
    for ip in ip_lists:print(ip)

전체 코드:

#!/usr/bin/python
#_*_ coding:utf8 _*_
import netifaces,nmap

def get_gateways():
    return netifaces.gateways()['default'][netifaces.AF_INET][0]

def get_ip_lists(ip):
    ip_lists = []
    for i in range(1, 256):
        ip_lists.append('{}{}'.format(ip[:-1], i))
    return ip_lists

def main(ip=None):
    ip=get_gateways()
    ip_lists=get_ip_lists(ip)
    nmScan,temp_ip_lists,hosts = nmap.PortScanner(),[],ip[:-1]+'0/24'
    ret = nmScan.scan(hosts=hosts, arguments='-sP')
    print('扫描时间:'+ret['nmap']['scanstats']['timestr']+'\n命令参数:'+ret['nmap']['command_line'])
    for ip in ip_lists:
        print('ip地址:'+ip+':')
        if ip not in ret['scan']:
            temp_ip_lists.append(ip)
            print('扫描超时')
        else:print('已扫描到主机,主机名:'+ret['scan'][ip]['hostnames'][0]['name'])
    print(str(hosts) +' 网络中的存活主机:')
    for ip in temp_ip_lists:ip_lists.remove(ip)
    for ip in ip_lists:print(ip)

if __name__ == '__main__':
    main()

실험용 스크린샷:

위 내용은 LAN에서 라이브 호스트를 검색하기 위해 python-nmap을 호출하는 방법(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.