返回

一键脚本设置SSH密钥登录服务器

   
摘要GPT
摘要小助理暂时失联跑路啦……😜

脚本地址:

curl -sS -O https://raw.githubusercontent.com/woniu336/open_shell/main/ssh-v.sh && chmod +x ssh-v.sh && ./ssh-v.sh

脚本如下,请在电脑上安装好 Git 将代码保存为xxx.sh,双击运行:

一路回车,输入yes,输入你的端口号,ip,密码,搞定

最后自定义别名(随意什么名称)

登录方式,打开终端,输入:ssh [别名] 登录

例如 ssh kk 就登录了

如果要在Linux系统上运行脚本,记得在目标服务器设置权限

SSH设置不生效解决办法

如果遇到设置ssh成功后仍然需要密码登录的情况解决办法

一、查看系统安全日志,定位问题

sudo cat /var/log/auth.log

或者

sudo cat /var/log/secure

找到下面的信息

Authentication refused: bad ownership or modes...

(网上的图片)

(我的)

for directory 或者 for file 后面跟着的就是指出什么文件或文件夹

我的这条日志说明 SSH 服务器拒绝了基于密钥的认证,原因是 /root/.ssh/authorized_keys 文件的所有权或权限模式设置不正确。(你的原因可能和我不一样,但是方法是一样的)

authorized_keys 文件存储了允许使用 SSH 密钥登录的公钥。如果这个文件的权限设置不当,SSH 服务器将拒绝基于密钥的认证,从而要求输入密码进行登录认证。

解决方法是检查 /root/.ssh/authorized_keys 文件的所有权和权限,确保它只对 root 用户可读写:

所有权应为 root:root

chown root:root /root/.ssh/authorized_keys

权限应为 600 (所有者可读写)

chmod 600 /root/.ssh/authorized_keys

如果 /root/.ssh 目录存在,也要检查它的权限为 700 (所有者可读写执行)

chmod 700 /root/.ssh

做完这些更改后,重新尝试 SSH 密钥登录,应该就不需要输入密码了。如果仍有问题,可以检查 SSH 服务器和客户端的其他配置。

脚本:

#!/bin/bash

# 创建SSH目录
mkdir -p ~/.ssh
cd ~/.ssh

# 生成SSH密钥
# 生成SSH密钥
echo -e "\e[32m开始愉快之旅吧\e[0m"
echo -e "\e[32m系统将提示您指定密钥对名称: \e[33m一路回车\e[32m 请按Enter继续\e[0m"
echo
ssh-keygen -t ed25519 -C "注释随意"

# 复制公钥到远程服务器
read -p "请输入SSH端口号(默认22):" ssh_port
ssh_port=${ssh_port:-22}
read -p "请输入服务器IP地址:" server_ip
read -p "请输入用户名(默认root):" ssh_user

ssh-copy-id -i ~/.ssh/id_ed25519.pub -p $ssh_port $ssh_user@$server_ip

# 修改远程服务器配置
ssh -p $ssh_port $ssh_user@$server_ip << 'EOF'
if grep -q "^#*PubkeyAuthentication\s*no" /etc/ssh/sshd_config; then
    sudo sed -i 's/^#*PubkeyAuthentication\s*no/ PubkeyAuthentication yes/' /etc/ssh/sshd_config
elif grep -q "^#*PubkeyAuthentication\s*yes" /etc/ssh/sshd_config; then
    sudo sed -i 's/^#*PubkeyAuthentication\s*yes/ PubkeyAuthentication yes/' /etc/ssh/sshd_config
else
    echo "PubkeyAuthentication yes" | sudo tee -a /etc/ssh/sshd_config
fi
sudo service ssh restart
exit
EOF

# 提示用户输入别名和ip
read -p "请输入别名:" alias_name

# 检查~/.ssh/config文件是否存在,如果不存在则创建并添加配置
if [ ! -f ~/.ssh/config ]; then
    touch ~/.ssh/config
fi

# 添加别名和IP到~/.ssh/config文件中
if ! grep -q "Host $alias_name" ~/.ssh/config; then
    echo "Host $alias_name" >> ~/.ssh/config
    echo "    Hostname $server_ip" >> ~/.ssh/config
    echo "    IdentityFile ~/.ssh/id_ed25519" >> ~/.ssh/config
    echo "    User $ssh_user" >> ~/.ssh/config  # 更新User为用户输入的用户名
    echo "    Port $ssh_port" >> ~/.ssh/config  # 添加Port选项
fi

# 使用SSH密钥登录
echo -e "\e[33m输入 ssh $alias_name 愉快登录吧\e[0m"
ssh $alias_name
知识共享许可证 CC BY-NC-SA 4.0
最后更新于 2024-07-17 18:28
使用 Hugo 构建
主题 hugo-magic小洋葱 魔改 由 Jimmy 设计
Written by Human, Not by AI