Skip to content

Instantly share code, notes, and snippets.

@arkag
Last active September 11, 2025 17:59
Show Gist options
  • Select an option

  • Save arkag/d96db27f464c5e2073ff2e6c8ad22249 to your computer and use it in GitHub Desktop.

Select an option

Save arkag/d96db27f464c5e2073ff2e6c8ad22249 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Function to show usage
usage() {
echo "Usage: $0 -i interface -a ip_address/subnet"
echo "Example: $0 -i enp22s0f0np0 -a 172.25.80.111/16"
exit 1
}
# Parse command line arguments
while getopts "i:a:h" opt; do
case $opt in
i) INTERFACE="$OPTARG" ;;
a) IP_ADDRESS="$OPTARG" ;;
h) usage ;;
*) usage ;;
esac
done
# Validate required arguments
if [ -z "$INTERFACE" ] || [ -z "$IP_ADDRESS" ]; then
echo "Error: Both interface and IP address are required"
usage
fi
CONFIG_FILE="/etc/netplan/01-netcfg.yaml"
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run this script as root or using sudo"
exit 1
fi
# Check if the interface exists
if ! ip link show "$INTERFACE" > /dev/null 2>&1; then
echo "Error: Interface $INTERFACE not found"
echo "Available interfaces:"
ip link show | grep -E "^[0-9]+:" | awk -F: '{print $2}' | tr -d ' '
exit 1
fi
# Validate IP address format (basic validation)
if ! echo "$IP_ADDRESS" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$'; then
echo "Error: Invalid IP address format. Use format: 192.168.1.100/24"
exit 1
fi
# Create backup of existing config
if [ -f "$CONFIG_FILE" ]; then
BACKUP_FILE="$CONFIG_FILE.backup.$(date +%Y%m%d%H%M%S)"
cp "$CONFIG_FILE" "$BACKUP_FILE"
echo "Backup created: $BACKUP_FILE"
fi
# Create or update Netplan configuration
cat > "$CONFIG_FILE" << EOF
network:
version: 2
renderer: networkd
ethernets:
$INTERFACE:
addresses:
- $IP_ADDRESS
EOF
# Set secure permissions for the netplan file
chmod 600 "$CONFIG_FILE"
chown root:root "$CONFIG_FILE"
echo "Netplan configuration created/updated: $CONFIG_FILE"
echo "Configuration applied:"
echo " Interface: $INTERFACE"
echo " IP Address: $IP_ADDRESS"
# Apply the configuration
echo ""
echo "Applying Netplan configuration..."
netplan apply
# Wait a moment for changes to take effect
sleep 2
# Verify the configuration
echo ""
echo "Verification:"
echo "Interface status:"
ip addr show "$INTERFACE" | grep -E "inet|state" || echo "No IP address assigned yet"
echo ""
echo "Current IP configuration for $INTERFACE:"
ip -4 addr show "$INTERFACE" | grep inet || echo "No IPv4 address found"
echo ""
echo "File permissions:"
ls -la "$CONFIG_FILE"
echo ""
echo "Script completed. Interface $INTERFACE configured with IP: $IP_ADDRESS"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment