NOVACyclist

Ubuntu Clone Hostname Reset

Jul 18th, 2025 (edited)
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.60 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Exit on error
  4. set -e
  5.  
  6. # Check if script is run as root
  7. if [ "$EUID" -ne 0 ]; then
  8.   echo "Please run as root"
  9.   exit 1
  10. fi
  11.  
  12. # Check if FQDN is provided
  13. if [ -z "$1" ]; then
  14.   echo "Please provide an FQDN"
  15.   exit 1
  16. fi
  17.  
  18. # Extract hostname and domain from FQDN
  19. FQDN="$1"
  20. NEW_HOSTNAME=$(echo "$FQDN" | cut -d'.' -f1)
  21. DOMAIN=$(echo "$FQDN" | cut -d'.' -f2-)
  22.  
  23. # Set new hostname
  24. hostnamectl set-hostname "$NEW_HOSTNAME"
  25. echo "$NEW_HOSTNAME" > /etc/hostname
  26.  
  27. # Update hosts file
  28. sed -i '/^127.0.1.1/d' /etc/hosts
  29. echo "127.0.1.1 $FQDN $NEW_HOSTNAME" >> /etc/hosts
  30.  
  31. # Reset machine-id
  32. truncate -s 0 /etc/machine-id
  33. rm -f /var/lib/dbus/machine-id
  34. systemd-machine-id-setup
  35.  
  36. # Clear SSH keys
  37. rm -f /etc/ssh/ssh_host_*
  38. if dpkg -l | grep -q openssh-server; then
  39.   dpkg-reconfigure openssh-server
  40.   systemctl restart ssh
  41. else
  42.   echo "Warning: openssh-server not installed, skipping SSH key regeneration"
  43. fi
  44.  
  45. # Reset network configuration
  46. # Detect primary network interface
  47. IFACE=$(ip link | awk -F: '$0 !~ "lo|vir|docker|br-|^[^0-9]"{print $2;getline}' | head -n 1 | xargs)
  48. if [ -z "$IFACE" ]; then
  49.   echo "Error: No network interface found"
  50.   exit 1
  51. fi
  52. # Delete existing connections
  53. nmcli -t -f UUID con show | while read -r uuid; do
  54.   nmcli con delete "$uuid" 2>/dev/null || true
  55. done
  56. # Add new ethernet connection
  57. nmcli con add type ethernet ifname "$IFACE" con-name "eth0" autoconnect yes
  58.  
  59. # Clear logs
  60. find /var/log -type f -name "*.log" -exec truncate -s 0 {} \;
  61.  
  62. # Remove temporary files
  63. rm -rf /tmp/* /var/tmp/*
  64.  
  65. echo "VM template reset complete. New FQDN: $FQDN"
Advertisement
Add Comment
Please, Sign In to add comment