Ubuntu 20.04之後的版本,似乎都是用cloud-ini設定IP,手動去改cloud-ini實在麻煩,沒有像以前直接改interfaces那麼方便。

下面提供DHCP、Static-IP快速修改的sciprt,目前測試Ubuntu 20.04, 22.04的cloud-ini都可以用。

dhcp.sh

#!/bin/bash

#NetworkInterface=$(ip r s 0/0 | grep -Po '(?<=(dev ))(\S+)')
#NetworkInterface=ens160

cd /sys/class/net || exit 1
echo "Select a Interface: "
select NetworkInterface in *; do break; done
echo "NetworkInterFace: $NetworkInterface"

read -p  "Change to DHCP [Y/N]: " DHCP

case $DHCP in
    y|Y) grep 'network: {config: disabled}' /etc/cloud/cloud.cfg.d/subiquity-disable-cloudinit-networking.cfg
        if [ "$?" = "0" ]; then
            cat <<EOF | tee /etc/netplan/00-installer-config.yaml > /dev/null
network:
  ethernets:
    $NetworkInterface:
      dhcp4: true
  version: 2
EOF
        fi
    ;;
    n|N) echo 'Exit'
    ;;
    *) echo 'Exit'
    ;;
esac

read -p  "Apply ? [Y/N]: " apply

case $apply in
    y|Y) /usr/sbin/netplan apply
    ;;
    n|N) echo 'Exit'
    ;;
    *) echo 'Exit'
    ;;
esac

static_ip.sh


#!/bin/bash


# NetworkInterface=$(ip r s 0/0 | grep -Po '(?<=(dev ))(\S+)')
#NetworkInterface=ens160

cd /sys/class/net || exit 1
echo "Select a Interface: "
select NetworkInterface in *; do break; done
echo "NetworkInterFace: $NetworkInterface"

read -p  "IP (Ex: 192.168.1.10): " NewIP
read -p  "GW IP (Ex: 192.168.1.254): " NewGW
read -n 3 -p  "CIDR Netmask (Ex: 24): " NewNM
read -p  "DNS (Ex: 168.95.1.1,8.8.8.8): " NewNS
echo '==============================='
echo "NetworkInterFace: "$NetworkInterface
echo "IP: "$NewIP
echo "GW: "$NewGW
echo "Netmask: "$NewNM
echo "DNS: "$NewNS

read -p  "information is correct[Y/N]: " correct

case $correct in
    y|Y) #echo yes
        grep 'network: {config: disabled}' /etc/cloud/cloud.cfg.d/subiquity-disable-cloudinit-networking.cfg
        if [ "$?" = "0" ]; then
            cat <<EOF | tee /etc/netplan/00-installer-config.yaml > /dev/null
network:
  ethernets:
    $NetworkInterface:
      addresses: [$NewIP/$NewNM]
      gateway4: $NewGW
      nameservers:
        addresses: [$NewNS]
  version: 2
EOF
        fi
        ;;
    n|N) echo 'Exit'
        ;;
    *) echo 'Exit'
        ;;
esac

read -p  "Apply ? [Y/N]: " apply

case $apply in
    y|Y) /usr/sbin/netplan apply
    ;;
    n|N) echo 'Exit'
    ;;
    *) echo 'Exit'
    ;;
esac

References