Linux下Python3 局域网在线IP快速扫描脚本

本文介绍了一种利用Python的threading模块加速扫描操作的方法,通过ping命令在几秒钟内扫描局域网内的活动邻居,获取其IP地址。提供了一个自动化扫描局域网邻居并报告其IP地址的脚本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/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"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值