编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Linux 使用 socat 让云服务器作为跳板机的方法

wxchong 2024-09-16 07:01:45 开源技术 10 ℃ 0 评论

概念

三台机器:

客户端 A ( 192.168.1.11 )

服务器 B ( 192.168.1.88 )

跳板机 C ( 192.168.1.32 )

实现 A 与 B 的双向数据传输,本该这样:

A <---> B

但由于某些原因,可能无法直连服务器,这就需要使用 中转 服务

A <---> C <---> B

相当于机器 C 做 机器 A 和 机器 B 中转桥梁,通常称之为 跳板

使用教程

  1. 安装 socat

通过包管理安装 (推荐)

# Centos
yum install -y socat

# Debian/Ubuntu
apt-get install -y socat

# macOS
brew install socat

通过源码方式安装

wget http://www.dest-unreach.org/socat/download/socat-1.7.4.4.tar.gz
tar zxf socat-1.7.3.2.tar.gz
cd socat-1.7.3.2
./configure
make
make install
  1. 创建 socat 运行的目录,并且进入该目录
mkdir -p /srv/socat
cd /srv/socat
  1. 创建跳板机信息的文件 config.ini
0.0.0.0:9222,192.168.1.88:22

其中,9222 为跳板机的端口,192.168.1.88:22 为目标远程服务器的 IP 和 ssh 端口。

  1. 将跳板机的 ssh 登录公钥上传到远程服务器
ssh-copy-id -p 22 192.168.1.88
  1. 创建执行文件 socat.sh,内容如下
#!/usr/bin/env bash

CURRENT_PATH=$(dirname "$0")

pushd "$CURRENT_PATH" >/dev/null 2>&1 || exit
while read -r LINE; do
  LOCAL_PORT=$(echo "$LINE" | grep -oP '(?<=:)\d+(?=,)')
  LOCAL_HOST=$(echo "$LINE" | cut -d ':' -f 1)
  REMOTE_ADDR=$(echo "$LINE" | cut -d ',' -f 2)
  socat -d -d -lf run.log TCP4-LISTEN:"$LOCAL_PORT",bind="$LOCAL_HOST",reuseaddr,fork TCP4:"$REMOTE_ADDR"
done < <(cat ./config.ini)
popd >/dev/null 2>&1 || exit

添加可执行权限

chmod +x socat.sh
  1. 创建 systemd 运行服务文件 /etc/systemd/system/socat.service
# 一键创建服务文件 
curl -SL https://jihulab.com/jetsung/sh-files/-/raw/main/sh/service.sh | bash -s -- --name 'socat' --exec "/srv/socat/socat.sh" --desc "NAT Server"

注意:

该方式会自动加载到“开机运行”,若不需要开机运行,可执行

systemctl disable socat

/etc/systemd/system/socat.service 内容为(或者自己手动添加该内容):

[Unit]
Description=NAT Server

[Service]
Type=simple
ExecStart="/srv/socat/socat.sh"

[Install]
WantedBy=multi-user.target

若是手动创建的文件,则需要自行重载 systemd 服务

systemctl daemon-reload
  1. 启动与重启
# 启动
systemctl start socat

# 若修改了跳板服务信息 config.ini,则需要重启
systemctl restart socat

# 查看运行状态
systemctl status socat
  1. 连接到跳板机

若跳板机的 IP 为 192.168.1.33config.ini 中的跳板机端口为 9222,则在客户机使用跳板机登录到远程服务器 192.168.1.88:22 的命令为

ssh -p9222 root@192.168.1.33

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表