用脚本获取网络拓扑信息

wen 实用脚本 3

本文目录导读:

用脚本获取网络拓扑信息

  1. Linux环境脚本 (Bash)
  2. Python高级拓扑发现脚本
  3. Windows环境脚本 (PowerShell)
  4. 快速使用的单行命令
  5. 使用方法

我来提供几种获取网络拓扑信息的脚本方案,包括Windows和Linux环境。

Linux环境脚本 (Bash)

基础网络拓扑发现脚本

#!/bin/bash
# 网络拓扑信息收集脚本
# network_topology.sh
echo "========================================="
echo "网络拓扑信息收集"
echo "时间: $(date)"
echo "========================================="
# 1. 获取本机网络接口信息
echo -e "\n[1] 网络接口信息:"
ip addr show | grep -E "^[0-9]|inet " | awk '{
    if ($1 ~ /^[0-9]/) {
        iface = $2
        gsub(/:/, "", iface)
        printf "\n接口: %s\n", iface
    }
    if ($1 == "inet") {
        printf "  IP地址: %s\n", $2
        printf "  广播地址: %s\n", $4
    }
}'
# 2. 路由表信息
echo -e "\n[2] 路由表:"
ip route show | while read line; do
    echo "  $line"
done
# 3. ARP表 - 直接连接的设备
echo -e "\n[3] ARP表 (直接连接设备):"
arp -n 2>/dev/null || ip neigh show
# 4. 活动连接
echo -e "\n[4] 活动网络连接 (TCP):"
ss -tun | head -20
# 5. DNS配置
echo -e "\n[5] DNS配置:"
cat /etc/resolv.conf 2>/dev/null || echo "无法读取DNS配置"
# 6. 防火墙规则
echo -e "\n[6] 防火墙规则:"
if command -v iptables &> /dev/null; then
    sudo iptables -L -n 2>/dev/null | head -20
else
    echo "iptables不可用"
fi
# 7. 网络服务状态
echo -e "\n[7] 网络服务状态:"
systemctl list-units --type=service --state=running | grep -E "network|ssh|http|dns" 2>/dev/null || echo "无法获取服务状态"

Python高级拓扑发现脚本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# network_topology_advanced.py
import subprocess
import re
import json
import socket
import netifaces
import ipaddress
from datetime import datetime
class NetworkTopologyCollector:
    def __init__(self):
        self.topology = {
            "timestamp": datetime.now().isoformat(),
            "hostname": socket.gethostname(),
            "interfaces": [],
            "routing_table": [],
            "arp_table": [],
            "discovered_devices": []
        }
    def get_interfaces(self):
        """获取所有网络接口信息"""
        interfaces = netifaces.interfaces()
        for iface in interfaces:
            details = netifaces.ifaddresses(iface)
            iface_info = {
                "name": iface,
                "mac": "",
                "ipv4": [],
                "ipv6": []
            }
            # MAC地址
            if netifaces.AF_LINK in details:
                iface_info["mac"] = details[netifaces.AF_LINK][0].get("addr", "")
            # IPv4地址
            if netifaces.AF_INET in details:
                for addr in details[netifaces.AF_INET]:
                    iface_info["ipv4"].append({
                        "address": addr.get("addr", ""),
                        "netmask": addr.get("netmask", ""),
                        "broadcast": addr.get("broadcast", "")
                    })
            # IPv6地址
            if netifaces.AF_INET6 in details:
                for addr in details[netifaces.AF_INET6]:
                    iface_info["ipv6"].append({
                        "address": addr.get("addr", ""),
                        "netmask": addr.get("netmask", "")
                    })
            if iface_info["ipv4"] or iface_info["ipv6"]:
                self.topology["interfaces"].append(iface_info)
        return self.topology["interfaces"]
    def get_routing_table(self):
        """获取路由表"""
        try:
            result = subprocess.run(["ip", "route"], capture_output=True, text=True)
            for line in result.stdout.strip().split("\n"):
                if line:
                    parts = line.split()
                    route = {
                        "destination": parts[0] if len(parts) > 0 else "",
                        "via": parts[2] if len(parts) > 2 and parts[1] == "via" else "",
                        "device": parts[-1] if len(parts) > 2 else ""
                    }
                    self.topology["routing_table"].append(route)
        except Exception as e:
            print(f"获取路由表错误: {e}")
        return self.topology["routing_table"]
    def get_arp_table(self):
        """获取ARP表"""
        try:
            result = subprocess.run(["arp", "-n"], capture_output=True, text=True)
            lines = result.stdout.strip().split("\n")[1:]  # 跳过标题
            for line in lines:
                if line:
                    parts = line.split()
                    if len(parts) >= 4:
                        arp_entry = {
                            "ip_address": parts[0],
                            "mac_address": parts[2],
                            "interface": parts[-1] if len(parts) > 3 else "",
                            "type": parts[-2] if len(parts) > 4 else ""
                        }
                        self.topology["arp_table"].append(arp_entry)
        except Exception as e:
            print(f"获取ARP表错误: {e}")
        return self.topology["arp_table"]
    def ping_scan(self, subnet):
        """Ping扫描子网发现设备"""
        try:
            network = ipaddress.IPv4Network(subnet, strict=False)
            print(f"扫描子网: {network}")
            active_hosts = []
            for host in network.hosts():
                host_str = str(host)
                result = subprocess.run(
                    ["ping", "-c", "1", "-W", "1", host_str],
                    capture_output=True,
                    timeout=2
                )
                if result.returncode == 0:
                    try:
                        hostname = socket.gethostbyaddr(host_str)[0]
                    except:
                        hostname = ""
                    device_info = {
                        "ip": host_str,
                        "hostname": hostname,
                        "mac": self.get_mac_from_arp(host_str)
                    }
                    self.topology["discovered_devices"].append(device_info)
                    active_hosts.append(host_str)
                    print(f"  发现设备: {host_str} - {hostname}")
            return active_hosts
        except Exception as e:
            print(f"扫描错误: {e}")
            return []
    def get_mac_from_arp(self, ip):
        """从ARP缓存获取MAC地址"""
        for entry in self.topology["arp_table"]:
            if entry["ip_address"] == ip:
                return entry["mac_address"]
        return ""
    def export_json(self, filename="network_topology.json"):
        """导出为JSON文件"""
        with open(filename, "w") as f:
            json.dump(self.topology, f, indent=2)
        print(f"拓扑信息已导出到: {filename}")
    def print_summary(self):
        """打印摘要信息"""
        print("\n" + "="*50)
        print("网络拓扑摘要")
        print("="*50)
        print(f"主机名: {self.topology['hostname']}")
        print(f"时间: {self.topology['timestamp']}")
        print(f"网络接口数: {len(self.topology['interfaces'])}")
        print(f"ARP表条目: {len(self.topology['arp_table'])}")
        print(f"发现设备数: {len(self.topology['discovered_devices'])}")
        print(f"路由条目: {len(self.topology['routing_table'])}")
        print("="*50)
        # 打印发现的设备
        if self.topology['discovered_devices']:
            print("\n发现的网络设备:")
            for device in self.topology['discovered_devices']:
                print(f"  {device['ip']:15} {device['hostname']:30} {device['mac']}")
def main():
    collector = NetworkTopologyCollector()
    print("开始收集网络拓扑信息...")
    # 收集基本信息
    collector.get_interfaces()
    collector.get_routing_table()
    collector.get_arp_table()
    # 显示网络接口
    print("\n网络接口:")
    for iface in collector.topology["interfaces"]:
        print(f"  {iface['name']}: {iface['mac']}")
        for ip in iface['ipv4']:
            print(f"    IPv4: {ip['address']}/{ip['netmask']}")
    # 询问是否进行主动扫描
    scan = input("\n是否进行网络扫描? (y/n): ").lower()
    if scan == 'y':
        subnet = input("输入要扫描的子网 (如 192.168.1.0/24): ")
        if subnet:
            collector.ping_scan(subnet)
    # 导出结果
    collector.print_summary()
    collector.export_json()
if __name__ == "__main__":
    main()

Windows环境脚本 (PowerShell)

# network_topology.ps1
Write-Host "=========================================" -ForegroundColor Cyan
Write-Host "网络拓扑信息收集 - Windows" -ForegroundColor Cyan
Write-Host "时间: $(Get-Date)" -ForegroundColor Cyan
Write-Host "=========================================" -ForegroundColor Cyan
# 1. 网络适配器信息
Write-Host "`n[1] 网络适配器信息:" -ForegroundColor Yellow
Get-NetAdapter | Select-Object Name, Status, MacAddress, LinkSpeed
# 2. IP配置
Write-Host "`n[2] IP配置:" -ForegroundColor Yellow
Get-NetIPAddress | Where-Object {$_.AddressFamily -eq "IPv4"} | 
    Select-Object InterfaceAlias, IPAddress, PrefixLength, SubnetMask
# 3. 路由表
Write-Host "`n[3] 路由表 (关键路由):" -ForegroundColor Yellow
Get-NetRoute | Where-Object {$_.AddressFamily -eq "IPv4"} | 
    Select-Object DestinationPrefix, NextHop, RouteMetric, InterfaceAlias
# 4. ARP缓存
Write-Host "`n[4] ARP缓存:" -ForegroundColor Yellow
Get-NetNeighbor | Where-Object {$_.AddressFamily -eq "IPv4" -and $_.State -eq "Reachable"} | 
    Select-Object IPAddress, LinkLayerAddress, InterfaceAlias
# 5. 网络连接
Write-Host "`n[5] 活动网络连接:" -ForegroundColor Yellow
Get-NetTCPConnection | Group-Object -Property State | 
    Select-Object Name, Count
# 6. DNS缓存
Write-Host "`n[6] DNS缓存统计:" -ForegroundColor Yellow
$dnsCache = Get-DnsClientCache
Write-Host "  DNS缓存条目数: $($dnsCache.Count)"
# 7. 网络共享
Write-Host "`n[7] 网络共享:" -ForegroundColor Yellow
Get-SmbShare | Select-Object Name, Path, Description
# 8. 防火墙规则
Write-Host "`n[8] 防火墙入站规则 (关键):" -ForegroundColor Yellow
Get-NetFirewallRule | Where-Object {$_.Direction -eq "Inbound" -and $_.Enabled -eq "True"} | 
    Select-Object DisplayName, Action, Profile | Format-Table -AutoSize
# 保存到文件
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$filename = "network_topology_$timestamp.txt"
$output = @"
网络拓扑信息
时间: $(Get-Date)
主机名: $env:COMPUTERNAME
IP地址: $(Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike "*Loopback*"} | 
    Select-Object -ExpandProperty IPAddress)
"@
$output | Out-File -FilePath $filename
Write-Host "`n信息已保存到: $filename" -ForegroundColor Green

快速使用的单行命令

Linux

# 快速查看网络拓扑
echo "=== 接口 ===" && ip -br addr && echo "=== 路由 ===" && ip route && echo "=== ARP ===" && arp -n
# 导出到文件
ip addr; ip route; arp -n; ss -tun > network_info_$(date +%Y%m%d).txt

Windows

# 快速查看
ipconfig /all; Get-NetRoute | Format-Table; arp -a
# 导出到文件
Get-NetAdapter | Export-Csv network_adapters.csv -NoTypeInformation
Get-NetIPAddress | Export-Csv network_ips.csv -NoTypeInformation

使用方法

  1. Linux脚本: 保存为 .sh 文件,运行 chmod +x network_topology.sh && ./network_topology.sh

  2. Python脚本: 需要安装依赖 pip install netifaces,然后运行 python3 network_topology_advanced.py

  3. PowerShell脚本: 以管理员身份运行 powershell -ExecutionPolicy Bypass -File network_topology.ps1

这些脚本会收集基本的网络拓扑信息,包括接口信息、路由表、ARP表等,Python版本还支持主动扫描发现网络中的设备。

上一篇怎么用脚本获取已安装更新

下一篇当前分类已是最新一篇

抱歉,评论功能暂时关闭!