生成公私钥
ssh-keygen -t rsa -b 4096可选
ssh-keygen -t rsa -b 4096 -C "你的邮箱或备注"SFTP链接服务器把/root/.ssh/中的 id_rsa 和 id_rsa.pub 保存一份
~/.ssh/id_rsa # 私钥,绝对不要泄露
~/.ssh/id_rsa.pub # 公钥,可分发给服务器新建脚本
vi sshkey.sh把下面内容复制进去
#!/bin/bash
# 设置预设公钥 ssh-rsa 开头
preset_pubkey=""
if [ -n "$preset_pubkey" ]; then
echo "使用预设公钥..."
pubkey="$preset_pubkey"
else
echo "请输入公钥:"
read pubkey
fi
mkdir -p ~/.ssh
echo "$pubkey" > ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
set_sshd_config() {
local key="$1"
local value="$2"
# 有参数被注释则修改
if grep -qE "^\s*#?\s*$key" /etc/ssh/sshd_config; then
sed -i -E "s|^\s*#?\s*($key).*|\1 $value|" /etc/ssh/sshd_config
else
# 不存在就追加
echo "$key $value" >> /etc/ssh/sshd_config
fi
}
# 设置参数
set_sshd_config UsePAM no
set_sshd_config PubkeyAuthentication yes
set_sshd_config PasswordAuthentication no
set_sshd_config PermitEmptyPasswords no
set_sshd_config KbdInteractiveAuthentication no
set_sshd_config PermitRootLogin prohibit-password
# 锁定文件
chattr +i /etc/ssh/sshd_config
chattr +i ~/.ssh/authorized_keys
# 重启 SSH
systemctl restart sshd
systemctl status sshd
echo "配置修改完成,SSH 服务已重启,文件已锁定。"执行脚本 root 登录 不需要在单独设置权限
bash sshkey.sh代码执行后会把文件锁定,锁定文件即使 root 权限也无法修改,取消锁定执行如下命令
# 解锁ssh
chattr -i /etc/ssh/sshd_config
# 解锁公钥文件
chattr -i ~/.ssh/authorized_keys注:生效后 只能使用证书登录,密码登录无效