Python 获取局域网内所有电脑信息并保存到文本文件
Python 获取局域网内所有电脑信息并保存到文本文件
该程序通过 ipconfig 命令获取本机 IP 和主机名,然后通过 ping 扫描局域网内所有 IP,再通过 nslookup 命令获取主机名和 wmic 命令获取操作系统信息,最后将所有信息存储到文件中。最后使用 os.system 命令打开文本文件。
import os
import platform
def get_local_computers_info():
computers = []
# 获取本机ip
local_ip = os.popen("ipconfig | findstr IPv4 | findstr 192").read().split(":")[1].strip()
# 获取本机主机名
host_name = platform.node()
computers.append({'主机名': host_name, 'IP': local_ip, '操作系统': platform.system()})
# 获取局域网内所有电脑信息
ip_prefix = local_ip.rsplit(".", 1)[0] + "."
for i in range(1, 255):
ip = ip_prefix + str(i)
if ip != local_ip:
res = os.system("ping -n 1 -w 1000 " + ip)
if res == 0: # ping成功,说明该ip对应的电脑在线
try:
host_name = os.popen("nslookup " + ip + " | findstr Name").read().split("=")[1].strip()
except:
host_name = "未知"
computers.append({'主机名': host_name, 'IP': ip, '操作系统': get_remote_computer_os(ip)})
return computers
def get_remote_computer_os(ip):
os_info = os.popen("wmic /node:" + ip + " os get Caption").read().split("\n")[1].strip()
if not os_info:
os_info = "未知"
return os_info
def save_to_file(computers):
with open("局域网电脑信息.txt", "w") as file:
for computer in computers:
file.write(str(computer) + "\n")
if __name__ == '__main__':
computers = get_local_computers_info()
save_to_file(computers)
os.system("start 局域网电脑信息.txt")
使用方法:
- 将代码保存为
.py文件,例如get_computer_info.py - 在命令行中运行该文件:
python get_computer_info.py - 运行程序后,会在桌面生成一个名为
局域网电脑信息.txt的文本文件,其中包含了局域网内所有电脑的信息。
注意事项:
- 该程序可能需要管理员权限才能运行。
- 由于网络环境的差异,该程序可能无法获取所有电脑的信息。
- 该程序只适用于 Windows 系统。
其他功能:
- 可以修改代码,将获取的信息保存到其他格式的文件中,例如 CSV 文件。
- 可以添加代码,将获取的信息整理成表格,方便查看。
- 可以添加代码,将获取的信息发送到邮件或其他平台。
代码解释:
get_local_computers_info()函数用于获取局域网内所有电脑的信息。get_remote_computer_os()函数用于获取远程电脑的操作系统信息。save_to_file()函数用于将获取的信息保存到文本文件中。os.system()函数用于执行系统命令。
希望这篇文章能够帮助您了解如何使用 Python 获取局域网内所有电脑的信息。
免责声明:
本文章仅供学习参考,请勿用于任何非法目的。作者不对任何因使用本文内容而产生的后果负责。
原文地址: https://www.cveoy.top/t/topic/nIUm 著作权归作者所有。请勿转载和采集!