TorqueWrench/ssh_tunnel_setup.sh

110 lines
3.2 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/bin/bash
# SSH反向隧道设置脚本
echo "=== SSH反向隧道设置脚本 ==="
# 1. 检查SSH客户端是否安装
echo "1. 检查SSH客户端..."
if command -v ssh &> /dev/null; then
echo "✓ SSH客户端已安装: $(which ssh)"
ssh -V
else
echo "✗ SSH客户端未安装开始安装..."
# 检测Linux发行版
if [ -f /etc/redhat-release ]; then
# CentOS/RHEL
echo "检测到 CentOS/RHEL 系统"
sudo yum install -y openssh-clients openssh-server
elif [ -f /etc/debian_version ]; then
# Debian/Ubuntu
echo "检测到 Debian/Ubuntu 系统"
sudo apt-get update
sudo apt-get install -y openssh-client openssh-server
elif [ -f /etc/arch-release ]; then
# Arch Linux
echo "检测到 Arch Linux 系统"
sudo pacman -S --noconfirm openssh
else
echo "无法自动检测系统类型,请手动安装 openssh-client"
exit 1
fi
# 验证安装
if command -v ssh &> /dev/null; then
echo "✓ SSH客户端安装成功"
ssh -V
else
echo "✗ SSH客户端安装失败请手动安装"
exit 1
fi
fi
echo ""
echo "2. 检查SSH服务是否运行..."
if systemctl is-active --quiet sshd || systemctl is-active --quiet ssh; then
echo "✓ SSH服务正在运行"
else
echo "⚠ SSH服务未运行启动SSH服务..."
sudo systemctl start sshd 2>/dev/null || sudo systemctl start ssh
sudo systemctl enable sshd 2>/dev/null || sudo systemctl enable ssh
fi
echo ""
echo "3. 生成SSH密钥如果不存在..."
if [ ! -f ~/.ssh/id_rsa ]; then
echo "生成SSH密钥..."
ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ""
echo "✓ SSH密钥已生成"
else
echo "✓ SSH密钥已存在"
fi
echo ""
echo "4. 配置SSH密钥免密登录可选..."
read -p "是否配置免密登录到阿里云服务器?(y/n): " setup_key
if [ "$setup_key" = "y" ] || [ "$setup_key" = "Y" ]; then
read -p "请输入阿里云服务器IP: " server_ip
read -p "请输入阿里云服务器用户名默认root: " server_user
server_user=${server_user:-root}
echo "复制SSH公钥到阿里云服务器..."
ssh-copy-id -p 22 ${server_user}@${server_ip}
if [ $? -eq 0 ]; then
echo "✓ 免密登录配置成功"
else
echo "⚠ 免密登录配置失败,请手动配置或使用密码登录"
fi
fi
echo ""
echo "5. 测试SSH连接..."
read -p "请输入阿里云服务器IP用于测试连接: " test_ip
read -p "请输入用户名默认root: " test_user
test_user=${test_user:-root}
echo "测试连接到 ${test_user}@${test_ip}..."
ssh -o ConnectTimeout=5 -p 22 ${test_user}@${test_ip} "echo '连接成功!'"
if [ $? -eq 0 ]; then
echo "✓ SSH连接测试成功"
else
echo "✗ SSH连接测试失败请检查"
echo " - 网络连接是否正常"
echo " - 阿里云服务器防火墙是否开放22端口"
echo " - 用户名和密码是否正确"
fi
echo ""
echo "=== 设置完成 ==="
echo ""
echo "使用方法:"
echo " 手动连接: ssh -fN -R 2222:localhost:22 root@123.56.98.4 -p 22"
echo ""
echo " 或者使用自动重连脚本(见下方)"