The script of listing all host names (computer names) in LAN under Linux

Time:2021-4-28

Recently, there is a need to list all the host names in the LAN (in SMB protocol), but the findsmb command is always incomplete. There is no ready-made solution after searching the Internet, so I wrote a python script

The script will scan all IP addresses in the local area network ARP table and try to resolve their host names, so that the relevant information can be listed more thoroughly.

Note that the samba common bin and ARP scan packages are required to run this script. If not, please apt install them first.

Usage: run directly or with Python 3, and then enter the name of the network interface to be scanned (if you don’t know, run ifconfig, usually ens33, eth0, etc., which appears in the leftmost column of the command output), and then enter to wait. It may take a few 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()