ip 命令详解#

ip 是 Linux 系统中用于配置和显示网络接口、路由、隧道等网络信息的现代命令行工具。它是 ifconfigroute 等传统命令的替代品,功能更强大、更灵活,是现代 Linux 系统网络管理的标准工具。

入门#

基本用法#

# 显示所有网络接口
ip link show

# 显示特定接口信息
ip link show eth0

# 显示接口的 IP 地址
ip addr show

# 显示路由表
ip route show

# 启用网络接口
ip link set eth0 up

# 禁用网络接口
ip link set eth0 down

常用子命令#

子命令说明
link配置网络接口
addr配置 IP 地址
route配置路由表
neigh管理邻居表(ARP 表)
tunnel配置隧道
maddr管理多播地址
mroute管理多播路由

基本示例#

# 查看所有网络接口
ip link show

# 输出示例:
# 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
#     link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
# 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
#     link/ether 00:11:22:33:44:55 brd ff:ff:ff:ff:ff:ff

# 查看接口 IP 地址
ip addr show eth0

# 查看路由表
ip route show

中级#

网络接口配置#

# 启用接口
ip link set eth0 up

# 禁用接口
ip link set eth0 down

# 设置接口 MTU
ip link set eth0 mtu 9000

# 修改 MAC 地址
ip link set eth0 address 00:11:22:33:44:55

# 启用混杂模式
ip link set eth0 promisc on

# 禁用混杂模式
ip link set eth0 promisc off

# 设置接口别名
ip link set eth0 name newname

IP 地址管理#

# 添加 IP 地址
ip addr add 192.168.1.100/24 dev eth0

# 添加多个 IP 地址
ip addr add 192.168.1.100/24 dev eth0
ip addr add 192.168.1.101/24 dev eth0

# 删除 IP 地址
ip addr del 192.168.1.100/24 dev eth0

# 查看特定接口的 IP 地址
ip addr show eth0

# 刷新接口的所有 IP 地址
ip addr flush dev eth0

# 添加 IPv6 地址
ip -6 addr add 2001:db8::1/64 dev eth0

路由管理#

# 添加默认路由
ip route add default via 192.168.1.1

# 添加特定路由
ip route add 192.168.2.0/24 via 192.168.1.1

# 添加带设备的路由
ip route add 192.168.2.0/24 dev eth0

# 删除路由
ip route del 192.168.2.0/24 via 192.168.1.1

# 查看路由表
ip route show

# 查看特定路由
ip route get 8.8.8.8

# 清空路由表
ip route flush table main

高级#

高级接口配置#

# 创建虚拟接口
ip link add link eth0 name eth0.10 type vlan id 10
ip link set eth0.10 up

# 创建网桥
ip link add name br0 type bridge
ip link set br0 up

# 将接口添加到网桥
ip link set eth0 master br0

# 从网桥移除接口
ip link set eth0 nomaster

# 创建 veth 对
ip link add veth0 type veth peer name veth1
ip link set veth0 up
ip link set veth1 up

# 删除接口
ip link delete veth0

高级路由配置#

# 添加带优先级的路由
ip route add 192.168.2.0/24 via 192.168.1.1 metric 100

# 添加带表的路由
ip route add 192.168.2.0/24 via 192.168.1.1 table custom

# 查看所有路由表
ip route show table all

# 添加策略路由
ip rule add from 192.168.1.100 table custom

# 查看策略路由
ip rule show

# 删除策略路由
ip rule del from 192.168.1.100 table custom

# 添加多路径路由
ip route add default nexthop via 192.168.1.1 weight 1 nexthop via 192.168.1.2 weight 1

邻居表管理#

# 查看邻居表(ARP 表)
ip neigh show

# 添加静态邻居条目
ip neigh add 192.168.1.1 lladdr 00:11:22:33:44:55 dev eth0

# 删除邻居条目
ip neigh del 192.168.1.1 dev eth0

# 刷新邻居表
ip neigh flush dev eth0

# 查看特定接口的邻居表
ip neigh show dev eth0

# 查看邻居表详细信息
ip neigh show nud reachable

大师#

网络接口监控#

#!/bin/bash
# 网络接口监控脚本

INTERFACE="eth0"
LOG_FILE="interface_monitor.log"

# 监控接口状态
monitor_interface() {
    while true; do
        TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
        
        RX_BYTES=$(ip -s link show $INTERFACE | awk '/RX:/ {getline; print $1}')
        TX_BYTES=$(ip -s link show $INTERFACE | awk '/TX:/ {getline; print $1}')
        
        echo "$TIMESTAMP - RX: $RX_BYTES bytes, TX: $TX_BYTES bytes" >> $LOG_FILE
        
        sleep 60
    done
}

# 监控接口状态变化
monitor_interface_status() {
    local last_state=""
    
    while true; do
        local current_state=$(ip link show $INTERFACE | grep -o "state [A-Z]*" | cut -d' ' -f2)
        
        if [ "$current_state" != "$last_state" ]; then
            TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
            echo "$TIMESTAMP - Interface $INTERFACE state changed: $last_state -> $current_state" >> $LOG_FILE
            last_state=$current_state
        fi
        
        sleep 10
    done
}

# 主函数
main() {
    case "$1" in
        monitor)
            monitor_interface
            ;;
        status)
            monitor_interface_status
            ;;
        *)
            echo "Usage: $0 {monitor|status}"
            exit 1
            ;;
    esac
}

main "$@"

网络配置备份与恢复#

#!/bin/bash
# 网络配置备份与恢复脚本

BACKUP_DIR="/etc/network/backups"
mkdir -p $BACKUP_DIR

# 备份网络配置
backup_config() {
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local backup_file="$BACKUP_DIR/network_config_$timestamp.sh"
    
    echo "# Network Configuration Backup - $timestamp" > $backup_file
    echo "# Generated on $(date)" >> $backup_file
    echo "" >> $backup_file
    
    # 备份接口配置
    ip link show | grep -E "^[0-9]+:" | while read line; do
        local interface=$(echo $line | awk '{print $2}' | cut -d: -f1)
        local state=$(echo $line | grep -o "state [A-Z]*" | cut -d' ' -f2)
        
        echo "# Interface: $interface" >> $backup_file
        echo "ip link set $interface $([[ "$state" == "UP" ]] && echo "up" || echo "down")" >> $backup_file
        
        # 备份 IP 地址
        ip addr show $interface 2>/dev/null | grep "inet " | while read addr_line; do
            local ip_addr=$(echo $addr_line | awk '{print $2}')
            echo "ip addr add $ip_addr dev $interface" >> $backup_file
        done
        
        echo "" >> $backup_file
    done
    
    # 备份路由配置
    echo "# Routes" >> $backup_file
    ip route show | while read route; do
        echo "ip route add $route" >> $backup_file
    done
    
    echo "Backup saved to: $backup_file"
}

# 恢复网络配置
restore_config() {
    local backup_file=$1
    
    if [ ! -f "$backup_file" ]; then
        echo "Backup file not found: $backup_file"
        return 1
    fi
    
    echo "Restoring network configuration from $backup_file..."
    
    # 先禁用所有接口
    ip link show | grep -E "^[0-9]+:" | awk '{print $2}' | cut -d: -f1 | while read interface; do
        if [ "$interface" != "lo" ]; then
            ip link set $interface down
        fi
    done
    
    # 执行备份脚本
    bash $backup_file
    
    echo "Network configuration restored"
}

# 列出备份
list_backups() {
    echo "Available backups:"
    ls -lh $BACKUP_DIR/
}

# 主函数
main() {
    case "$1" in
        backup)
            backup_config
            ;;
        restore)
            restore_config "$2"
            ;;
        list)
            list_backups
            ;;
        *)
            echo "Usage: $0 {backup|restore|list}"
            exit 1
            ;;
    esac
}

main "$@"

网络性能优化#

#!/bin/bash
# 网络性能优化脚本

optimize_interface() {
    local interface=$1
    
    echo "Optimizing interface: $interface"
    
    # 设置 MTU
    ip link set $interface mtu 9000
    
    # 启用 GRO(Generic Receive Offload)
    ethtool -K $interface gro on 2>/dev/null
    
    # 启用 GSO(Generic Segmentation Offload)
    ethtool -K $interface gso on 2>/dev/null
    
    # 启用 TSO(TCP Segmentation Offload)
    ethtool -K $interface tso on 2>/dev/null
    
    # 调整队列长度
    ip link set $interface txqueuelen 10000
    
    echo "Interface $interface optimized"
}

# 优化系统网络参数
optimize_system_params() {
    echo "Optimizing system network parameters..."
    
    # 启用 TCP 窗口缩放
    sysctl -w net.ipv4.tcp_window_scaling=1
    
    # 调整 TCP 缓冲区大小
    sysctl -w net.core.rmem_max=16777216
    sysctl -w net.core.wmem_max=16777216
    sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216"
    sysctl -w net.ipv4.tcp_wmem="4096 65536 16777216"
    
    # 启用 TCP 快速打开
    sysctl -w net.ipv4.tcp_fastopen=3
    
    # 禁用 TCP 时间戳
    sysctl -w net.ipv4.tcp_timestamps=0
    
    echo "System network parameters optimized"
}

# 恢复默认设置
restore_defaults() {
    local interface=$1
    
    echo "Restoring defaults for interface: $interface"
    
    ip link set $interface mtu 1500
    ip link set $interface txqueuelen 1000
    
    echo "Defaults restored for $interface"
}

# 主函数
main() {
    case "$1" in
        optimize)
            optimize_interface "$2"
            optimize_system_params
            ;;
        restore)
            restore_defaults "$2"
            ;;
        *)
            echo "Usage: $0 {optimize|restore}"
            exit 1
            ;;
    esac
}

main "$@"

无敌#

企业级网络管理系统#

#!/bin/bash
# 企业级网络管理系统

CONFIG_FILE="/etc/network_manager/config.conf"
LOG_DIR="/var/log/network_manager"
STATE_DIR="/var/run/network_manager"

mkdir -p $LOG_DIR $STATE_DIR

# 加载配置
source $CONFIG_FILE

# 初始化接口
init_interface() {
    local interface=$1
    local config_file="$STATE_DIR/${interface}.conf"
    
    if [ -f "$config_file" ]; then
        source $config_file
        
        # 配置接口
        ip link set $interface up
        
        if [ -n "$IP_ADDR" ]; then
            ip addr add $IP_ADDR dev $interface
        fi
        
        if [ -n "$MTU" ]; then
            ip link set $interface mtu $MTU
        fi
        
        echo "Interface $interface initialized"
    fi
}

# 监控接口状态
monitor_interface() {
    local interface=$1
    local state_file="$STATE_DIR/${interface}.state"
    
    while true; do
        local current_state=$(ip link show $interface 2>/dev/null | grep -o "state [A-Z]*" | cut -d' ' -f2)
        
        if [ -n "$current_state" ]; then
            echo "$current_state" > $state_file
        fi
        
        sleep $MONITOR_INTERVAL
    done
}

# 故障恢复
failover_recovery() {
    local primary=$1
    local secondary=$2
    
    local primary_state=$(cat "$STATE_DIR/${primary}.state" 2>/dev/null)
    
    if [ "$primary_state" != "UP" ]; then
        echo "Primary interface $primary is down, switching to $secondary"
        
        # 激活备用接口
        ip link set $secondary up
        
        # 更新路由
        ip route replace default via $SECONDARY_GW dev $secondary
    fi
}

# 主程序
main() {
    # 初始化所有接口
    for interface in "${MANAGED_INTERFACES[@]}"; do
        init_interface $interface
        monitor_interface $interface &
    done
    
    # 故障监控
    while true; do
        failover_recovery $PRIMARY_INTERFACE $SECONDARY_INTERFACE
        sleep $FAILOVER_CHECK_INTERVAL
    done
}

main

智能网络配置系统#

#!/bin/bash
# 智能网络配置系统

CONFIG_DIR="/etc/smart_network"
LOG_FILE="/var/log/smart_network.log"

mkdir -p $CONFIG_DIR

# 检测网络环境
detect_network_environment() {
    echo "Detecting network environment..."
    
    # 检测网关
    local gateway=$(ip route | grep default | awk '{print $3}')
    echo "Gateway: $gateway" >> $LOG_FILE
    
    # 检测 DNS
    local dns=$(grep nameserver /etc/resolv.conf | head -1 | awk '{print $2}')
    echo "DNS: $dns" >> $LOG_FILE
    
    # 检测网络类型
    if ping -c 1 -W 2 $gateway > /dev/null 2>&1; then
        echo "Network type: Wired" >> $LOG_FILE
    else
        echo "Network type: Wireless" >> $LOG_FILE
    fi
}

# 自动配置网络
auto_configure_network() {
    local interface=$1
    
    echo "Auto-configuring network for $interface..."
    
    # 检测网络环境
    detect_network_environment
    
    # 应用配置
    local config_file="$CONFIG_DIR/${interface}.conf"
    
    if [ -f "$config_file" ]; then
        source $config_file
        
        # 配置 IP 地址
        if [ -n "$IP_ADDR" ]; then
            ip addr add $IP_ADDR dev $interface
        fi
        
        # 配置路由
        if [ -n "$GATEWAY" ]; then
            ip route add default via $GATEWAY
        fi
        
        # 配置 DNS
        if [ -n "$DNS_SERVERS" ]; then
            echo "nameserver $DNS_SERVERS" > /etc/resolv.conf
        fi
        
        echo "Network auto-configuration completed"
    else
        echo "Configuration file not found: $config_file"
    fi
}

# 网络健康检查
network_health_check() {
    local interface=$1
    
    echo "Performing network health check..."
    
    # 检查接口状态
    local state=$(ip link show $interface | grep -o "state [A-Z]*" | cut -d' ' -f2)
    echo "Interface state: $state"
    
    # 检查 IP 地址
    local ip_addr=$(ip addr show $interface | grep "inet " | awk '{print $2}')
    echo "IP address: $ip_addr"
    
    # 检查连通性
    local gateway=$(ip route | grep default | awk '{print $3}')
    if ping -c 1 -W 2 $gateway > /dev/null 2>&1; then
        echo "Gateway connectivity: OK"
    else
        echo "Gateway connectivity: FAILED"
    fi
    
    # 检查 DNS
    local dns=$(grep nameserver /etc/resolv.conf | head -1 | awk '{print $2}')
    if ping -c 1 -W 2 $dns > /dev/null 2>&1; then
        echo "DNS connectivity: OK"
    else
        echo "DNS connectivity: FAILED"
    fi
}

# 主函数
main() {
    case "$1" in
        detect)
            detect_network_environment
            ;;
        configure)
            auto_configure_network "$2"
            ;;
        health)
            network_health_check "$2"
            ;;
        *)
            echo "Usage: $0 {detect|configure|health}"
            exit 1
            ;;
    esac
}

main "$@"

网络故障诊断系统#

#!/bin/bash
# 网络故障诊断系统

DIAGNOSTIC_LOG="/tmp/network_diagnostic_$(date +%Y%m%d_%H%M%S).log"

# 诊断网络接口
diagnose_interfaces() {
    echo "=== Network Interface Diagnosis ===" >> $DIAGNOSTIC_LOG
    
    ip link show >> $DIAGNOSTIC_LOG
    echo "" >> $DIAGNOSTIC_LOG
    
    ip addr show >> $DIAGNOSTIC_LOG
    echo "" >> $DIAGNOSTIC_LOG
}

# 诊断路由
diagnose_routes() {
    echo "=== Route Diagnosis ===" >> $DIAGNOSTIC_LOG
    
    ip route show >> $DIAGNOSTIC_LOG
    echo "" >> $DIAGNOSTIC_LOG
    
    ip route get 8.8.8.8 >> $DIAGNOSTIC_LOG
    echo "" >> $DIAGNOSTIC_LOG
}

# 诊断邻居表
diagnose_neighbors() {
    echo "=== Neighbor Table Diagnosis ===" >> $DIAGNOSTIC_LOG
    
    ip neigh show >> $DIAGNOSTIC_LOG
    echo "" >> $DIAGNOSTIC_LOG
}

# 诊断特定问题
diagnose_specific_issue() {
    local issue=$1
    
    case $issue in
        "no_internet")
            echo "=== Diagnosing No Internet Access ===" >> $DIAGNOSTIC_LOG
            
            # 检查接口状态
            ip link show | grep -v "state DOWN" >> $DIAGNOSTIC_LOG
            
            # 检查路由
            ip route show default >> $DIAGNOSTIC_LOG
            
            # 检查 DNS
            cat /etc/resolv.conf >> $DIAGNOSTIC_LOG
            ;;
        "slow_network")
            echo "=== Diagnosing Slow Network ===" >> $DIAGNOSTIC_LOG
            
            # 检查接口统计
            ip -s link show >> $DIAGNOSTIC_LOG
            
            # 检查 MTU
            ip link show | grep mtu >> $DIAGNOSTIC_LOG
            ;;
        "ip_conflict")
            echo "=== Diagnosing IP Conflict ===" >> $DIAGNOSTIC_LOG
            
            # 检查邻居表
            ip neigh show nud reachable >> $DIAGNOSTIC_LOG
            
            # 检查重复 IP
            arping -c 2 $(ip addr show | grep "inet " | head -1 | awk '{print $2}' | cut -d/ -f1) >> $DIAGNOSTIC_LOG 2>&1
            ;;
        *)
            echo "Unknown issue: $issue" >> $DIAGNOSTIC_LOG
            ;;
    esac
}

# 生成诊断报告
generate_diagnostic_report() {
    echo "Network Diagnostic Report - $(date)" > $DIAGNOSTIC_LOG
    echo "================================" >> $DIAGNOSTIC_LOG
    echo "" >> $DIAGNOSTIC_LOG
    
    diagnose_interfaces
    diagnose_routes
    diagnose_neighbors
    
    if [ -n "$1" ]; then
        diagnose_specific_issue "$1"
    fi
    
    echo -e "\nDiagnostic completed. Log saved to: $DIAGNOSTIC_LOG"
}

# 主函数
main() {
    generate_diagnostic_report "$1"
}

main "$@"

最佳实践#

  1. 使用 ip 命令替代传统工具:优先使用 ip 命令替代 ifconfigroute
  2. 配置持久化:使用网络配置文件使配置持久化
  3. 备份配置:在进行重要配置更改前,先备份当前配置
  4. 监控接口状态:定期监控网络接口状态,及时发现和解决问题
  5. 合理设置 MTU:根据网络环境设置合适的 MTU 值
  6. 使用策略路由:在复杂网络环境中使用策略路由
  7. 记录日志:记录重要的配置更改和事件,便于故障排查
  8. 测试配置:在生产环境应用配置前,先在测试环境验证

注意事项#

  • ip 命令的配置在重启后会丢失,需要使用配置文件持久化
  • 修改网络接口配置可能导致网络连接中断
  • 在远程服务器上修改网络配置时要格外小心
  • 某些网络配置更改需要 root 权限
  • 不同 Linux 发行版的网络配置文件位置可能不同
  • 注意网络安全策略,避免违反组织规定
  • 在高可用环境中,注意网络配置的一致性
  • 对于关键业务,建议使用专业的网络管理工具