服务器配置密钥登录并禁止密码登录一键脚本

如果你有很多服务器,那么配置公钥是一件很枯燥的事情,于是,一键配置脚本应运而生。

❗ 请注意,PUB_KEY 可以手动填写或者从你的 github 中下载,亦或者是从某个网站下载。

❗ 请注意,务必先思考是要 增加 还是 覆盖 公钥,然后择一运行,否则你的公钥可能丢失。

下方代码可以直接粘贴在 Linux Bash 中运行,但是,请将公钥链接替换为自己的 Github 地址或者其他【可访问】的 URL!!

#!/usr/bin/env bash

PUB_KEY=$(curl -fsSL https://github.com/someone.keys)
if [ ! -f "${HOME}/.ssh/authorized_keys" ]; then
    mkdir -p ${HOME}/.ssh/
    touch ${HOME}/.ssh/authorized_keys
fi

# 追加
echo -e "\n${PUB_KEY}\n" >> ${HOME}/.ssh/authorized_keys
# 覆盖
echo -e "${PUB_KEY}\n" > ${HOME}/.ssh/authorized_keys

chmod 700 ${HOME}/.ssh/
chmod 600 ${HOME}/.ssh/authorized_keys

sudo sed -i "s@.*\(PasswordAuthentication \).*@no@" /etc/ssh/sshd_config
sudo sed -i 's/#\?PubkeyAuthentication \(yes\|no\)/PubkeyAuthentication yes/' /etc/ssh/sshd_config
sudo sed -i 's/^#AuthorizedKeysFile/AuthorizedKeysFile/' /etc/ssh/sshd_config

sudo systemctl restart sshd

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.