Use Python to view the live hosts in the LAN

Overview

When some new devices are connected to our network for the first time, and these devices are not screen devices like mobile phones and computers, such as servers, Nas, Raspberry Pi and other hardware, we want to control them through the network connection, but do not know The IP address of the device, at this time, we need to scan the network to find the IP address of our target hardware device.

Common methods such as entering the router management background, we can find our device IP address, or use ready-made software, such as Adbanced IP Scannersoftware , we can also scan the network to achieve the goal we want. However, in fact, all we really need is to know the device name and IP address. No matter logging in to the router or using the software, it seems a bit like killing chickens, so we try to use Python to write a method to find the IP address of the online host on the intranet. script.

 

NMAP

Nmap is a network security tool for network discovery and security auditing. It can detect whether the target host is online, port open status, detect running service type and version information, detect operating system and device type and other information.

Before using it, we need to install the Nmap software. For the WIndow system, you can log in to the download page of the Nmap official website to download the corresponding version and install it.

For MacOS systems, you can use HomeBrew to install, as follows:

brew update
brew install nmap

For Ubuntu/Linux, you can use apt to install, the specific method is as follows:

sudo apt install nmap

After completing the nmap software installation, we continue to install the python module, the specific method is as follows:

pip install nmap
pip install python-nmap

In addition, for the convenience of our code behind, we also need to install a netifaces module, the specific method is as follows:

pip instal netifaces

Detailed script code

First, we can directly use the nmap tool to scan the local area network, as follows:

# 假设本地 ip 地址范围为 192.168.100.1 ~ 192.168.100.255
nmap 192.168.100.1-255 -sP
>>
(...省略部分内容...)
Nmap scan report for 192.168.100.16
Host is up (0.0020s latency).
Nmap scan report for MIMAX-xiaomishouji (192.168.100.17)
Host is up (0.0019s latency).
(...省略部分内容...)

We can see that nmap will scan all ip addresses and output the scan results. If the host is online, then you can see the host name and its IP address. We can also scan an IP address separately, as follows:

# 扫描小米手机ip地址 192.168.100.17
nmap 192.168.100.17
>>
Starting Nmap 7.70 ( https://nmap.org ) at 2018-04-30 17:34 CST
Nmap scan report for MIMAX-xiaomishouji (192.168.100.17)
Host is up (0.00099s latency).
Not shown: 995 filtered ports
PORT     STATE SERVICE
80/tcp   open  http
110/tcp  open  pop3
143/tcp  open  imap
3128/tcp open  squid-http
8080/tcp open  http-proxy

Nmap done: 1 IP address (1 host up) scanned in 4.39 seconds

We do not add -sPparameters , nmap will scan all ports of the IP, and we can see the ports opened by my Xiaomi phone from the results.

Next, use python to complete the above operations, the specific code is as follows:

import nmap
nmScan = nmap.PortScanner()
nmScan.scan(hosts='192.168.100.17', arguments='-sP')
>>
{'nmap': {'command_line': 'nmap -oX - -sP 192.168.100.17', 'scaninfo': {}, 'scanstats': {'downhosts': '0', 'elapsed': '0.01', 'timestr': 'Mon Apr 30 17:39:50 2018', 'totalhosts': '1', 'uphosts': '1'}}, 'scan': {'192.168.100.17': {'addresses': {'ipv4': '192.168.100.17'}, 'hostnames': [{'name': 'MIMAX-xiaomishouji', 'type': 'PTR'}], 'status': {'reason': 'syn-ack', 'state': 'up'}, 'vendor': {}}}} nmScan.scan(hosts='192.168.100.16', arguments='-sP') >> {'nmap': {'command_line': 'nmap -oX - -sP 192.168.100.16', 'scaninfo': {}, 'scanstats': {'downhosts': '0', 'elapsed': '0.01', 'timestr': 'Mon Apr 30 17:40:19 2018', 'totalhosts': '1', 'uphosts': '1'}}, 'scan': {'192.168.100.16': {'addresses': {'ipv4': '192.168.100.16'}, 'hostnames': [{'name': '', 'type': ''}], 'status': {'reason': 'syn-ack', 'state': 'up'}, 'vendor': {}}}} 

It can be seen that, like using nmap directly, if there is a host online, the host name can be displayed, otherwise the host name is empty, so that we can filter the online hosts by judging whether there is a host name in the result. The method of judging whether the host name exists is also very simple. We obtain the namefield and judge whether it is empty. The code is as follows:

mScan['192.168.100.16']['hostnames'][0]['name']
>> '' # 因为 192.168.100.16 不存在在线主机,所以输出为空 

Next, we only need an intranet IP list, and then scan and judge one by one. Obtaining the IP list is also very simple. Generally, in a simple network environment, we can first obtain the gateway address, and then splicing the IP list through the gateway address. The specific code as follows:

import netifaces
gateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
gateway
>>
'192.168.100.1'
# 拼接 IP 列表 ip_lists = [] for ip in range(1, 256): ip_lists.append('{}{}'.format(gateway[:-1], ip)) 

Finally, we can traverse one by one according to the above IP list and use nmap to scan.

full code

Let's integrate the above ideas and organize the code. The following is a display of the complete code:

# filename: lan_ip_scan.py
import netifaces
import nmap


def get_gateways(): return netifaces.gateways()['default'][netifaces.AF_INET][0] def get_ip_lists(gateway): ip_lists = [] for i in range(1, 256): ip_lists.append('{}{}'.format(gateway[:-1], i)) return ip_lists def scan_ip_survial(ip): nmScan = nmap.PortScanner() nmScan.scan(hosts=ip, arguments='-sP') if nmScan[ip]['hostnames'][0]['name']: return {'IP Address:': ip, 'Hostname:': nmScan[ip]['hostnames'][0]['name'] } else: return None def get_all_survial_hosts(): survial_hosts = [] gateway = get_gateways() ip_lists = get_ip_lists(gateway) for ip in ip_lists: scan_rst = scan_ip_survial(ip) if scan_rst: survial_hosts.append(scan_rst) print(scan_rst) return survial_hosts if __name__ == '__main__': get_all_survial_hosts() 

Next, let's try the following run script to see the results:

# 因隐私问题,屏蔽结果的 host 名称
python lan_ip_scan.py
{'IP Address:': '192.168.100.1', 'Hostname:': 'ch***n'}
{'IP Address:': '192.168.100.17', 'Hostname:': 'MIMAX-xiaomishouji'}
{'IP Address:': '192.168.100.18', 'Hostname:': '*****'}
{'IP Address:': '192.168.100.19', 'Hostname:': '***MBP'}
{'IP Address:': '192.168.100.20', 'Hostname:': '***iPhone'}
{'IP Address:': '192.168.100.21', 'Hostname:': '***-xiaomishouji'}
{'IP Address:': '192.168.100.22', 'Hostname:': '****-iPhone'}
{'IP Address:': '192.168.100.23', 'Hostname:': 'raspberrypi'}
{'IP Address:': '192.168.100.26', 'Hostname:': '**'}

So far, we have completed our exploration and coding of using Python to view surviving hosts on the local area network. In this article, we discussed the installation of nmap and related python modules, the simple use of nmap scanning, and some script writing tips. I hope this article can be useful to you. If there are technical or theoretical errors in the article, please point out the exchange and explore together. progress.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325089499&siteId=291194637