通过脚本secure_ssh.sh
#!/bin/bash
# 严格执行出错即停,确保任何步骤失败都会提前中止
set -euo pipefail
trap 'echo "[ERROR] 脚本执行失败,请检查上方日志" >&2' ERR
SSH_CONFIG="/etc/ssh/sshd_config"
SSH_SERVICE="ssh"
SSH_DIR="/root/.ssh"
AUTHORIZED_KEYS="${SSH_DIR}/authorized_keys"
log_info() {
echo "[INFO] $1"
}
log_error() {
echo "[ERROR] $1" >&2
}
require_root() {
if [[ "${EUID}" -ne 0 ]]; then
log_error "此脚本必须以 root 身份运行"
exit 1
fi
}
prompt_public_key() {
local input
read -r -p "请输入要写入 root authorized_keys 的公钥(回车使用当前 PUBLIC_KEY):" input
if [[ -n "${input}" ]]; then
PUBLIC_KEY="${input}"
fi
if [[ -z "${PUBLIC_KEY:-}" ]]; then
log_error "公钥内容不能为空"
exit 1
fi
}
ensure_ssh_config_exists() {
if [[ ! -f "${SSH_CONFIG}" ]]; then
log_error "未找到 SSH 配置文件 ${SSH_CONFIG}"
exit 1
fi
}
ensure_service_active() {
log_info "检查 SSH 服务状态"
if command -v systemctl >/dev/null 2>&1; then
if ! systemctl is-active --quiet "${SSH_SERVICE}"; then
log_info "SSH 服务未运行,正在启动"
systemctl start "${SSH_SERVICE}"
fi
else
if ! service "${SSH_SERVICE}" status >/dev/null 2>&1; then
log_info "SSH 服务未运行,正在启动"
service "${SSH_SERVICE}" start
fi
fi
}
apply_config_value() {
local key="$1"
local value="$2"
if grep -Eq "^[#[:space:]]*${key}\\b" "${SSH_CONFIG}"; then
sed -i "s|^[#[:space:]]*${key}\\b.*|${key} ${value}|" "${SSH_CONFIG}"
else
printf '%s %s\n' "${key}" "${value}" >> "${SSH_CONFIG}"
fi
}
configure_ssh_port_and_auth() {
log_info "设置 SSH 端口为 2222 并禁用密码登录"
apply_config_value "Port" "2222"
apply_config_value "PasswordAuthentication" "no"
apply_config_value "PermitRootLogin" "prohibit-password"
}
configure_firewall() {
log_info "检测防火墙并开放 2222/tcp"
if command -v firewall-cmd >/dev/null 2>&1; then
if firewall-cmd --state >/dev/null 2>&1; then
if ! firewall-cmd --permanent --query-port=2222/tcp >/dev/null 2>&1; then
firewall-cmd --permanent --add-port=2222/tcp
fi
firewall-cmd --reload
return
fi
fi
if command -v ufw >/dev/null 2>&1; then
if ufw status | grep -qi "Status: active"; then
ufw allow 2222/tcp >/dev/null 2>&1 || log_error "UFW 开放 2222 端口失败"
return
fi
fi
log_info "未检测到需要配置的受支持防火墙"
}
configure_root_authorized_key() {
log_info "配置 root 公钥登录"
mkdir -p "${SSH_DIR}"
chmod 700 "${SSH_DIR}"
printf '%s\n' "${PUBLIC_KEY}" > "${AUTHORIZED_KEYS}"
chmod 600 "${AUTHORIZED_KEYS}"
chown root:root "${SSH_DIR}" "${AUTHORIZED_KEYS}"
}
restart_ssh_service() {
log_info "重启 SSH 服务以应用配置"
if command -v systemctl >/dev/null 2>&1; then
systemctl restart "${SSH_SERVICE}"
else
service "${SSH_SERVICE}" restart
fi
}
main() {
require_root
prompt_public_key
ensure_ssh_config_exists
ensure_service_active
configure_ssh_port_and_auth
configure_firewall
configure_root_authorized_key
restart_ssh_service
log_info "SSH 安全加固完成"
}
main "$@"
bash <(curl -sL https://hostaff.com/file/secure_ssh.sh)
目前ssh-agent 不适用于 Putty 或任何其他与 Pageant 兼容的应用程序 可以通过winssh-pageant 解决
打开管理员命令提示符
winget install winssh-pageant
禁用并重新启用 Bitwarden SSH 代理:设置 > 启用 SSH 代理 重启系统

主机推介


