使用Python写的一个局域网计算机扫描程序
使用Python写的一个局域网计算机扫描程序,本程序为提升速度使用了多线程,基于模块:ipaddress,ping3,subprocess,re,prettytable,threading
程序可扫描指定IP范围的在线情况与检测目标主机的计算机名称,以表格形式打印出来。
程序非常实用,易于理解,敬请参考。
模块
ipaddress,ping3,subprocess,re,prettytable,threading
代码
import ipaddress
from ping3 import ping
import subprocess
import re
import prettytable
start="192.168.1.1"
end="192.168.1.200"
import threading
def get_ip_span(start,end):
start=ipaddress.ip_address(start)
end=ipaddress.ip_address(end)
ipspan=[]
ipaddr=start
while ipaddr<=end:
ipspan.append(str(ipaddr))
ipaddr+=1
return ipspan
def get_hostname(ip):
cmd=subprocess.check_output("ping -a -n 1 {}".format(ip))
cmd=cmd.decode("gbk")
if cmd:
lines=cmd.split("\n")
l1=lines[1]
pattern=".*Ping (.*) \["
names=re.findall(pattern,l1)
return names[0]
class Scan(threading.Thread):
def __init__(self,ip,data:list):
self.ip=ip
self.data=data
threading.Thread.__init__(self)
def run(self):
delay = ping(dest_addr=self.ip, timeout=0.3)
if delay:
delay = int(delay * 1000)
try:
hn = get_hostname(self.ip)
except:
hn = "unknown"
print("{}, 在线, 名称: {}".format(self.ip, hn))
self.data.append((self.ip, hn, delay))
else:
print("{}, 不在线".format(self.ip))
ipaddrs=get_ip_span(start,end)
pt=prettytable.PrettyTable(field_names=("IP","机器名","延时"))
data=[]
thread=[]
def check_thread_alive():
for th in thread:
if th.is_alive():
return True
for ip in ipaddrs:
th=Scan(ip=ip,data=data)
th.start()
thread.append(th)
while 1:
if not check_thread_alive():
break
for row in data:
pt.add_row(row)
print(pt)