Created
December 19, 2025 10:26
-
-
Save techfish-11/57b805fee8ed928d22f8d04c357afaee to your computer and use it in GitHub Desktop.
DHCPでもらっていたIPをそのまま固定するシェルスクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -e | |
| echo "[*] Detecting interface (IPv4 default)..." | |
| IFACE=$(ip -4 route show default | awk '{print $5}' | head -n1) | |
| echo "[*] Detecting current IPv4 (non-secondary)..." | |
| ADDR=$(ip -4 addr show "$IFACE" \ | |
| | awk '/inet / && $0 !~ /secondary/ {print $2}' \ | |
| | head -n1) | |
| echo "[*] Detecting gateway..." | |
| GATEWAY=$(ip -4 route show default | awk '{print $3}' | head -n1) | |
| echo "[*] Detecting DNS (IPv4 only)..." | |
| DNS=$(resolvectl dns "$IFACE" 2>/dev/null \ | |
| | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' \ | |
| | head -n1) | |
| NETPLAN_FILE="/etc/netplan/01-static-${IFACE}.yaml" | |
| echo "[*] Backing up other netplan configs..." | |
| for f in /etc/netplan/*.yaml; do | |
| if [[ "$f" != "$NETPLAN_FILE" ]]; then | |
| mv "$f" "$f.bak" | |
| fi | |
| done | |
| echo "[*] Writing static netplan config..." | |
| cat <<EOF | tee "$NETPLAN_FILE" >/dev/null | |
| network: | |
| version: 2 | |
| renderer: networkd | |
| ethernets: | |
| $IFACE: | |
| dhcp4: no | |
| dhcp6: no | |
| accept-ra: no | |
| addresses: | |
| - $ADDR | |
| routes: | |
| - to: default | |
| via: $GATEWAY | |
| nameservers: | |
| addresses: | |
| - $DNS | |
| EOF | |
| chmod 600 "$NETPLAN_FILE" | |
| echo "[*] Disabling cloud-init network config..." | |
| mkdir -p /etc/cloud/cloud.cfg.d | |
| cat <<EOF | tee /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg >/dev/null | |
| network: {config: disabled} | |
| EOF | |
| echo "[*] Cleaning cloud-init..." | |
| cloud-init clean || true | |
| echo "[*] Removing DHCP leases..." | |
| rm -f /run/systemd/netif/leases/* | |
| rm -f /var/lib/dhcp/dhclient*.lease* || true | |
| echo "[*] Restarting network stack..." | |
| systemctl restart systemd-networkd | |
| echo "[*] Applying netplan..." | |
| netplan apply | |
| echo | |
| echo "[✓] Finished. Verify with:" | |
| echo " ip addr show $IFACE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment