NetworkManager配置IP和HostName

设置IP与Hostname

#!/bin/bash
# set-net.sh - Modify network settings partially using NetworkManager
# Example:
# set-net.sh -i eth0 --ip 192.168.1.10/24
# set-net.sh -i eth0 --gw 192.168.1.1
# set-net.sh -i eth0 --dns 8.8.8.8
# set-net.sh --hostname server01

set -e

usage() {
echo "Usage:"
echo "  $0 -i <iface> [--ip IP/PREFIX] [--gw GATEWAY] [--dns DNS]"
echo "  $0 --hostname HOSTNAME"
exit 1
}

IFACE=""
IPADDR=""
GATEWAY=""
DNS=""
NEW_HOSTNAME=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        -i|--iface)
            IFACE="$2"
            shift 2
            ;;
        --ip)
            IPADDR="$2"
            shift 2
            ;;
        --gw)
            GATEWAY="$2"
            shift 2
            ;;
        --dns)
            DNS="$2"
            shift 2
            ;;
        --hostname)
            NEW_HOSTNAME="$2"
            shift 2
            ;;
        *)
            usage
            ;;
    esac
done

if [[ -z "$IFACE" && -z "$NEW_HOSTNAME" ]]; then
    usage
fi

# ------------------------
# Network Configuration
# ------------------------
if [[ -n "$IFACE" ]]; then
    echo "=== Configuring interface $IFACE ==="

    CON_NAME=$(nmcli -t -f NAME,DEVICE con show | grep ":$IFACE" | cut -d: -f1)

    if [[ -z "$CON_NAME" ]]; then
        echo "No existing connection found, creating..."
        CON_NAME="${IFACE}-manual"
        nmcli con add type ethernet ifname "$IFACE" con-name "$CON_NAME"
    fi

    echo "Using connection: $CON_NAME"

    [[ -n "$IPADDR" ]] && nmcli con mod "$CON_NAME" ipv4.addresses "$IPADDR" ipv4.method manual
    [[ -n "$GATEWAY" ]] && nmcli con mod "$CON_NAME" ipv4.gateway "$GATEWAY"
    [[ -n "$DNS" ]] && nmcli con mod "$CON_NAME" ipv4.dns "$DNS"

    nmcli con mod "$CON_NAME" connection.autoconnect yes

    nmcli con down "$CON_NAME" || true
    nmcli con up "$CON_NAME"

    echo "Network updated."
fi

# ------------------------
# Hostname Configuration
# ------------------------
if [[ -n "$NEW_HOSTNAME" ]]; then
    echo "=== Setting hostname to $NEW_HOSTNAME ==="

    hostnamectl set-hostname "$NEW_HOSTNAME"

    if grep -q "127.0.1.1" /etc/hosts; then
        sed -i "s/^127\.0\.1\.1.*/127.0.1.1\t$NEW_HOSTNAME/" /etc/hosts
    else
        echo -e "127.0.1.1\t$NEW_HOSTNAME" >> /etc/hosts
    fi

    echo "Hostname updated."
fi

echo "✅ Done"

使用

root@debian-m1:~# bash setip.sh
Usage:
  setip.sh -i <iface> [--ip IP/PREFIX] [--gw GATEWAY] [--dns DNS]
  setip.sh --hostname HOSTNAME

root@debian-m1:~# bash setip.sh --hostname debian-m
=== Setting hostname to debian-m ===
Hostname updated.
✅ Done
posted @ 2026-03-07 08:13  菜阿  阅读(17)  评论(0)    收藏  举报