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

该文章介绍了一个脚本,用于生成SSH密钥、复制到远程服务器、配置SSH并创建别名,以便在Linux终端快速登录。
摘要由CSDN通过智能技术生成

脚本地址:

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系统上运行脚本,记得在目标服务器设置权限

chmod 600 authorized_keys
#!/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值