linux下快速列出局域網中所有主機名(計算機名)的腳本


最近有列出局域網中所有主機名的需求(SMB協議里的),但是findsmb命令總是列不全,搜了搜網上也沒什么現成的解決方案,於是自己寫了個python腳本

腳本會掃描局域網arp表中所有ip,並嘗試解析其主機名,這樣可以較為徹底地列出相關信息。

注意,運行這個腳本需要samba-common-bin和arp-scan這兩個包,沒有的請先apt install它們。

用法:直接運行或用python3運行,然后輸入需要掃描的網卡名(network interface)(不知道的運行ifconfig可查,一般是ens33、eth0等,出現在該命令輸出最左列),然后回車等待,可能需要運行幾分鍾。

需要root權限運行!!

#!/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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM