init.sh
                        
                             · 11 KiB · Bash
                        
                    
                    
                      
                        Surowy
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            #!/usr/bin/env bash
#===============================================================================
# Concise server preparation script with error confirmation (idempotent)
#===============================================================================
set -euo pipefail
export LC_ALL=C
export LANG=en_US.UTF-8
export DEBIAN_FRONTEND=noninteractive
#-----------------------------------
# Colors & Prompts
#-----------------------------------
Green="\033[32m"; Red="\033[31m"; Yellow="\033[33m"; Blue="\033[36m"; Font="\033[0m"
OK="${Green}[  OK  ]${Font}"; ERROR="${Red}[FAILED]${Font}"; WARN="${Yellow}[ WARN ]${Font}"
print_ok(){   echo -e "${OK} $1"; }
print_error(){ echo -e "${ERROR} $1"; }
print_warn(){ echo -e "${WARN} $1"; }
#-----------------------------------
# Error handling & confirmation
#-----------------------------------
on_error(){ print_error "Error at line $1."; areYouSure; }
trap 'on_error $LINENO' ERR
areYouSure(){
  print_warn "Continue despite errors? [y/N]"
  read -r ans
  case $ans in [yY]*) print_ok "Continuing...";; *) print_error "Aborted."; exit 1;; esac
}
#-----------------------------------
# Helpers
#-----------------------------------
run_local(){   print_ok "Local: $*"; "$@"; }
run_remote(){  sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$SERVER" "$*"; }
wait_ssh(){
  print_ok "Waiting for SSH on $SERVER... (Running ssh $REMOTE_USER@$SERVER)"
  until sshpass -p "$REMOTE_PASS" ssh -q \
      -o StrictHostKeyChecking=no \
      -o ConnectTimeout=5 \
      "$REMOTE_USER@$SERVER" exit; do
    print_warn "SSH not ready, retrying in 5s..."
    sleep 5
  done
  print_ok "SSH available."
}
usage(){ echo "Usage: $0 <orig_user> <orig_pass> <server> <new_hostname> <new_user>"; exit 1; }
#-----------------------------------
# Main
#-----------------------------------
[ $# -ne 5 ] && usage
USER="$1"; PASS="$2"; SERVER="$3"; HOSTNAME="$4"; NEWUSER="$5"
REMOTE_USER="$USER"; REMOTE_PASS="$PASS"
# 1) Install sshpass locally
run_local sudo apt-get update -y
run_local sudo apt-get install -y sshpass
# 2) Clear known_hosts, wait for SSH
run_local ssh-keygen -R "$SERVER" -f ~/.ssh/known_hosts
wait_ssh
# 3) Hostname & reboot (only if changed)
CURRENT_HOST=$(run_remote "hostname")
if [[ "$CURRENT_HOST" != "$HOSTNAME" ]]; then
  print_ok "Setting hostname to $HOSTNAME"
  run_remote "sudo hostnamectl set-hostname $HOSTNAME"
  run_remote "sudo reboot" || true
  print_ok "Server rebooting..."
  sleep 5
  wait_ssh
else
  print_ok "Hostname already '$HOSTNAME', skipping"
fi
# 4) Create or verify new user
if run_remote "id -u $NEWUSER" &>/dev/null; then
  print_ok "User $NEWUSER exists"
else
  print_ok "Creating user $NEWUSER"
  run_remote "sudo adduser --disabled-password --gecos '' $NEWUSER"
fi
# 5) Grant sudo & set up passwordless
print_ok "Granting sudo to $NEWUSER"
run_remote "sudo usermod -aG sudo $NEWUSER"
print_ok "Setting passwordless sudo for $NEWUSER"
run_remote "echo '$NEWUSER ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/$NEWUSER"
# 6) Generate & persist random password (once)
if run_remote "[ -f /etc/$NEWUSER.pass ]" &>/dev/null; then
  # In this case, the password is already set
  print_ok "Don't have to change password. Reusing existing password for $NEWUSER"
  PASS_NEW=$(run_remote "sudo cat /etc/$NEWUSER.pass")
else
  PASS_NEW=$(uuidgen)
  print_ok "Setting password for $NEWUSER"
  run_remote "echo '$NEWUSER:$PASS_NEW' | sudo chpasswd"
  run_remote "echo '$PASS_NEW' | sudo tee /etc/$NEWUSER.pass > /dev/null"
  run_remote "sudo chmod 600 /etc/$NEWUSER.pass"
  run_remote "sudo chown root:root /etc/$NEWUSER.pass"
  print_ok "New password generated for $NEWUSER and persisted at /etc/$NEWUSER.pass. Please back it up! It can still be used to log in via serial console or rescue mode!"
fi
local_pass_file="./password_${NEWUSER}_at_${SERVER}.txt"
rm -f "$local_pass_file" 2>/dev/null || true
sshpass -p "$REMOTE_PASS" ssh -q -o StrictHostKeyChecking=no \
  "$REMOTE_USER@$SERVER" "sudo cat /etc/$NEWUSER.pass" \
  > "$local_pass_file"
sudo chown "$USER:$USER" "$local_pass_file"
sudo chmod 600 "$local_pass_file"
print_ok "Password for $NEWUSER saved locally at $local_pass_file [DO NOT SHARE THIS FILE! IT CAN BE USED TO LOG IN VIA SERIAL CONSOLE OR RESCUE MODE!]"
# 7) Copy SSH key (only if absent)
[ ! -f ~/.ssh/id_rsa.pub ] && run_local ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
PUBKEY=$(<~/.ssh/id_rsa.pub)
print_ok "Ensuring SSH key in authorized_keys"
run_remote "mkdir -p /home/$NEWUSER/.ssh && \
  sudo bash -c 'grep -qxF \"$PUBKEY\" /home/$NEWUSER/.ssh/authorized_keys 2>/dev/null || \
  echo \"$PUBKEY\" >> /home/$NEWUSER/.ssh/authorized_keys' && \
  sudo chown -R $NEWUSER:$NEWUSER /home/$NEWUSER/.ssh && \
  sudo chmod 700 /home/$NEWUSER/.ssh && \
  sudo chmod 600 /home/$NEWUSER/.ssh/authorized_keys"
# Switch to new user for subsequent operations
print_ok "Switching to new user $NEWUSER"
REMOTE_USER="$NEWUSER"; REMOTE_PASS="$PASS_NEW"
wait_ssh
# 8) Harden SSH
print_ok "Hardening SSH settings"
run_remote "sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/; \
  s/PasswordAuthentication yes/PasswordAuthentication no/; \
  s/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config && \
  sudo systemctl restart sshd || sudo systemctl restart ssh"
# 9) Remove other non-system users
print_ok "Removing other users"
others=$(run_remote "awk -F: -v skip='$NEWUSER' '\$3>=1000 && \$1!=skip {print \$1}' /etc/passwd")
for u in $others; do
  print_warn "Deleting user $u"
  run_remote "sudo pkill -u $u || true; sudo deluser --remove-home $u"
done
# 10) Reset machine-id
print_ok "Resetting machine-id"
run_remote "sudo rm -f /etc/machine-id /var/lib/dbus/machine-id && \
  sudo systemd-machine-id-setup && \
  sudo cp /etc/machine-id /var/lib/dbus/machine-id"
# 11) Enable UFW & OpenSSH
print_ok "Enabling UFW firewall"
run_remote "sudo apt-get install -y ufw && sudo ufw allow OpenSSH && echo y | sudo ufw enable"
# 12) Install & configure Fail2Ban
print_ok "Installing Fail2Ban"
run_remote "sudo apt-get update && sudo apt-get install -y fail2ban"
print_ok "Configuring Fail2Ban"
run_remote <<'EOF'
sudo tee /etc/fail2ban/jail.local > /dev/null <<EOJ
[sshd]
enabled   = true
port      = ssh
filter    = sshd
backend  = systemd
logpath  = journal
maxretry  = 3
findtime  = 600
bantime   = 3600
EOJ
sudo systemctl restart fail2ban
EOF
print_ok "Fail2Ban setup complete"
# 13) Enable BBR (only once)
print_ok "Enabling BBR congestion control"
run_remote <<'EOF'
grep -q 'net.ipv4.tcp_congestion_control = bbr' /etc/sysctl.d/99-bbr.conf 2>/dev/null || {
  sudo tee /etc/sysctl.d/99-bbr.conf > /dev/null <<SYSCTL
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
SYSCTL
  sudo sysctl --system
}
EOF
# 14) Select best mirror & update
print_ok "Selecting best mirror & updating"
run_remote "curl -s https://gist.aiursoft.cn/anduin/879917820a6c4b268fc12c21f1b3fe7a/raw/HEAD/mirror.sh | bash"
run_remote "sudo apt-get update"
# 15) Install or upgrade latest HWE kernel if needed
print_ok "Checking HWE kernel package on remote"
run_remote <<'EOF'
set -euo pipefail
# Try to find the HWE package
HWE_PKG=$(apt search linux-generic-hwe- 2>/dev/null | grep -o 'linux-generic-hwe-[^/ ]*' | head -1)
if [ -z "$HWE_PKG" ]; then
  echo "[  OK  ] No HWE kernel package found for this release, skipping"
else
  inst=$(apt-cache policy "$HWE_PKG" | awk '/Installed:/ {print $2}')
  cand=$(apt-cache policy "$HWE_PKG" | awk '/Candidate:/ {print $2}')
  if dpkg -s "$HWE_PKG" &>/dev/null; then
    if [ "$inst" != "$cand" ] && [ "$cand" != "(none)" ]; then
      echo "[  OK  ] Upgrading $HWE_PKG from $inst to $cand"
      sudo apt-get update
      sudo apt-get install -y "$HWE_PKG"
      echo reboot_required > /tmp/.reboot_flag
    else
      echo "[  OK  ] $HWE_PKG is already at latest version ($inst), skipping"
    fi
  else
    if [ "$cand" != "(none)" ]; then
      echo "[  OK  ] Installing $HWE_PKG ($cand)"
      sudo apt-get update
      sudo apt-get install -y "$HWE_PKG"
      echo reboot_required > /tmp/.reboot_flag
    else
      echo "[  OK  ] $HWE_PKG has no installation candidate, skipping"
    fi
  fi
fi
EOF
# 16) Conditionally reboot & wait
if run_remote 'test -f /tmp/.reboot_flag'; then
  print_ok "Rebooting server to apply new kernel"
  run_remote "rm -f /tmp/.reboot_flag"
  run_remote "sudo reboot" || true
  sleep 5
  wait_ssh
else
  print_ok "No new kernel installed, skipping reboot"
fi
# 17) Final updates & cleanup
print_ok "Installing upgrades & cleanup"
run_remote "sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get autoremove -y"
# 18) Performance tuning
print_ok "Tuning CPU performance & timezone"
run_remote "sudo apt-get install -y linux-tools-$(uname -r) cpupower && \
  sudo cpupower frequency-set -g performance || true && \
  sudo timedatectl set-timezone GMT"
# 19) Remove snap
print_ok "Removing snapd"
run_remote <<'EOF'
# 1) 如果 snapd.service 存在,就 disable 一下;否则跳过
if systemctl list-unit-files | grep -q '^snapd\.service'; then
  sudo systemctl disable --now snapd || true
else
  echo "[  OK  ] snapd.service not found, skipping disable"
fi
# 2) 如果 dpkg 里检测到 snapd 包,就 purge 并清理数据目录
if dpkg -l snapd &>/dev/null; then
  sudo apt-get purge -y snapd
  sudo rm -rf /snap /var/lib/snapd /var/cache/snapd
else
  echo "[  OK  ] snapd package not installed, skipping purge"
fi
# 3) 在所有机器都写上 no-snap 的 pin
sudo tee /etc/apt/preferences.d/no-snap.pref > /dev/null <<EOP
Package: snapd
Pin: release a=*
Pin-Priority: -10
EOP
EOF
# 20) Final cleanup & benchmark
print_ok "Final autoremove & benchmark"
run_remote "sudo apt-get autoremove -y --purge && \
  sudo apt-get install -y sysbench && sysbench cpu --threads=$(nproc) run && \
  sudo apt-get autoremove -y sysbench --purge"
print_ok "Setup complete. Connect via: ssh $NEWUSER@$SERVER"
# After this script, server will:
# * Only allow SSH key login
# * Root login disabled, password authentication disabled
# * Have a new hostname set
# * Have a new user with sudo privileges and can log in via SSH
# * Have a random password stored securely at /etc/<new_user>.pass
# * Have SSH key copied to authorized_keys so you can log in without a password
# * Be hardened with UFW, Fail2Ban and allowed SSH connections(only)
# * Have BBR enabled for better network performance
# * Have the latest HWE kernel installed
# * Have the best mirror selected for package updates
# * Have snap removed
# * Have CPU performance tuned to 'performance' mode
# * Have timezone set to GMT
# * Have all unnecessary users removed (Check /etc/passwd for remaining users)
# * Have all unnecessary packages removed
# * Have the latest updates installed
# * Have sysbench installed for performance testing
# * Have a final benchmark run to verify CPU performance
# * Have a final cleanup of unnecessary packages
                | 1 | #!/usr/bin/env bash | 
| 2 | #=============================================================================== | 
| 3 | # Concise server preparation script with error confirmation (idempotent) | 
| 4 | #=============================================================================== | 
| 5 | |
| 6 | set -euo pipefail | 
| 7 | export LC_ALL=C | 
| 8 | export LANG=en_US.UTF-8 | 
| 9 | export DEBIAN_FRONTEND=noninteractive | 
| 10 | |
| 11 | #----------------------------------- | 
| 12 | # Colors & Prompts | 
| 13 | #----------------------------------- | 
| 14 | Green="\033[32m"; Red="\033[31m"; Yellow="\033[33m"; Blue="\033[36m"; Font="\033[0m" | 
| 15 | OK="${Green}[ OK ]${Font}"; ERROR="${Red}[FAILED]${Font}"; WARN="${Yellow}[ WARN ]${Font}" | 
| 16 | |
| 17 | print_ok(){ echo -e "${OK} $1"; } | 
| 18 | print_error(){ echo -e "${ERROR} $1"; } | 
| 19 | print_warn(){ echo -e "${WARN} $1"; } | 
| 20 | |
| 21 | #----------------------------------- | 
| 22 | # Error handling & confirmation | 
| 23 | #----------------------------------- | 
| 24 | on_error(){ print_error "Error at line $1."; areYouSure; } | 
| 25 | trap 'on_error $LINENO' ERR | 
| 26 | |
| 27 | areYouSure(){ | 
| 28 | print_warn "Continue despite errors? [y/N]" | 
| 29 | read -r ans | 
| 30 | case $ans in [yY]*) print_ok "Continuing...";; *) print_error "Aborted."; exit 1;; esac | 
| 31 | } | 
| 32 | |
| 33 | #----------------------------------- | 
| 34 | # Helpers | 
| 35 | #----------------------------------- | 
| 36 | run_local(){ print_ok "Local: $*"; "$@"; } | 
| 37 | run_remote(){ sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$SERVER" "$*"; } | 
| 38 | wait_ssh(){ | 
| 39 | print_ok "Waiting for SSH on $SERVER... (Running ssh $REMOTE_USER@$SERVER)" | 
| 40 | until sshpass -p "$REMOTE_PASS" ssh -q \ | 
| 41 | -o StrictHostKeyChecking=no \ | 
| 42 | -o ConnectTimeout=5 \ | 
| 43 | "$REMOTE_USER@$SERVER" exit; do | 
| 44 | print_warn "SSH not ready, retrying in 5s..." | 
| 45 | sleep 5 | 
| 46 | done | 
| 47 | print_ok "SSH available." | 
| 48 | } | 
| 49 | |
| 50 | usage(){ echo "Usage: $0 <orig_user> <orig_pass> <server> <new_hostname> <new_user>"; exit 1; } | 
| 51 | |
| 52 | #----------------------------------- | 
| 53 | # Main | 
| 54 | #----------------------------------- | 
| 55 | [ $# -ne 5 ] && usage | 
| 56 | USER="$1"; PASS="$2"; SERVER="$3"; HOSTNAME="$4"; NEWUSER="$5" | 
| 57 | REMOTE_USER="$USER"; REMOTE_PASS="$PASS" | 
| 58 | |
| 59 | # 1) Install sshpass locally | 
| 60 | run_local sudo apt-get update -y | 
| 61 | run_local sudo apt-get install -y sshpass | 
| 62 | |
| 63 | # 2) Clear known_hosts, wait for SSH | 
| 64 | run_local ssh-keygen -R "$SERVER" -f ~/.ssh/known_hosts | 
| 65 | wait_ssh | 
| 66 | |
| 67 | # 3) Hostname & reboot (only if changed) | 
| 68 | CURRENT_HOST=$(run_remote "hostname") | 
| 69 | if [[ "$CURRENT_HOST" != "$HOSTNAME" ]]; then | 
| 70 | print_ok "Setting hostname to $HOSTNAME" | 
| 71 | run_remote "sudo hostnamectl set-hostname $HOSTNAME" | 
| 72 | run_remote "sudo reboot" || true | 
| 73 | print_ok "Server rebooting..." | 
| 74 | sleep 5 | 
| 75 | wait_ssh | 
| 76 | else | 
| 77 | print_ok "Hostname already '$HOSTNAME', skipping" | 
| 78 | fi | 
| 79 | |
| 80 | # 4) Create or verify new user | 
| 81 | if run_remote "id -u $NEWUSER" &>/dev/null; then | 
| 82 | print_ok "User $NEWUSER exists" | 
| 83 | else | 
| 84 | print_ok "Creating user $NEWUSER" | 
| 85 | run_remote "sudo adduser --disabled-password --gecos '' $NEWUSER" | 
| 86 | fi | 
| 87 | |
| 88 | # 5) Grant sudo & set up passwordless | 
| 89 | print_ok "Granting sudo to $NEWUSER" | 
| 90 | run_remote "sudo usermod -aG sudo $NEWUSER" | 
| 91 | print_ok "Setting passwordless sudo for $NEWUSER" | 
| 92 | run_remote "echo '$NEWUSER ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/$NEWUSER" | 
| 93 | |
| 94 | # 6) Generate & persist random password (once) | 
| 95 | if run_remote "[ -f /etc/$NEWUSER.pass ]" &>/dev/null; then | 
| 96 | # In this case, the password is already set | 
| 97 | print_ok "Don't have to change password. Reusing existing password for $NEWUSER" | 
| 98 | PASS_NEW=$(run_remote "sudo cat /etc/$NEWUSER.pass") | 
| 99 | else | 
| 100 | PASS_NEW=$(uuidgen) | 
| 101 | print_ok "Setting password for $NEWUSER" | 
| 102 | run_remote "echo '$NEWUSER:$PASS_NEW' | sudo chpasswd" | 
| 103 | run_remote "echo '$PASS_NEW' | sudo tee /etc/$NEWUSER.pass > /dev/null" | 
| 104 | run_remote "sudo chmod 600 /etc/$NEWUSER.pass" | 
| 105 | run_remote "sudo chown root:root /etc/$NEWUSER.pass" | 
| 106 | print_ok "New password generated for $NEWUSER and persisted at /etc/$NEWUSER.pass. Please back it up! It can still be used to log in via serial console or rescue mode!" | 
| 107 | fi | 
| 108 | |
| 109 | local_pass_file="./password_${NEWUSER}_at_${SERVER}.txt" | 
| 110 | rm -f "$local_pass_file" 2>/dev/null || true | 
| 111 | sshpass -p "$REMOTE_PASS" ssh -q -o StrictHostKeyChecking=no \ | 
| 112 | "$REMOTE_USER@$SERVER" "sudo cat /etc/$NEWUSER.pass" \ | 
| 113 | > "$local_pass_file" | 
| 114 | sudo chown "$USER:$USER" "$local_pass_file" | 
| 115 | sudo chmod 600 "$local_pass_file" | 
| 116 | print_ok "Password for $NEWUSER saved locally at $local_pass_file [DO NOT SHARE THIS FILE! IT CAN BE USED TO LOG IN VIA SERIAL CONSOLE OR RESCUE MODE!]" | 
| 117 | |
| 118 | # 7) Copy SSH key (only if absent) | 
| 119 | [ ! -f ~/.ssh/id_rsa.pub ] && run_local ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa | 
| 120 | PUBKEY=$(<~/.ssh/id_rsa.pub) | 
| 121 | print_ok "Ensuring SSH key in authorized_keys" | 
| 122 | run_remote "mkdir -p /home/$NEWUSER/.ssh && \ | 
| 123 | sudo bash -c 'grep -qxF \"$PUBKEY\" /home/$NEWUSER/.ssh/authorized_keys 2>/dev/null || \ | 
| 124 | echo \"$PUBKEY\" >> /home/$NEWUSER/.ssh/authorized_keys' && \ | 
| 125 | sudo chown -R $NEWUSER:$NEWUSER /home/$NEWUSER/.ssh && \ | 
| 126 | sudo chmod 700 /home/$NEWUSER/.ssh && \ | 
| 127 | sudo chmod 600 /home/$NEWUSER/.ssh/authorized_keys" | 
| 128 | |
| 129 | # Switch to new user for subsequent operations | 
| 130 | print_ok "Switching to new user $NEWUSER" | 
| 131 | REMOTE_USER="$NEWUSER"; REMOTE_PASS="$PASS_NEW" | 
| 132 | wait_ssh | 
| 133 | |
| 134 | # 8) Harden SSH | 
| 135 | print_ok "Hardening SSH settings" | 
| 136 | run_remote "sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/; \ | 
| 137 | s/PasswordAuthentication yes/PasswordAuthentication no/; \ | 
| 138 | s/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config && \ | 
| 139 | sudo systemctl restart sshd || sudo systemctl restart ssh" | 
| 140 | |
| 141 | # 9) Remove other non-system users | 
| 142 | print_ok "Removing other users" | 
| 143 | others=$(run_remote "awk -F: -v skip='$NEWUSER' '\$3>=1000 && \$1!=skip {print \$1}' /etc/passwd") | 
| 144 | for u in $others; do | 
| 145 | print_warn "Deleting user $u" | 
| 146 | run_remote "sudo pkill -u $u || true; sudo deluser --remove-home $u" | 
| 147 | done | 
| 148 | |
| 149 | # 10) Reset machine-id | 
| 150 | print_ok "Resetting machine-id" | 
| 151 | run_remote "sudo rm -f /etc/machine-id /var/lib/dbus/machine-id && \ | 
| 152 | sudo systemd-machine-id-setup && \ | 
| 153 | sudo cp /etc/machine-id /var/lib/dbus/machine-id" | 
| 154 | |
| 155 | # 11) Enable UFW & OpenSSH | 
| 156 | print_ok "Enabling UFW firewall" | 
| 157 | run_remote "sudo apt-get install -y ufw && sudo ufw allow OpenSSH && echo y | sudo ufw enable" | 
| 158 | |
| 159 | # 12) Install & configure Fail2Ban | 
| 160 | print_ok "Installing Fail2Ban" | 
| 161 | run_remote "sudo apt-get update && sudo apt-get install -y fail2ban" | 
| 162 | print_ok "Configuring Fail2Ban" | 
| 163 | run_remote <<'EOF' | 
| 164 | sudo tee /etc/fail2ban/jail.local > /dev/null <<EOJ | 
| 165 | [sshd] | 
| 166 | enabled = true | 
| 167 | port = ssh | 
| 168 | filter = sshd | 
| 169 | backend = systemd | 
| 170 | logpath = journal | 
| 171 | maxretry = 3 | 
| 172 | findtime = 600 | 
| 173 | bantime = 3600 | 
| 174 | EOJ | 
| 175 | sudo systemctl restart fail2ban | 
| 176 | EOF | 
| 177 | print_ok "Fail2Ban setup complete" | 
| 178 | |
| 179 | # 13) Enable BBR (only once) | 
| 180 | print_ok "Enabling BBR congestion control" | 
| 181 | run_remote <<'EOF' | 
| 182 | grep -q 'net.ipv4.tcp_congestion_control = bbr' /etc/sysctl.d/99-bbr.conf 2>/dev/null || { | 
| 183 | sudo tee /etc/sysctl.d/99-bbr.conf > /dev/null <<SYSCTL | 
| 184 | net.core.default_qdisc = fq | 
| 185 | net.ipv4.tcp_congestion_control = bbr | 
| 186 | SYSCTL | 
| 187 | sudo sysctl --system | 
| 188 | } | 
| 189 | EOF | 
| 190 | |
| 191 | # 14) Select best mirror & update | 
| 192 | print_ok "Selecting best mirror & updating" | 
| 193 | run_remote "curl -s https://gist.aiursoft.cn/anduin/879917820a6c4b268fc12c21f1b3fe7a/raw/HEAD/mirror.sh | bash" | 
| 194 | run_remote "sudo apt-get update" | 
| 195 | |
| 196 | # 15) Install or upgrade latest HWE kernel if needed | 
| 197 | print_ok "Checking HWE kernel package on remote" | 
| 198 | run_remote <<'EOF' | 
| 199 | set -euo pipefail | 
| 200 | |
| 201 | # Try to find the HWE package | 
| 202 | HWE_PKG=$(apt search linux-generic-hwe- 2>/dev/null | grep -o 'linux-generic-hwe-[^/ ]*' | head -1) | 
| 203 | |
| 204 | if [ -z "$HWE_PKG" ]; then | 
| 205 | echo "[ OK ] No HWE kernel package found for this release, skipping" | 
| 206 | else | 
| 207 | inst=$(apt-cache policy "$HWE_PKG" | awk '/Installed:/ {print $2}') | 
| 208 | cand=$(apt-cache policy "$HWE_PKG" | awk '/Candidate:/ {print $2}') | 
| 209 | |
| 210 | if dpkg -s "$HWE_PKG" &>/dev/null; then | 
| 211 | if [ "$inst" != "$cand" ] && [ "$cand" != "(none)" ]; then | 
| 212 | echo "[ OK ] Upgrading $HWE_PKG from $inst to $cand" | 
| 213 | sudo apt-get update | 
| 214 | sudo apt-get install -y "$HWE_PKG" | 
| 215 | echo reboot_required > /tmp/.reboot_flag | 
| 216 | else | 
| 217 | echo "[ OK ] $HWE_PKG is already at latest version ($inst), skipping" | 
| 218 | fi | 
| 219 | else | 
| 220 | if [ "$cand" != "(none)" ]; then | 
| 221 | echo "[ OK ] Installing $HWE_PKG ($cand)" | 
| 222 | sudo apt-get update | 
| 223 | sudo apt-get install -y "$HWE_PKG" | 
| 224 | echo reboot_required > /tmp/.reboot_flag | 
| 225 | else | 
| 226 | echo "[ OK ] $HWE_PKG has no installation candidate, skipping" | 
| 227 | fi | 
| 228 | fi | 
| 229 | fi | 
| 230 | EOF | 
| 231 | |
| 232 | # 16) Conditionally reboot & wait | 
| 233 | if run_remote 'test -f /tmp/.reboot_flag'; then | 
| 234 | print_ok "Rebooting server to apply new kernel" | 
| 235 | run_remote "rm -f /tmp/.reboot_flag" | 
| 236 | run_remote "sudo reboot" || true | 
| 237 | sleep 5 | 
| 238 | wait_ssh | 
| 239 | else | 
| 240 | print_ok "No new kernel installed, skipping reboot" | 
| 241 | fi | 
| 242 | |
| 243 | # 17) Final updates & cleanup | 
| 244 | print_ok "Installing upgrades & cleanup" | 
| 245 | run_remote "sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get autoremove -y" | 
| 246 | |
| 247 | # 18) Performance tuning | 
| 248 | print_ok "Tuning CPU performance & timezone" | 
| 249 | run_remote "sudo apt-get install -y linux-tools-$(uname -r) cpupower && \ | 
| 250 | sudo cpupower frequency-set -g performance || true && \ | 
| 251 | sudo timedatectl set-timezone GMT" | 
| 252 | |
| 253 | # 19) Remove snap | 
| 254 | print_ok "Removing snapd" | 
| 255 | run_remote <<'EOF' | 
| 256 | # 1) 如果 snapd.service 存在,就 disable 一下;否则跳过 | 
| 257 | if systemctl list-unit-files | grep -q '^snapd\.service'; then | 
| 258 | sudo systemctl disable --now snapd || true | 
| 259 | else | 
| 260 | echo "[ OK ] snapd.service not found, skipping disable" | 
| 261 | fi | 
| 262 | |
| 263 | # 2) 如果 dpkg 里检测到 snapd 包,就 purge 并清理数据目录 | 
| 264 | if dpkg -l snapd &>/dev/null; then | 
| 265 | sudo apt-get purge -y snapd | 
| 266 | sudo rm -rf /snap /var/lib/snapd /var/cache/snapd | 
| 267 | else | 
| 268 | echo "[ OK ] snapd package not installed, skipping purge" | 
| 269 | fi | 
| 270 | |
| 271 | # 3) 在所有机器都写上 no-snap 的 pin | 
| 272 | sudo tee /etc/apt/preferences.d/no-snap.pref > /dev/null <<EOP | 
| 273 | Package: snapd | 
| 274 | Pin: release a=* | 
| 275 | Pin-Priority: -10 | 
| 276 | EOP | 
| 277 | EOF | 
| 278 | |
| 279 | # 20) Final cleanup & benchmark | 
| 280 | print_ok "Final autoremove & benchmark" | 
| 281 | run_remote "sudo apt-get autoremove -y --purge && \ | 
| 282 | sudo apt-get install -y sysbench && sysbench cpu --threads=$(nproc) run && \ | 
| 283 | sudo apt-get autoremove -y sysbench --purge" | 
| 284 | |
| 285 | print_ok "Setup complete. Connect via: ssh $NEWUSER@$SERVER" | 
| 286 | |
| 287 | # After this script, server will: | 
| 288 | |
| 289 | # * Only allow SSH key login | 
| 290 | # * Root login disabled, password authentication disabled | 
| 291 | # * Have a new hostname set | 
| 292 | # * Have a new user with sudo privileges and can log in via SSH | 
| 293 | # * Have a random password stored securely at /etc/<new_user>.pass | 
| 294 | # * Have SSH key copied to authorized_keys so you can log in without a password | 
| 295 | # * Be hardened with UFW, Fail2Ban and allowed SSH connections(only) | 
| 296 | # * Have BBR enabled for better network performance | 
| 297 | # * Have the latest HWE kernel installed | 
| 298 | # * Have the best mirror selected for package updates | 
| 299 | # * Have snap removed | 
| 300 | # * Have CPU performance tuned to 'performance' mode | 
| 301 | # * Have timezone set to GMT | 
| 302 | # * Have all unnecessary users removed (Check /etc/passwd for remaining users) | 
| 303 | # * Have all unnecessary packages removed | 
| 304 | # * Have the latest updates installed | 
| 305 | # * Have sysbench installed for performance testing | 
| 306 | # * Have a final benchmark run to verify CPU performance | 
| 307 | # * Have a final cleanup of unnecessary packages | 
                    
                        
                        install_fail2ban.sh
                        
                             · 1.1 KiB · Bash
                        
                    
                    
                      
                        Surowy
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            #!/usr/bin/env bash
set -euo pipefail
echo "[+] Updating package index and installing fail2ban..."
sudo apt update
sudo apt install -y fail2ban
echo "[+] Writing /etc/fail2ban/jail.local..."
sudo tee /etc/fail2ban/jail.local > /dev/null <<'EOF'
[sshd]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3
findtime = 600
bantime  = 3600
EOF
sleep 1
echo "[+] Restarting fail2ban service..."
sudo systemctl restart fail2ban
echo "=== Fail2Ban global status ==="
# Allow script to continue even if fail2ban-client status fails (e.g., socket not yet ready)
sudo fail2ban-client status || true
echo "=== SSHD jail status ==="
sudo fail2ban-client status sshd || true
echo "Tip: To view the currently banned IP list again, run:"
echo "sudo fail2ban-client status sshd"
echo "Tip: To unban an IP address, run:"
echo "sudo fail2ban-client set sshd unbanip <IP_ADDRESS>"
echo "Tip: To ban an IP address manually, run:"
echo "sudo fail2ban-client set sshd banip <IP_ADDRESS>"
echo "Tip: To view the fail2ban logs, run:"
echo "sudo journalctl -u fail2ban"
                | 1 | #!/usr/bin/env bash | 
| 2 | set -euo pipefail | 
| 3 | |
| 4 | echo "[+] Updating package index and installing fail2ban..." | 
| 5 | sudo apt update | 
| 6 | sudo apt install -y fail2ban | 
| 7 | |
| 8 | echo "[+] Writing /etc/fail2ban/jail.local..." | 
| 9 | sudo tee /etc/fail2ban/jail.local > /dev/null <<'EOF' | 
| 10 | [sshd] | 
| 11 | enabled = true | 
| 12 | port = ssh | 
| 13 | filter = sshd | 
| 14 | logpath = /var/log/auth.log | 
| 15 | maxretry = 3 | 
| 16 | findtime = 600 | 
| 17 | bantime = 3600 | 
| 18 | EOF | 
| 19 | sleep 1 | 
| 20 | |
| 21 | echo "[+] Restarting fail2ban service..." | 
| 22 | sudo systemctl restart fail2ban | 
| 23 | |
| 24 | echo "=== Fail2Ban global status ===" | 
| 25 | # Allow script to continue even if fail2ban-client status fails (e.g., socket not yet ready) | 
| 26 | sudo fail2ban-client status || true | 
| 27 | |
| 28 | echo "=== SSHD jail status ===" | 
| 29 | sudo fail2ban-client status sshd || true | 
| 30 | |
| 31 | echo "Tip: To view the currently banned IP list again, run:" | 
| 32 | echo "sudo fail2ban-client status sshd" | 
| 33 | |
| 34 | echo "Tip: To unban an IP address, run:" | 
| 35 | echo "sudo fail2ban-client set sshd unbanip <IP_ADDRESS>" | 
| 36 | |
| 37 | echo "Tip: To ban an IP address manually, run:" | 
| 38 | echo "sudo fail2ban-client set sshd banip <IP_ADDRESS>" | 
| 39 | |
| 40 | echo "Tip: To view the fail2ban logs, run:" | 
| 41 | echo "sudo journalctl -u fail2ban" | 
| 42 | 
                    
                        
                        mirror.sh
                        
                             · 9.0 KiB · Bash
                        
                    
                    
                      
                        Surowy
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            #!/usr/bin/env bash
set -euo pipefail
# Check current APT source format status
check_apt_format() {
    local old_format=false
    local new_format=false
    
    # Check old format (.list)
    if [ -f "/etc/apt/sources.list" ]; then
        if grep -v '^#' /etc/apt/sources.list | grep -q '[^[:space:]]'; then
            old_format=true
        fi
    fi
    
    # Check for ubuntu.sources file in new format
    if [ -f "/etc/apt/sources.list.d/ubuntu.sources" ]; then
        if grep -v '^#' /etc/apt/sources.list.d/ubuntu.sources | grep -q '[^[:space:]]'; then
            new_format=true
        fi
    fi
    
    # Return status
    if $old_format && $new_format; then
        echo "both"
    elif $old_format; then
        echo "old"
    elif $new_format; then
        echo "new"
    else
        echo "none"
    fi
}
# Find the fastest mirror
find_fastest_mirror() {
    # Redirect all output to stderr
    echo "Testing mirror speeds..." >&2
    
    # Get current Ubuntu codename
    codename=$(lsb_release -cs)
    
    # Define list of potential mirrors
    mirrors=(
        "https://archive.ubuntu.com/ubuntu/"
        "https://mirror.aarnet.edu.au/pub/ubuntu/archive/" # Australia
        "https://mirror.fsmg.org.nz/ubuntu/"               # New Zealand
        "https://mirrors.neterra.net/ubuntu/archive/"       # Bulgaria
        "https://mirror.csclub.uwaterloo.ca/ubuntu/"        # Canada
        "https://mirrors.dotsrc.org/ubuntu/"                # Denmark
        "https://mirrors.nic.funet.fi/ubuntu/"              # Finland
        "https://mirror.ubuntu.ikoula.com/"                 # France
        "https://mirror.xtom.com.hk/ubuntu/"                # Hong Kong
        "https://mirrors.piconets.webwerks.in/ubuntu-mirror/ubuntu/" # India
        "https://ftp.udx.icscoe.jp/Linux/ubuntu/"           # Japan
        "https://ftp.kaist.ac.kr/ubuntu/"                   # Korea
        "https://ubuntu.mirror.garr.it/ubuntu/"             # Italy
        "https://ftp.uni-stuttgart.de/ubuntu/"              # Germany
        "https://mirror.i3d.net/pub/ubuntu/"                # Netherlands
        "https://mirroronet.pl/pub/mirrors/ubuntu/"         # Poland
        "https://ubuntu.mobinhost.com/ubuntu/"              # Iran
        "http://sg.archive.ubuntu.com/ubuntu/"              # Singapore
        "http://ossmirror.mycloud.services/os/linux/ubuntu/" # Singapore
        "https://mirror.enzu.com/ubuntu/"                   # United States
        "http://jp.archive.ubuntu.com/ubuntu/"              # Japan
        "http://kr.archive.ubuntu.com/ubuntu/"              # Korea
        "http://us.archive.ubuntu.com/ubuntu/"              # United States
        "http://tw.archive.ubuntu.com/ubuntu/"              # Taiwan
        "https://mirror.twds.com.tw/ubuntu/"                # Taiwan
        "https://ubuntu.mirrors.uk2.net/ubuntu/"            # United Kingdom
        "http://mirrors.ustc.edu.cn/ubuntu/"                # USTC
        "http://ftp.sjtu.edu.cn/ubuntu/"                    # SJTU
        "http://mirrors.tuna.tsinghua.edu.cn/ubuntu/"       # Tsinghua
        "http://mirrors.aliyun.com/ubuntu/"                 # Aliyun
        "http://mirrors.163.com/ubuntu/"                    # NetEase
        "http://mirrors.cloud.tencent.com/ubuntu/"          # Tencent Cloud
        "http://mirror.aiursoft.cn/ubuntu/"                 # Aiursoft
        "http://mirrors.huaweicloud.com/ubuntu/"            # Huawei Cloud
        "http://mirrors.zju.edu.cn/ubuntu/"                 # Zhejiang University
        "http://azure.archive.ubuntu.com/ubuntu/"           # Azure
        "https://mirrors.isu.net.sa/apt-mirror/"            # Saudi Arabia
        "https://mirror.team-host.ru/ubuntu/"               # Russia
        "https://labs.eif.urjc.es/mirror/ubuntu/"           # Spain
        "https://mirror.alastyr.com/ubuntu/ubuntu-archive/" # Turkey
        "https://ftp.acc.umu.se/ubuntu/"                    # Sweden
        "https://mirror.kku.ac.th/ubuntu/"                  # Thailand
        "https://mirror.bizflycloud.vn/ubuntu/"             # Vietnam
    )
    
    declare -A results
    
    # Test speed of each mirror
    for mirror in "${mirrors[@]}"; do
        echo "Testing $mirror ..." >&2
        response="$(curl -o /dev/null -s -w "%{http_code} %{time_total}\n" \
                  --connect-timeout 1 --max-time 3 "${mirror}dists/${codename}/Release")"
        
        http_code=$(echo "$response" | awk '{print $1}')
        time_total=$(echo "$response" | awk '{print $2}')
        
        if [ "$http_code" -eq 200 ]; then
            results["$mirror"]="$time_total"
            echo "  Success: $time_total seconds" >&2
        else
            echo "  Failed: HTTP code $http_code" >&2
            results["$mirror"]="9999"
        fi
    done
    
    # Sort mirrors by response time
    sorted_mirrors="$(
        for url in "${!results[@]}"; do
            echo "$url ${results[$url]}"
        done | sort -k2 -n
    )"
    
    echo >&2
    echo "=== Mirrors sorted by response time (ascending) ===" >&2
    echo "$sorted_mirrors" >&2
    echo >&2
    
    # Choose the fastest mirror
    fastest_mirror="$(echo "$sorted_mirrors" | head -n 1 | awk '{print $1}')"
    
    if [[ "$fastest_mirror" == "" || "${results[$fastest_mirror]}" == "9999" ]]; then
        echo "No usable mirror found, using default mirror" >&2
        fastest_mirror="http://archive.ubuntu.com/ubuntu/"
    fi
    
    echo "Fastest mirror found: $fastest_mirror" >&2
    echo >&2
    
    # Only this line will be returned to caller, without >&2
    echo "$fastest_mirror"
}
# Generate old format source list
generate_old_format() {
    local mirror="$1"
    local codename="$2"
    
    echo "Generating old format source list /etc/apt/sources.list"
    
    sudo tee /etc/apt/sources.list >/dev/null <<EOF
deb $mirror $codename main restricted universe multiverse
deb $mirror $codename-updates main restricted universe multiverse
deb $mirror $codename-backports main restricted universe multiverse
deb $mirror $codename-security main restricted universe multiverse
EOF
    
    echo "Old format source list updated"
}
# Generate new format source list
generate_new_format() {
    local mirror="$1"
    local codename="$2"
    
    echo "Generating new format source list /etc/apt/sources.list.d/ubuntu.sources"
    
    sudo tee /etc/apt/sources.list.d/ubuntu.sources >/dev/null <<EOF
Types: deb
URIs: $mirror
Suites: $codename
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
Types: deb
URIs: $mirror
Suites: $codename-updates
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
Types: deb
URIs: $mirror
Suites: $codename-backports
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
Types: deb
URIs: $mirror
Suites: $codename-security
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
EOF
    
    echo "New format source list updated"
}
# Main function
main() {
    # Ensure required packages are installed
    sudo apt update
    sudo apt install -y curl lsb-release bc
    
    # Get current source format
    format=$(check_apt_format)
    echo "Current APT source format status: $format"
    
    # Get Ubuntu codename
    codename=$(lsb_release -cs)
    echo "Ubuntu codename: $codename"
    
    # Find the fastest mirror
    echo "Searching for the fastest mirror..."
    fastest_mirror=$(find_fastest_mirror)
    
    # Decide update strategy based on format
    case "$format" in
        "none")
            echo "No valid APT source found, generating old format source list"
            generate_old_format "$fastest_mirror" "$codename"
            ;;
        "old")
            echo "System uses traditional format, updating old format source list"
            generate_old_format "$fastest_mirror" "$codename"
            ;;
        "new")
            echo "System uses modern format, updating new format source list"
            generate_new_format "$fastest_mirror" "$codename"
            ;;
        "both")
            echo "System uses both formats, old format will be removed, only new format will be retained"
            sudo mv /etc/apt/sources.list /etc/apt/sources.list.bak
            echo "Old format source list backed up to /etc/apt/sources.list.bak"
            generate_new_format "$fastest_mirror" "$codename"
            ;;
    esac
    
    # Update package list
    echo "Updating package list..."
    sudo apt update
    
    echo "APT source optimization completed!"
    aptVersion=$(apt --version | head -n 1 | awk '{print $2}')
    echo "Current APT version: $aptVersion"
    # If current APT version is 3.0 or higher, and using old format or none, convert to new format
    # sudo apt modernize-sources
    if [[ $(echo "$aptVersion >= 3.0" | bc) -eq 1 && ( "$format" == "old" || "$format" == "none" ) ]]; then
        echo "APT version is 3.0 or higher, converting to new format"
        sudo apt modernize-sources
        echo "APT sources converted to new format"
    fi
}
# Execute main function
main
                | 1 | #!/usr/bin/env bash | 
| 2 | set -euo pipefail | 
| 3 | |
| 4 | # Check current APT source format status | 
| 5 | check_apt_format() { | 
| 6 | local old_format=false | 
| 7 | local new_format=false | 
| 8 | |
| 9 | # Check old format (.list) | 
| 10 | if [ -f "/etc/apt/sources.list" ]; then | 
| 11 | if grep -v '^#' /etc/apt/sources.list | grep -q '[^[:space:]]'; then | 
| 12 | old_format=true | 
| 13 | fi | 
| 14 | fi | 
| 15 | |
| 16 | # Check for ubuntu.sources file in new format | 
| 17 | if [ -f "/etc/apt/sources.list.d/ubuntu.sources" ]; then | 
| 18 | if grep -v '^#' /etc/apt/sources.list.d/ubuntu.sources | grep -q '[^[:space:]]'; then | 
| 19 | new_format=true | 
| 20 | fi | 
| 21 | fi | 
| 22 | |
| 23 | # Return status | 
| 24 | if $old_format && $new_format; then | 
| 25 | echo "both" | 
| 26 | elif $old_format; then | 
| 27 | echo "old" | 
| 28 | elif $new_format; then | 
| 29 | echo "new" | 
| 30 | else | 
| 31 | echo "none" | 
| 32 | fi | 
| 33 | } | 
| 34 | |
| 35 | # Find the fastest mirror | 
| 36 | find_fastest_mirror() { | 
| 37 | # Redirect all output to stderr | 
| 38 | echo "Testing mirror speeds..." >&2 | 
| 39 | |
| 40 | # Get current Ubuntu codename | 
| 41 | codename=$(lsb_release -cs) | 
| 42 | |
| 43 | # Define list of potential mirrors | 
| 44 | mirrors=( | 
| 45 | "https://archive.ubuntu.com/ubuntu/" | 
| 46 | "https://mirror.aarnet.edu.au/pub/ubuntu/archive/" # Australia | 
| 47 | "https://mirror.fsmg.org.nz/ubuntu/" # New Zealand | 
| 48 | "https://mirrors.neterra.net/ubuntu/archive/" # Bulgaria | 
| 49 | "https://mirror.csclub.uwaterloo.ca/ubuntu/" # Canada | 
| 50 | "https://mirrors.dotsrc.org/ubuntu/" # Denmark | 
| 51 | "https://mirrors.nic.funet.fi/ubuntu/" # Finland | 
| 52 | "https://mirror.ubuntu.ikoula.com/" # France | 
| 53 | "https://mirror.xtom.com.hk/ubuntu/" # Hong Kong | 
| 54 | "https://mirrors.piconets.webwerks.in/ubuntu-mirror/ubuntu/" # India | 
| 55 | "https://ftp.udx.icscoe.jp/Linux/ubuntu/" # Japan | 
| 56 | "https://ftp.kaist.ac.kr/ubuntu/" # Korea | 
| 57 | "https://ubuntu.mirror.garr.it/ubuntu/" # Italy | 
| 58 | "https://ftp.uni-stuttgart.de/ubuntu/" # Germany | 
| 59 | "https://mirror.i3d.net/pub/ubuntu/" # Netherlands | 
| 60 | "https://mirroronet.pl/pub/mirrors/ubuntu/" # Poland | 
| 61 | "https://ubuntu.mobinhost.com/ubuntu/" # Iran | 
| 62 | "http://sg.archive.ubuntu.com/ubuntu/" # Singapore | 
| 63 | "http://ossmirror.mycloud.services/os/linux/ubuntu/" # Singapore | 
| 64 | "https://mirror.enzu.com/ubuntu/" # United States | 
| 65 | "http://jp.archive.ubuntu.com/ubuntu/" # Japan | 
| 66 | "http://kr.archive.ubuntu.com/ubuntu/" # Korea | 
| 67 | "http://us.archive.ubuntu.com/ubuntu/" # United States | 
| 68 | "http://tw.archive.ubuntu.com/ubuntu/" # Taiwan | 
| 69 | "https://mirror.twds.com.tw/ubuntu/" # Taiwan | 
| 70 | "https://ubuntu.mirrors.uk2.net/ubuntu/" # United Kingdom | 
| 71 | "http://mirrors.ustc.edu.cn/ubuntu/" # USTC | 
| 72 | "http://ftp.sjtu.edu.cn/ubuntu/" # SJTU | 
| 73 | "http://mirrors.tuna.tsinghua.edu.cn/ubuntu/" # Tsinghua | 
| 74 | "http://mirrors.aliyun.com/ubuntu/" # Aliyun | 
| 75 | "http://mirrors.163.com/ubuntu/" # NetEase | 
| 76 | "http://mirrors.cloud.tencent.com/ubuntu/" # Tencent Cloud | 
| 77 | "http://mirror.aiursoft.cn/ubuntu/" # Aiursoft | 
| 78 | "http://mirrors.huaweicloud.com/ubuntu/" # Huawei Cloud | 
| 79 | "http://mirrors.zju.edu.cn/ubuntu/" # Zhejiang University | 
| 80 | "http://azure.archive.ubuntu.com/ubuntu/" # Azure | 
| 81 | "https://mirrors.isu.net.sa/apt-mirror/" # Saudi Arabia | 
| 82 | "https://mirror.team-host.ru/ubuntu/" # Russia | 
| 83 | "https://labs.eif.urjc.es/mirror/ubuntu/" # Spain | 
| 84 | "https://mirror.alastyr.com/ubuntu/ubuntu-archive/" # Turkey | 
| 85 | "https://ftp.acc.umu.se/ubuntu/" # Sweden | 
| 86 | "https://mirror.kku.ac.th/ubuntu/" # Thailand | 
| 87 | "https://mirror.bizflycloud.vn/ubuntu/" # Vietnam | 
| 88 | ) | 
| 89 | |
| 90 | declare -A results | 
| 91 | |
| 92 | # Test speed of each mirror | 
| 93 | for mirror in "${mirrors[@]}"; do | 
| 94 | echo "Testing $mirror ..." >&2 | 
| 95 | response="$(curl -o /dev/null -s -w "%{http_code} %{time_total}\n" \ | 
| 96 | --connect-timeout 1 --max-time 3 "${mirror}dists/${codename}/Release")" | 
| 97 | |
| 98 | http_code=$(echo "$response" | awk '{print $1}') | 
| 99 | time_total=$(echo "$response" | awk '{print $2}') | 
| 100 | |
| 101 | if [ "$http_code" -eq 200 ]; then | 
| 102 | results["$mirror"]="$time_total" | 
| 103 | echo " Success: $time_total seconds" >&2 | 
| 104 | else | 
| 105 | echo " Failed: HTTP code $http_code" >&2 | 
| 106 | results["$mirror"]="9999" | 
| 107 | fi | 
| 108 | done | 
| 109 | |
| 110 | # Sort mirrors by response time | 
| 111 | sorted_mirrors="$( | 
| 112 | for url in "${!results[@]}"; do | 
| 113 | echo "$url ${results[$url]}" | 
| 114 | done | sort -k2 -n | 
| 115 | )" | 
| 116 | |
| 117 | echo >&2 | 
| 118 | echo "=== Mirrors sorted by response time (ascending) ===" >&2 | 
| 119 | echo "$sorted_mirrors" >&2 | 
| 120 | echo >&2 | 
| 121 | |
| 122 | # Choose the fastest mirror | 
| 123 | fastest_mirror="$(echo "$sorted_mirrors" | head -n 1 | awk '{print $1}')" | 
| 124 | |
| 125 | if [[ "$fastest_mirror" == "" || "${results[$fastest_mirror]}" == "9999" ]]; then | 
| 126 | echo "No usable mirror found, using default mirror" >&2 | 
| 127 | fastest_mirror="http://archive.ubuntu.com/ubuntu/" | 
| 128 | fi | 
| 129 | |
| 130 | echo "Fastest mirror found: $fastest_mirror" >&2 | 
| 131 | echo >&2 | 
| 132 | |
| 133 | # Only this line will be returned to caller, without >&2 | 
| 134 | echo "$fastest_mirror" | 
| 135 | } | 
| 136 | |
| 137 | # Generate old format source list | 
| 138 | generate_old_format() { | 
| 139 | local mirror="$1" | 
| 140 | local codename="$2" | 
| 141 | |
| 142 | echo "Generating old format source list /etc/apt/sources.list" | 
| 143 | |
| 144 | sudo tee /etc/apt/sources.list >/dev/null <<EOF | 
| 145 | deb $mirror $codename main restricted universe multiverse | 
| 146 | deb $mirror $codename-updates main restricted universe multiverse | 
| 147 | deb $mirror $codename-backports main restricted universe multiverse | 
| 148 | deb $mirror $codename-security main restricted universe multiverse | 
| 149 | EOF | 
| 150 | |
| 151 | echo "Old format source list updated" | 
| 152 | } | 
| 153 | |
| 154 | # Generate new format source list | 
| 155 | generate_new_format() { | 
| 156 | local mirror="$1" | 
| 157 | local codename="$2" | 
| 158 | |
| 159 | echo "Generating new format source list /etc/apt/sources.list.d/ubuntu.sources" | 
| 160 | |
| 161 | sudo tee /etc/apt/sources.list.d/ubuntu.sources >/dev/null <<EOF | 
| 162 | Types: deb | 
| 163 | URIs: $mirror | 
| 164 | Suites: $codename | 
| 165 | Components: main restricted universe multiverse | 
| 166 | Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg | 
| 167 | |
| 168 | Types: deb | 
| 169 | URIs: $mirror | 
| 170 | Suites: $codename-updates | 
| 171 | Components: main restricted universe multiverse | 
| 172 | Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg | 
| 173 | |
| 174 | Types: deb | 
| 175 | URIs: $mirror | 
| 176 | Suites: $codename-backports | 
| 177 | Components: main restricted universe multiverse | 
| 178 | Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg | 
| 179 | |
| 180 | Types: deb | 
| 181 | URIs: $mirror | 
| 182 | Suites: $codename-security | 
| 183 | Components: main restricted universe multiverse | 
| 184 | Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg | 
| 185 | EOF | 
| 186 | |
| 187 | echo "New format source list updated" | 
| 188 | } | 
| 189 | |
| 190 | # Main function | 
| 191 | main() { | 
| 192 | # Ensure required packages are installed | 
| 193 | sudo apt update | 
| 194 | sudo apt install -y curl lsb-release bc | 
| 195 | |
| 196 | # Get current source format | 
| 197 | format=$(check_apt_format) | 
| 198 | echo "Current APT source format status: $format" | 
| 199 | |
| 200 | # Get Ubuntu codename | 
| 201 | codename=$(lsb_release -cs) | 
| 202 | echo "Ubuntu codename: $codename" | 
| 203 | |
| 204 | # Find the fastest mirror | 
| 205 | echo "Searching for the fastest mirror..." | 
| 206 | fastest_mirror=$(find_fastest_mirror) | 
| 207 | |
| 208 | # Decide update strategy based on format | 
| 209 | case "$format" in | 
| 210 | "none") | 
| 211 | echo "No valid APT source found, generating old format source list" | 
| 212 | generate_old_format "$fastest_mirror" "$codename" | 
| 213 | ;; | 
| 214 | "old") | 
| 215 | echo "System uses traditional format, updating old format source list" | 
| 216 | generate_old_format "$fastest_mirror" "$codename" | 
| 217 | ;; | 
| 218 | "new") | 
| 219 | echo "System uses modern format, updating new format source list" | 
| 220 | generate_new_format "$fastest_mirror" "$codename" | 
| 221 | ;; | 
| 222 | "both") | 
| 223 | echo "System uses both formats, old format will be removed, only new format will be retained" | 
| 224 | sudo mv /etc/apt/sources.list /etc/apt/sources.list.bak | 
| 225 | echo "Old format source list backed up to /etc/apt/sources.list.bak" | 
| 226 | generate_new_format "$fastest_mirror" "$codename" | 
| 227 | ;; | 
| 228 | esac | 
| 229 | |
| 230 | # Update package list | 
| 231 | echo "Updating package list..." | 
| 232 | sudo apt update | 
| 233 | |
| 234 | echo "APT source optimization completed!" | 
| 235 | |
| 236 | aptVersion=$(apt --version | head -n 1 | awk '{print $2}') | 
| 237 | echo "Current APT version: $aptVersion" | 
| 238 | |
| 239 | # If current APT version is 3.0 or higher, and using old format or none, convert to new format | 
| 240 | # sudo apt modernize-sources | 
| 241 | if [[ $(echo "$aptVersion >= 3.0" | bc) -eq 1 && ( "$format" == "old" || "$format" == "none" ) ]]; then | 
| 242 | echo "APT version is 3.0 or higher, converting to new format" | 
| 243 | sudo apt modernize-sources | 
| 244 | echo "APT sources converted to new format" | 
| 245 | fi | 
| 246 | |
| 247 | } | 
| 248 | |
| 249 | # Execute main function | 
| 250 | main | 
| 251 |