#!/bin/bash
# 添加 SSH 公钥到 authorized_keys(如果不存在)
add_ssh_key_if_not_exists() {
local ssh_key="$1"
local key_file="$HOME/.ssh/authorized_keys"
# 检查是否已存在公钥
if grep -qxF "$ssh_key" "$key_file"; then
echo "SSH public key already exists."
else
echo "$ssh_key" >> "$key_file"
echo "SSH public key added."
fi
}
# 检查 .ssh 目录和 authorized_keys 文件
setup_ssh_directory() {
local ssh_dir="$HOME/.ssh"
local key_file="$ssh_dir/authorized_keys"
if [ ! -d "$ssh_dir" ]; then
echo "Creating .ssh directory..."
mkdir -p "$ssh_dir"
chmod 0700 "$ssh_dir"
fi
if [ ! -e "$key_file" ]; then
echo "Creating authorized_keys file..."
touch "$key_file"
chmod 0600 "$key_file"
fi
}
# 注释掉不符合密钥格式的行
clean_authorized_keys() {
local key_file="$HOME/.ssh/authorized_keys"
local backup_file="$HOME/.ssh/authorized_keys.bak"
# 备份 authorized_keys 文件
cp "$key_file" "$backup_file"
# 过滤有效的密钥格式
awk '{
if ($1 ~ /^(#|ssh-(rsa|dsa|ecdsa|ed25519))/) {
print $0
} else {
print "#" $0 " # Invalid Key Format"
}
}' "$backup_file" > "$key_file"
echo "Invalid SSH keys have been commented out."
}
# 修改 sshd_config 配置
configure_sshd() {
local sshd_config="/etc/ssh/sshd_config"
# 检查是否有权限编辑配置文件
if [ ! -w "$sshd_config" ]; then
echo "Error: No permission to edit $sshd_config. Please run as root."
exit 1
fi
# 确保启用 PubkeyAuthentication
if ! grep -qE "^PubkeyAuthentication yes" "$sshd_config"; then
sed -i '/^#*PubkeyAuthentication /d' "$sshd_config"
echo "PubkeyAuthentication yes" >> "$sshd_config"
echo "PubkeyAuthentication enabled."
fi
# 禁用 PasswordAuthentication
if grep -qE "^PasswordAuthentication yes" "$sshd_config"; then
sed -i 's/^PasswordAuthentication yes/PasswordAuthentication no/' "$sshd_config"
echo "PasswordAuthentication disabled."
elif grep -qE "^#PasswordAuthentication yes" "$sshd_config"; then
sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication no/' "$sshd_config"
echo "PasswordAuthentication disabled."
else
echo "PasswordAuthentication already disabled."
fi
# 重启 SSH 服务
if command -v systemctl > /dev/null; then
# Ubuntu 及其他使用 systemd 的系统
if systemctl is-active --quiet ssh; then
systemctl restart ssh && echo "SSH service restarted successfully." || echo "Failed to restart SSH service."
else
echo "SSH service is not active."
fi
elif command -v service > /dev/null; then
# 某些旧版的 Ubuntu 或其他使用 service 的系统
service ssh restart && echo "SSH service restarted successfully." || echo "Failed to restart SSH service."
else
echo "Error: Unable to restart SSH service. Please restart it manually."
fi
}
# 主函数
main() {
setup_ssh_directory
clean_authorized_keys
SSH_KEYS=(
"ssh-rsa Openssh-local"
"ssh-rsa xxx mac"
"ssh-ed25519 xxx"
"ssh-rsa deploy"
)
for key in "${SSH_KEYS[@]}"; do
add_ssh_key_if_not_exists "$key"
done
configure_sshd
}
main
基础使用:替换 SSH_KEYS 每行一个
最佳使用:shell保存到github或者自己服务器,买新服务器以后 直接 curl xxx | bash
我稍微加多了一个判断
给已经注释的字段不处理判断是否为错误格式,因为有些厂商安装系统的时候带的ssh会加一句注释,我跑脚本发现它给那句注释也加了 # Invalid Key Format
我是直接修改DD腳本加入公鑰,D好就有公鑰了,而且還禁止了密碼登入
好用,没法加腿。。
好东西
不错
写得好