网站运营
位置:首页>> 网站运营>> linux下快速列出局域网中所有主机名(计算机名)的脚本

linux下快速列出局域网中所有主机名(计算机名)的脚本

作者:RDX  发布时间:2023-07-22 14:13:38 

标签: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()

来源:https://www.cnblogs.com/jz3025/archive/2020/07/29/13395728.html

0
投稿

猜你喜欢

手机版 网站运营 asp之家 www.aspxhome.com