init.sh
                        
                             · 6.7 KiB · Bash
                        
                    
                    
                      
                        原始文件
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            #!/usr/bin/env bash
#===============================================================================
# Concise server preparation script with error confirmation
#===============================================================================
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 "$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
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
# 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 & set random password
PASS_NEW=$(uuidgen)
print_ok "Setting password for $NEWUSER"
run_remote "echo '$NEWUSER:$PASS_NEW' | sudo chpasswd"
print_ok "New password for $NEWUSER: $PASS_NEW"
# 7) Copy SSH key
[ ! -f ~/.ssh/id_rsa.pub ] && run_local ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
print_ok "Copying SSH key"
sshpass -p "$PASS_NEW" ssh-copy-id -i ~/.ssh/id_rsa.pub "$NEWUSER@$SERVER"
# Switch to new user for subsequent operations
print_ok "Switching to new user $NEWUSER instead of $REMOTE_USER"
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"
run_remote "sudo systemctl restart sshd"
# 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"
run_remote "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"
run_remote "sudo ufw allow OpenSSH && echo y | sudo ufw enable"
# 12) Install & configure Fail2Ban
print_ok "Installing Fail2Ban"
run_remote "sudo apt-get update"
run_remote "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
logpath   = /var/log/auth.log
maxretry  = 3
findtime  = 600
bantime   = 3600
EOJ
sudo systemctl restart fail2ban
EOF
print_ok "Fail2Ban setup complete"
run_remote "sudo fail2ban-client status sshd"
# 13) Enable BBR
print_ok "Enabling BBR congestion control"
#run_remote "sudo bash -c 'grep -q bbr /etc/sysctl.conf || { echo net.core.default_qdisc=fq >>/etc/sysctl.conf; echo net.ipv4.tcp_congestion_control=bbr >>/etc/sysctl.conf; sysctl -p; }'"
run_remote <<'EOF'
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 latest HWE kernel
print_ok "Installing latest HWE kernel"
run_remote "sudo apt-get install -y \$(apt search linux-generic-hwe- | awk -F/ '/linux-generic-hwe-/{print \$1}' | head -1)"
# 16) Reboot & wait
print_ok "Rebooting server"
run_remote "sudo reboot" || true
sleep 5
wait_ssh
# 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)"
run_remote "sudo apt-get install -y cpupower" || true
run_remote "sudo cpupower frequency-set -g performance" || true
run_remote "sudo timedatectl set-timezone GMT"
# 19) Remove snap
print_ok "Removing snapd"
run_remote "sudo systemctl disable --now snapd && sudo apt-get purge -y snapd && sudo rm -rf /snap /var/lib/snapd /var/cache/snapd"
run_remote "sudo tee /etc/apt/preferences.d/no-snap.pref <<EOF
Package: snapd
Pin: release a=*
Pin-Priority: -10
EOF"
# 20) Final cleanup & benchmark
print_ok "Final autoremove & benchmark"
run_remote "sudo apt-get autoremove -y --purge"
run_remote "sudo apt-get install -y sysbench && sysbench cpu --threads=\$(nproc) run"
run_remote "sudo apt-get autoremove -y sysbench --purge"
print_ok "Setup complete. Connect via: ssh $NEWUSER@$SERVER"
                | 1 | #!/usr/bin/env bash | 
| 2 | #=============================================================================== | 
| 3 | # Concise server preparation script with error confirmation | 
| 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 -o StrictHostKeyChecking=no "$REMOTE_USER@$SERVER" exit; do | 
| 41 | print_warn "SSH not ready, retrying in 5s..." | 
| 42 | sleep 5 | 
| 43 | done | 
| 44 | print_ok "SSH available." | 
| 45 | } | 
| 46 | |
| 47 | usage(){ echo "Usage: $0 <orig_user> <orig_pass> <server> <new_hostname> <new_user>"; exit 1; } | 
| 48 | |
| 49 | #----------------------------------- | 
| 50 | # Main | 
| 51 | #----------------------------------- | 
| 52 | [ $# -ne 5 ] && usage | 
| 53 | USER="$1"; PASS="$2"; SERVER="$3"; HOSTNAME="$4"; NEWUSER="$5" | 
| 54 | REMOTE_USER="$USER"; REMOTE_PASS="$PASS" | 
| 55 | |
| 56 | # 1) Install sshpass locally | 
| 57 | run_local sudo apt-get update -y | 
| 58 | run_local sudo apt-get install -y sshpass | 
| 59 | |
| 60 | # 2) Clear known_hosts, wait for SSH | 
| 61 | run_local ssh-keygen -R "$SERVER" -f ~/.ssh/known_hosts | 
| 62 | wait_ssh | 
| 63 | |
| 64 | # 3) Hostname & reboot | 
| 65 | print_ok "Setting hostname to $HOSTNAME" | 
| 66 | run_remote "sudo hostnamectl set-hostname $HOSTNAME" | 
| 67 | run_remote "sudo reboot" || true | 
| 68 | print_ok "Server rebooting..." | 
| 69 | sleep 5 | 
| 70 | wait_ssh | 
| 71 | |
| 72 | # 4) Create or verify new user | 
| 73 | if run_remote "id -u $NEWUSER" &>/dev/null; then | 
| 74 | print_ok "User $NEWUSER exists" | 
| 75 | else | 
| 76 | print_ok "Creating user $NEWUSER" | 
| 77 | run_remote "sudo adduser --disabled-password --gecos '' $NEWUSER" | 
| 78 | fi | 
| 79 | |
| 80 | # 5) Grant sudo & set up passwordless | 
| 81 | print_ok "Granting sudo to $NEWUSER" | 
| 82 | run_remote "sudo usermod -aG sudo $NEWUSER" | 
| 83 | |
| 84 | print_ok "Setting passwordless sudo for $NEWUSER" | 
| 85 | run_remote "echo '$NEWUSER ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/$NEWUSER" | 
| 86 | |
| 87 | # 6) Generate & set random password | 
| 88 | PASS_NEW=$(uuidgen) | 
| 89 | print_ok "Setting password for $NEWUSER" | 
| 90 | run_remote "echo '$NEWUSER:$PASS_NEW' | sudo chpasswd" | 
| 91 | print_ok "New password for $NEWUSER: $PASS_NEW" | 
| 92 | |
| 93 | # 7) Copy SSH key | 
| 94 | [ ! -f ~/.ssh/id_rsa.pub ] && run_local ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa | 
| 95 | print_ok "Copying SSH key" | 
| 96 | sshpass -p "$PASS_NEW" ssh-copy-id -i ~/.ssh/id_rsa.pub "$NEWUSER@$SERVER" | 
| 97 | |
| 98 | # Switch to new user for subsequent operations | 
| 99 | print_ok "Switching to new user $NEWUSER instead of $REMOTE_USER" | 
| 100 | REMOTE_USER="$NEWUSER"; REMOTE_PASS="$PASS_NEW" | 
| 101 | wait_ssh | 
| 102 | |
| 103 | # 8) Harden SSH | 
| 104 | print_ok "Hardening SSH settings" | 
| 105 | run_remote "sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/; s/PasswordAuthentication yes/PasswordAuthentication no/; s/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config" | 
| 106 | run_remote "sudo systemctl restart sshd" | 
| 107 | |
| 108 | # 9) Remove other non-system users | 
| 109 | print_ok "Removing other users" | 
| 110 | others=$(run_remote \ | 
| 111 | "awk -F: -v skip='$NEWUSER' '\$3>=1000 && \$1!=skip {print \$1}' /etc/passwd") | 
| 112 | |
| 113 | for u in $others; do | 
| 114 | print_warn "Deleting user $u" | 
| 115 | run_remote "sudo pkill -u $u || true; sudo deluser --remove-home $u" | 
| 116 | done | 
| 117 | |
| 118 | # 10) Reset machine-id | 
| 119 | print_ok "Resetting machine-id" | 
| 120 | run_remote "sudo rm -f /etc/machine-id /var/lib/dbus/machine-id" | 
| 121 | run_remote "sudo systemd-machine-id-setup; sudo cp /etc/machine-id /var/lib/dbus/machine-id" | 
| 122 | |
| 123 | # 11) Enable UFW & OpenSSH | 
| 124 | print_ok "Enabling UFW firewall" | 
| 125 | run_remote "sudo apt-get install -y ufw" | 
| 126 | run_remote "sudo ufw allow OpenSSH && echo y | sudo ufw enable" | 
| 127 | |
| 128 | # 12) Install & configure Fail2Ban | 
| 129 | print_ok "Installing Fail2Ban" | 
| 130 | run_remote "sudo apt-get update" | 
| 131 | run_remote "sudo apt-get install -y fail2ban" | 
| 132 | print_ok "Configuring Fail2Ban" | 
| 133 | run_remote <<'EOF' | 
| 134 | sudo tee /etc/fail2ban/jail.local > /dev/null <<EOJ | 
| 135 | [sshd] | 
| 136 | enabled = true | 
| 137 | port = ssh | 
| 138 | filter = sshd | 
| 139 | logpath = /var/log/auth.log | 
| 140 | maxretry = 3 | 
| 141 | findtime = 600 | 
| 142 | bantime = 3600 | 
| 143 | EOJ | 
| 144 | sudo systemctl restart fail2ban | 
| 145 | EOF | 
| 146 | print_ok "Fail2Ban setup complete" | 
| 147 | run_remote "sudo fail2ban-client status sshd" | 
| 148 | |
| 149 | # 13) Enable BBR | 
| 150 | print_ok "Enabling BBR congestion control" | 
| 151 | #run_remote "sudo bash -c 'grep -q bbr /etc/sysctl.conf || { echo net.core.default_qdisc=fq >>/etc/sysctl.conf; echo net.ipv4.tcp_congestion_control=bbr >>/etc/sysctl.conf; sysctl -p; }'" | 
| 152 | run_remote <<'EOF' | 
| 153 | sudo tee /etc/sysctl.d/99-bbr.conf > /dev/null <<SYSCTL | 
| 154 | net.core.default_qdisc = fq | 
| 155 | net.ipv4.tcp_congestion_control = bbr | 
| 156 | SYSCTL | 
| 157 | sudo sysctl --system | 
| 158 | EOF | 
| 159 | |
| 160 | # 14) Select best mirror & update | 
| 161 | print_ok "Selecting best mirror & updating" | 
| 162 | run_remote "curl -s https://gist.aiursoft.cn/anduin/879917820a6c4b268fc12c21f1b3fe7a/raw/HEAD/mirror.sh | bash" | 
| 163 | run_remote "sudo apt-get update" | 
| 164 | |
| 165 | # 15) Install latest HWE kernel | 
| 166 | print_ok "Installing latest HWE kernel" | 
| 167 | run_remote "sudo apt-get install -y \$(apt search linux-generic-hwe- | awk -F/ '/linux-generic-hwe-/{print \$1}' | head -1)" | 
| 168 | |
| 169 | # 16) Reboot & wait | 
| 170 | print_ok "Rebooting server" | 
| 171 | run_remote "sudo reboot" || true | 
| 172 | sleep 5 | 
| 173 | wait_ssh | 
| 174 | |
| 175 | # 17) Final updates & cleanup | 
| 176 | print_ok "Installing upgrades & cleanup" | 
| 177 | run_remote "sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get autoremove -y" | 
| 178 | |
| 179 | # 18) Performance tuning | 
| 180 | print_ok "Tuning CPU performance & timezone" | 
| 181 | run_remote "sudo apt-get install -y linux-tools-$(uname -r)" | 
| 182 | run_remote "sudo apt-get install -y cpupower" || true | 
| 183 | run_remote "sudo cpupower frequency-set -g performance" || true | 
| 184 | run_remote "sudo timedatectl set-timezone GMT" | 
| 185 | |
| 186 | # 19) Remove snap | 
| 187 | print_ok "Removing snapd" | 
| 188 | run_remote "sudo systemctl disable --now snapd && sudo apt-get purge -y snapd && sudo rm -rf /snap /var/lib/snapd /var/cache/snapd" | 
| 189 | run_remote "sudo tee /etc/apt/preferences.d/no-snap.pref <<EOF | 
| 190 | Package: snapd | 
| 191 | Pin: release a=* | 
| 192 | Pin-Priority: -10 | 
| 193 | EOF" | 
| 194 | |
| 195 | # 20) Final cleanup & benchmark | 
| 196 | print_ok "Final autoremove & benchmark" | 
| 197 | run_remote "sudo apt-get autoremove -y --purge" | 
| 198 | run_remote "sudo apt-get install -y sysbench && sysbench cpu --threads=\$(nproc) run" | 
| 199 | run_remote "sudo apt-get autoremove -y sysbench --purge" | 
| 200 | print_ok "Setup complete. Connect via: ssh $NEWUSER@$SERVER" | 
| 201 | |
| 202 | 
                    
                        
                        install_fail2ban.sh
                        
                             · 1.1 KiB · Bash
                        
                    
                    
                      
                        原始文件
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            #!/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
                        
                             · 4.9 KiB · Bash
                        
                    
                    
                      
                        原始文件
                      
                    
                      
                    
                        
                          
                        
                    
                    
                
                
                
            #!/usr/bin/env bash
# Step 1: Ensure required packages are installed
sudo apt update
sudo apt install -y curl apt-transport-https lsb-release
function switchSource() {
  # Get current Ubuntu codename (e.g., jammy, focal, bionic)
  codename=$(lsb_release -cs)
  # Define a 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/"                # 中国科学技术大学
    "http://ftp.sjtu.edu.cn/ubuntu/"                    # 上海交通大学
    "http://mirrors.tuna.tsinghua.edu.cn/ubuntu/"       # 清华大学
    "http://mirrors.aliyun.com/ubuntu/"                 # 阿里云
    "http://mirrors.163.com/ubuntu/"                    # 网易
    "http://mirrors.cloud.tencent.com/ubuntu/"          # 腾讯云
    "http://mirror.aiursoft.cn/ubuntu/"                 # Aiursoft
    "http://mirrors.huaweicloud.com/ubuntu/"            # 华为云
    "http://mirrors.zju.edu.cn/ubuntu/"                 # 浙江大学
    "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
  # Function to test speed of a single mirror
  test_speed() {
    url="$1"
    # Attempt to do a quick GET and measure total time
    response="$(curl -o /dev/null -s -w "%{http_code} %{time_total}\n" \
                --connect-timeout 1 --max-time 2 "$url")"
    http_code=$(echo "$response" | awk '{print $1}')
    time_total=$(echo "$response" | awk '{print $2}')
    # If HTTP code == 200, mark the measured time; otherwise use a large value
    if [ "$http_code" -eq 200 ]; then
      results["$url"]="$time_total"
    else
      echo "Failed to access $url (HTTP code: $http_code)"
      results["$url"]="9999"
    fi
  }
  echo "Testing all mirrors for Ubuntu '$codename'..."
  for mirror in "${mirrors[@]}"; do
    test_speed "$mirror"
  done
  # Sort mirrors by time_total
  # Example of sorted_mirrors entry: "https://archive.ubuntu.com/ubuntu/ 0.034"
  sorted_mirrors="$(
    for url in "${!results[@]}"; do
      echo "$url ${results[$url]}"
    done | sort -k2 -n
  )"
  echo
  echo "=== Sorted mirrors by response time (ascending) ==="
  echo "$sorted_mirrors"
  echo
  # Pick the top (fastest) mirror from the sorted list
  fastest_mirror="$(echo "$sorted_mirrors" | head -n 1 | awk '{print $1}')"
  echo "Fastest mirror found: $fastest_mirror"
  echo "Updating /etc/apt/sources.list..."
  # Update /etc/apt/sources.list with the fastest mirror
  sudo tee /etc/apt/sources.list >/dev/null <<EOF
deb $fastest_mirror $codename main restricted universe multiverse
deb $fastest_mirror $codename-updates main restricted universe multiverse
deb $fastest_mirror $codename-backports main restricted universe multiverse
deb $fastest_mirror $codename-security main restricted universe multiverse
EOF
  # Final check
  sudo apt update
  echo "All done!"
}
# Call the main function
switchSource
                | 1 | #!/usr/bin/env bash | 
| 2 | # Step 1: Ensure required packages are installed | 
| 3 | sudo apt update | 
| 4 | sudo apt install -y curl apt-transport-https lsb-release | 
| 5 | |
| 6 | function switchSource() { | 
| 7 | # Get current Ubuntu codename (e.g., jammy, focal, bionic) | 
| 8 | codename=$(lsb_release -cs) | 
| 9 | |
| 10 | # Define a list of potential mirrors | 
| 11 | mirrors=( | 
| 12 | "https://archive.ubuntu.com/ubuntu/" | 
| 13 | "https://mirror.aarnet.edu.au/pub/ubuntu/archive/" # Australia | 
| 14 | "https://mirror.fsmg.org.nz/ubuntu/" # New Zealand | 
| 15 | "https://mirrors.neterra.net/ubuntu/archive/" # Bulgaria | 
| 16 | "https://mirror.csclub.uwaterloo.ca/ubuntu/" # Canada | 
| 17 | "https://mirrors.dotsrc.org/ubuntu/" # Denmark | 
| 18 | "https://mirrors.nic.funet.fi/ubuntu/" # Finland | 
| 19 | "https://mirror.ubuntu.ikoula.com/" # France | 
| 20 | "https://mirror.xtom.com.hk/ubuntu/" # Hong Kong | 
| 21 | "https://mirrors.piconets.webwerks.in/ubuntu-mirror/ubuntu/" # India | 
| 22 | "https://ftp.udx.icscoe.jp/Linux/ubuntu/" # Japan | 
| 23 | "https://ftp.kaist.ac.kr/ubuntu/" # Korea | 
| 24 | "https://ubuntu.mirror.garr.it/ubuntu/" # Italy | 
| 25 | "https://ftp.uni-stuttgart.de/ubuntu/" # Germany | 
| 26 | "https://mirror.i3d.net/pub/ubuntu/" # Netherlands | 
| 27 | "https://mirroronet.pl/pub/mirrors/ubuntu/" # Poland | 
| 28 | "https://ubuntu.mobinhost.com/ubuntu/" # Iran | 
| 29 | "http://sg.archive.ubuntu.com/ubuntu/" # Singapore | 
| 30 | "http://ossmirror.mycloud.services/os/linux/ubuntu/" # Singapore | 
| 31 | "https://mirror.enzu.com/ubuntu/" # United States | 
| 32 | "http://jp.archive.ubuntu.com/ubuntu/" # Japan | 
| 33 | "http://kr.archive.ubuntu.com/ubuntu/" # Korea | 
| 34 | "http://us.archive.ubuntu.com/ubuntu/" # United States | 
| 35 | "http://tw.archive.ubuntu.com/ubuntu/" # Taiwan | 
| 36 | "https://mirror.twds.com.tw/ubuntu/" # Taiwan | 
| 37 | "https://ubuntu.mirrors.uk2.net/ubuntu/" # United Kingdom | 
| 38 | "http://mirrors.ustc.edu.cn/ubuntu/" # 中国科学技术大学 | 
| 39 | "http://ftp.sjtu.edu.cn/ubuntu/" # 上海交通大学 | 
| 40 | "http://mirrors.tuna.tsinghua.edu.cn/ubuntu/" # 清华大学 | 
| 41 | "http://mirrors.aliyun.com/ubuntu/" # 阿里云 | 
| 42 | "http://mirrors.163.com/ubuntu/" # 网易 | 
| 43 | "http://mirrors.cloud.tencent.com/ubuntu/" # 腾讯云 | 
| 44 | "http://mirror.aiursoft.cn/ubuntu/" # Aiursoft | 
| 45 | "http://mirrors.huaweicloud.com/ubuntu/" # 华为云 | 
| 46 | "http://mirrors.zju.edu.cn/ubuntu/" # 浙江大学 | 
| 47 | "http://azure.archive.ubuntu.com/ubuntu/" # Azure | 
| 48 | "https://mirrors.isu.net.sa/apt-mirror/" # Saudi Arabia | 
| 49 | "https://mirror.team-host.ru/ubuntu/" # Russia | 
| 50 | "https://labs.eif.urjc.es/mirror/ubuntu/" # Spain | 
| 51 | "https://mirror.alastyr.com/ubuntu/ubuntu-archive/" # Turkey | 
| 52 | "https://ftp.acc.umu.se/ubuntu/" # Sweden | 
| 53 | "https://mirror.kku.ac.th/ubuntu/" # Thailand | 
| 54 | "https://mirror.bizflycloud.vn/ubuntu/" # Vietnam | 
| 55 | ) | 
| 56 | |
| 57 | declare -A results | 
| 58 | |
| 59 | # Function to test speed of a single mirror | 
| 60 | test_speed() { | 
| 61 | url="$1" | 
| 62 | # Attempt to do a quick GET and measure total time | 
| 63 | response="$(curl -o /dev/null -s -w "%{http_code} %{time_total}\n" \ | 
| 64 | --connect-timeout 1 --max-time 2 "$url")" | 
| 65 | |
| 66 | http_code=$(echo "$response" | awk '{print $1}') | 
| 67 | time_total=$(echo "$response" | awk '{print $2}') | 
| 68 | |
| 69 | # If HTTP code == 200, mark the measured time; otherwise use a large value | 
| 70 | if [ "$http_code" -eq 200 ]; then | 
| 71 | results["$url"]="$time_total" | 
| 72 | else | 
| 73 | echo "Failed to access $url (HTTP code: $http_code)" | 
| 74 | results["$url"]="9999" | 
| 75 | fi | 
| 76 | } | 
| 77 | |
| 78 | echo "Testing all mirrors for Ubuntu '$codename'..." | 
| 79 | for mirror in "${mirrors[@]}"; do | 
| 80 | test_speed "$mirror" | 
| 81 | done | 
| 82 | |
| 83 | # Sort mirrors by time_total | 
| 84 | # Example of sorted_mirrors entry: "https://archive.ubuntu.com/ubuntu/ 0.034" | 
| 85 | sorted_mirrors="$( | 
| 86 | for url in "${!results[@]}"; do | 
| 87 | echo "$url ${results[$url]}" | 
| 88 | done | sort -k2 -n | 
| 89 | )" | 
| 90 | |
| 91 | echo | 
| 92 | echo "=== Sorted mirrors by response time (ascending) ===" | 
| 93 | echo "$sorted_mirrors" | 
| 94 | echo | 
| 95 | |
| 96 | # Pick the top (fastest) mirror from the sorted list | 
| 97 | fastest_mirror="$(echo "$sorted_mirrors" | head -n 1 | awk '{print $1}')" | 
| 98 | |
| 99 | echo "Fastest mirror found: $fastest_mirror" | 
| 100 | echo "Updating /etc/apt/sources.list..." | 
| 101 | |
| 102 | # Update /etc/apt/sources.list with the fastest mirror | 
| 103 | sudo tee /etc/apt/sources.list >/dev/null <<EOF | 
| 104 | deb $fastest_mirror $codename main restricted universe multiverse | 
| 105 | deb $fastest_mirror $codename-updates main restricted universe multiverse | 
| 106 | deb $fastest_mirror $codename-backports main restricted universe multiverse | 
| 107 | deb $fastest_mirror $codename-security main restricted universe multiverse | 
| 108 | EOF | 
| 109 | |
| 110 | # Final check | 
| 111 | sudo apt update | 
| 112 | echo "All done!" | 
| 113 | } | 
| 114 | |
| 115 | # Call the main function | 
| 116 | switchSource |