TorqueWrench/ssh_tunnel_service.sh

77 lines
1.7 KiB
Bash
Raw 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
# 创建systemd服务文件用于开机自启
REMOTE_HOST="123.56.98.4"
REMOTE_USER="root"
TUNNEL_PORT=2222
# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AUTO_SCRIPT="${SCRIPT_DIR}/ssh_tunnel_auto.sh"
echo "=== 创建SSH隧道systemd服务 ==="
# 检查是否以root运行
if [ "$EUID" -ne 0 ]; then
echo "请使用sudo运行此脚本"
exit 1
fi
# 创建服务文件
SERVICE_FILE="/etc/systemd/system/ssh-tunnel.service"
cat > ${SERVICE_FILE} << EOF
[Unit]
Description=SSH Reverse Tunnel to ${REMOTE_HOST}
After=network.target ssh.service
Wants=network-online.target
[Service]
Type=simple
User=root
ExecStart=/bin/bash ${AUTO_SCRIPT}
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
EOF
echo "✓ 服务文件已创建: ${SERVICE_FILE}"
# 重新加载systemd
systemctl daemon-reload
echo "✓ systemd配置已重新加载"
# 启用服务
systemctl enable ssh-tunnel.service
echo "✓ 服务已设置为开机自启"
# 启动服务
read -p "是否立即启动服务?(y/n): " start_now
if [ "$start_now" = "y" ] || [ "$start_now" = "Y" ]; then
systemctl start ssh-tunnel.service
echo "✓ 服务已启动"
echo ""
echo "查看服务状态: systemctl status ssh-tunnel"
echo "查看服务日志: journalctl -u ssh-tunnel -f"
fi
echo ""
echo "=== 服务配置完成 ==="
echo ""
echo "常用命令:"
echo " 启动服务: sudo systemctl start ssh-tunnel"
echo " 停止服务: sudo systemctl stop ssh-tunnel"
echo " 查看状态: sudo systemctl status ssh-tunnel"
echo " 查看日志: sudo journalctl -u ssh-tunnel -f"
echo " 禁用自启: sudo systemctl disable ssh-tunnel"