#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LAN Neighbour Fast Scanner
Created on Tue Aug 6 16:13:26 2019
@author: farman
"""
import os
import threading
def get_local_ip():
'''
Get IP address of script host machine.
'''
file_name = 'asdfwaefasdf.txt'
os.system('ifconfig>%s'%file_name)
local_ip = []
with open(file_name) as f:
for line in f:
if line.find('inet6')==-1 and line.find('inet') > -1 and line.find('127.0.0.1')==-1:
line = line[:line.find('netmask')]
line = line.strip().split()[1]
local_ip.append(line)
os.system('rm %s'%file_name)
print('\nLAN connection%s : %s'%('' if len(local_ip)<2 else 's', len(local_ip)))
print('-'*40)
for n in range(len(local_ip)):
print(' No.%s -'%(n+1), local_ip[n])
print('\n')
return local_ip
#get_local_ip()
'''
Module "threading" of python3 is used to accelerate the scan operation.
'''
class MyThread(threading.Thread):
"""
This Class is just for result fetching of threaded function.
"""
def __init__(self, function, args):
threading.Thread.__init__(self)
self.function = function
self.args = args
def run(self):
self.result = self.function(*self.args)
def get_result(self):
return self.result
def my_ping(a, b, c, d):
'''
Ping a given ip, and return the result.
The IP address to be pinged is "a.b.c.d".
'''
ip = '%s.%s.%s.%s'%(a, b, c, d)
command = 'ping %s -c 1 -W 1'%ip
#print("ping", ip, end=' --> ')
valid_ip = []
if not os.system(command):
valid_ip.append('%s.%s.%s.%s'%(a, b, c, d))
#print('RESPONSED.')
else:
#print('dummy.')
pass
return valid_ip
def scan_lan(a, b, c, d_begin=1, d_end=255):
'''
Scan LAN neighbours by ping command
in range from "a.b.c.d_begin" to "a.b.c.d_end"
with threading method to reduce time consumption of scanning.
input:
The IP address to be pinged is "a.b.c.d".
outpur:
list of IP address of active neighbours.
'''
threads = [MyThread(my_ping, (a, b, c, d)) for d in range(d_begin, d_end)]
for n in range(len(threads)):
threads[n].start()
for n in range(len(threads)):
threads[n].join()
valid_ip = []
for n in range(len(threads)):
valid_ip += threads[n].get_result()
return valid_ip
#print(scan_lan(192, 168, 43))
def auto_scan():
'''
Auto scan LAN neighbours, report and return their IP addresses.
Calling this function directly is the right manner to
get IP addresses of LAN neighbouts
because it's convinient and so comfort:)
'''
local_ip = get_local_ip()
if not len(local_ip):
return
valid_ip = []
for ip in local_ip:
[a, b, c, d] = ip.split('.')
valid_ip += scan_lan(a, b, c)
print('LAN neighbour%s : %s'%(
'' if len(valid_ip)<2 else 's',
len(valid_ip)))
print('-'*40)
for n in range(len(valid_ip)):
print(' No.%s -'%(n+1), valid_ip[n])
return valid_ip
if __name__ == '__main__':
print('\n\nLAN neighbour IP address Scanner')
print('-'*40)
print(' '*22, 'Farman@2019.08.06\n')
auto_scan()
input("Press 'Enter' to exit ...")
几秒钟时间就可以出结果。
使用:
(1)复制上述代码,保存为 .py 为后缀的文件[filename].py
(2)shell下运行"python3 [filename].py
或chmod +x [filename].py,添加运行属性,图形界面双击运行或者shell下运行"./[filename].py"