作为一个网工我们要知道内网有多少设备连接和ip,我们可以通过python脚本简单的完成。
这里我的python环境为python 3.13
下图是一个大概的运行成果
以下是整个代码复制即用。
import os
import subprocess
import platform
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
# 检查主机是否在线
def ping(host):
# 检测当前操作系统,并选择合适的ping命令
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, '1', '-w', '1000', host] # '-w 1000'设置超时为1秒
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return result.returncode == 0 # 返回True代表主机在线
# 执行网络扫描
def scan_network(network_range, start_ip, end_ip, max_threads=32):
online_hosts = []
offline_hosts = []
# 在给定的IP范围内扫描
def scan_ip(ip):
if ping(ip):
online_hosts.append(ip)
else:
offline_hosts.append(ip)
# 使用ThreadPoolExecutor来管理线程池
with ThreadPoolExecutor(max_workers=max_threads) as executor:
futures = []
for i in range(start_ip, end_ip + 1):
ip = f"{network_range}.{i}"
futures.append(executor.submit(scan_ip, ip))
# 等待所有任务完成
for future in as_completed(futures):
pass
return online_hosts, offline_hosts
# 记录扫描结果到日志
def log_results(online_hosts, offline_hosts):
with open("network_scan_results.log", "a") as log_file:
log_file.write(f"Network Scan Results - {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
log_file.write("Online Hosts:\n")
for host in online_hosts:
log_file.write(f"{host}\n")
log_file.write("Offline Hosts:\n")
for host in offline_hosts:
log_file.write(f"{host}\n")
log_file.write("\n")
if __name__ == "__main__":
network_range = "192.168.1" # 网段
start_ip = 1 # 扫描的起始IP
end_ip = 254 # 扫描的结束IP
print(f"开始扫描 {network_range}.{start_ip} 到 {network_range}.{end_ip}...")
online_hosts, offline_hosts = scan_network(network_range, start_ip, end_ip)
log_results(online_hosts, offline_hosts)
print("网络扫描完成,结果已记录到 network_scan_results.log 文件中。")
配置扫描网段和IP范围:
- 修改脚本中的
network_range
、来自定义start_ip
的end_ip
,需要扫描的网段和IP范围。network_range
:例如"192.168.16"
,表示您要扫描的网段延伸。start_ip
和end_ip
:指定要扫描的IP范围。例如,start_ip = 1
和end_ip = 254
表示扫描192.168.16.1
到192.168.16.254
的所有IP地址。
执行脚本
直接复制保存为ping_network_scan.py
用powershell运行
python ping_network_scan.py
查看结果会在同文件夹下生成一个叫 network_scan_results.log 的文件
结果表明有两个主机在线
标签:network,查看,scan,python,ip,range,hosts,log From: https://blog.csdn.net/2402_86725606/article/details/144384451