每次新建了一个VPS,或者重装了Debian系统,要把ssh密码登录改成密钥登录都要输好多条命令,略显繁琐,所以写了一个小脚本,可以一键执行
#!/bin/bash
# Backup existing SSH configuration
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# Generate a random port number for SSH
port=$(shuf -i 20000-60000 -n 1)
# Generate SSH key if it does not exist
if [ ! -f ~/.ssh/id_rsa ]; then
echo "Generating SSH key..."
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -q -N ""
fi
# Add SSH key to authorized keys
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh
# Update SSH configuration
sudo sed -i 's/^#\?\(PubkeyAuthentication\s*\).*$/\1yes/' /etc/ssh/sshd_config
sudo sed -i 's/^#\?\(PasswordAuthentication\s*\).*$/\1no/' /etc/ssh/sshd_config
sudo sed -i 's/^#\?\(ChallengeResponseAuthentication\s*\).*$/\1no/' /etc/ssh/sshd_config
sudo sed -i "s/^#\?\\(Port\\s*\\).*$/\\1$port/" /etc/ssh/sshd_config
# Restart SSH service
sudo systemctl restart sshd
# Check if SSH service is running
if systemctl is-active --quiet sshd; then
echo -e "SSH port has been changed to $port.\nCheck the firewall to make sure port $port is open.\nKey-based authentication has been enabled while password authentication has been disabled.\nDon't forget to save the private key file."
else
# SSH service failed to start, restore original configuration and display error message
echo "Error: SSH service failed to start. Reverting to original configuration..."
sudo cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
sudo systemctl restart sshd
echo "SSH service has been restored to the original configuration."
exit 1
fi
# Remove backup of SSH configuration(Optional)
# sudo rm /etc/ssh/sshd_config.bak
主要功能:自动生成密钥对,更改ssh端口为随机端口,禁用密码登录,并开启密钥登陆。
脚本执行的第一步会备份原ssh配置,如果后续执行报错,会把原ssh配置文件恢复。