Bootstrap

用脚本一键修改IP地址和主机名

#!/bin/bash

# 脚本使用说明
usage() {
    echo "Usage: $0 <interface> <new_ip> <netmask> <gateway> <new_hostname>"
    echo "Example: $0 eth0 192.168.1.100 255.255.255.0 192.168.1.1 myhostname"
    exit 1
}

# 检查参数个数是否正确
if [ "$#" -ne 5 ]; then
    usage
fi

interface="$1"
new_ip="$2"
netmask="$3"
gateway="$4"
new_hostname="$5"

# 检查网卡是否存在
if ! ip addr show dev "$interface" > /dev/null 2>&1; then
    echo "Error: Network interface '$interface' not found."
    exit 1
fi

# 设定新的 IP 地址、子网掩码和网关
sudo ip addr flush dev "$interface"
sudo ip addr add "$new_ip"/"$netmask" dev "$interface"
sudo ip route add default via "$gateway" dev "$interface"

# 修改主机名
sudo hostnamectl set-hostname "$new_hostname"

echo "Network configuration updated successfully:"
echo "Interface: $interface"
echo "New IP Address: $new_ip"
echo "Subnet Mask: $netmask"
echo "Gateway: $gateway"
echo "New Hostname: $new_hostname"
  • 执行脚本时,传递五个参数:网卡名称、新的 IP 地址、子网掩码、网关地址和新的主机名。
;