Python 局域网扫描:获取电脑信息并保存到文本文件
Python 局域网扫描:获取电脑信息并保存到文本文件
本脚本使用 Python 的 socket 库和 os 库来扫描局域网内所有电脑,获取主机名、IP、操作系统、电脑型号等信息,并保存到名为 'computers.txt' 的桌面文本文件中。
import socket
import os
# 获取当前主机名和IP
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
# 获取局域网网段
ip_prefix = '.'.join(ip.split('.')[:-1]) + '.'
# 扫描局域网内所有电脑
computers = []
for i in range(1, 255):
target_ip = ip_prefix + str(i)
response = os.system('ping -n 1 ' + target_ip)
if response == 0:
try:
# 获取电脑信息
computer_name = socket.gethostbyaddr(target_ip)[0]
os_info = os.popen(f'wmic /node:{target_ip} os get caption').read().strip().split('
')[1]
model_info = os.popen(f'wmic /node:{target_ip} computersystem get model').read().strip().split('
')[1]
# 存储电脑信息
computers.append({
'name': computer_name,
'ip': target_ip,
'os': os_info,
'model': model_info
})
except:
pass
# 存储到文本文件
with open('computers.txt', 'w') as f:
for computer in computers:
f.write(f'{computer['name']} {computer['ip']} {computer['os']} {computer['model']}
')
代码解释:
- 获取当前主机名和IP: 使用
socket.gethostname()和socket.gethostbyname()获取当前主机名和IP地址。 - 获取局域网网段: 通过 IP 地址截取前三个部分,拼接 '.' 和 1-255 的数字,生成局域网内所有可能的 IP 地址。
- 扫描局域网内所有电脑: 使用
os.system('ping -n 1 ' + target_ip)命令 ping 每个 IP 地址,如果返回码为 0,则表示该电脑在线。 - 获取电脑信息: 对于在线的电脑,使用
socket.gethostbyaddr()获取电脑名,使用os.popen()执行wmic命令获取操作系统和电脑型号信息。 - 存储电脑信息: 将获取到的电脑信息存储到一个列表中。
- 存储到文本文件: 将列表中的信息写入到名为 'computers.txt' 的文本文件中,每个信息用制表符分隔。
注意:
- 该脚本需要在管理员权限下运行才能获取到所有电脑信息。
wmic命令可能需要在某些系统中进行配置。- 本脚本仅供参考,使用前请确保了解相关安全风险,并谨慎使用。
原文地址: https://www.cveoy.top/t/topic/nIWV 著作权归作者所有。请勿转载和采集!