Script under linux to Quickly List All Host Names (Computer Names) in LAN

  • 2021-08-21 21:54:30
  • OfStack

LAN has recently listed all the host name requirements (SMB protocol), but the findsmb command is always incomplete, search the search network also no ready-made solutions, so I wrote an python script

The script scans all ip in the LAN arp table and attempts to resolve their hostnames so that the relevant information can be listed more thoroughly.

Note that two packages, samba-common-bin and arp-scan, are required to run this script. If you don't have them, please start with apt install.

Usage: Run directly or with python3, then enter the name of the network card to be scanned (network interface) (unknown ifconfig can be checked, ens33, eth0, etc., which appear in the leftmost column of the command output), and then enter and wait, which may take several minutes to run.

Need root permission to run! !


#!/usr/bin/env python3

import os

def shellrun(cmd):
    a = os.popen(cmd)
    b = a.read()
    c = b.split('\n')
    return c

def cutarpresult(lst):
    a = []
    b = []
    for line in lst[2:]:
        if line != '':
            a.append(line)
        else:
            break
    for line in a:
        b.append(line.split('\t')[0])
    return b

def commandmaker(ip):
    return 'nmblookup -A ' + ip

def getrst(iplist):
    rst = []
    for ip in iplist:
        rst.append(shellrun(commandmaker(ip)))
    return rst

def washrst(rst):
    rtn = []
    for line in rst:
        if line[1].split(' ')[1] != 'reply':
            rtn.append(line[:-1])
    return rtn

def main():
    interface = input('which interface to use: ')
    iplist = cutarpresult(shellrun('arp-scan -I ' + interface + ' -l'))
    for rs in washrst(getrst(iplist)):
        for line in rs:
            print(line)

if __name__ == '__main__':
    main()

Related articles: