在Mac上使用Socat实现端口转发
# 在Mac上使用socat实现端口转发
# 简介
在Mac操作系统中,socat
是一个功能强大的网络工具,它可以用来实现端口转发,类似于Windows中的netsh
端口转发功能。本文将介绍如何在Mac上使用socat
进行端口转发。
# 操作步骤
# 安装socat
首先,你需要安装socat
。在Mac上,可以通过Homebrew来安装:
brew install socat
1
# 进行端口转发
使用socat
进行端口转发的基本命令格式如下:
socat TCP-LISTEN:本地端口,reuseaddr,fork TCP:远程IP:远程端口
1
例如,如果你想要将本地的1521端口转发到远程IP 1.119.199.37
的9521端口,你可以执行:
socat TCP-LISTEN:1521,reuseaddr,fork TCP:1.119.199.37:9521
1
# 后台运行
如果你希望socat
在后台运行,可以使用nohup
命令:
nohup socat TCP-LISTEN:1521,reuseaddr,fork TCP:1.119.199.37:9521 &
1
# 检查端口转发是否成功
你可以通过以下命令来检查端口转发是否成功:
- 查看端口是否在监听:
lsof -i :1521
# 或者
netstat -an | grep 1521
1
2
3
2
3
# 停止转发
如果你需要停止端口转发,可以按照以下步骤操作:
- 首先找到
socat
进程:
ps aux | grep socat
1
- 然后终止进程:
kill <进程ID>
1
# 创建shell脚本方便使用
为了方便管理端口转发,可以创建一个shell脚本:
- 创建脚本文件:
vim ~/oracle-forward.sh
1
- 添加以下内容:
#!/bin/bash
case "$1" in
start)
nohup socat TCP-LISTEN:1521,reuseaddr,fork TCP:1.119.199.37:9521 &
echo "Port forwarding started"
;;
stop)
pkill socat
echo "Port forwarding stopped"
;;
status)
if pgrep socat > /dev/null
then
echo "Port forwarding is running"
netstat -an | grep 1521
else
echo "Port forwarding is not running"
fi
;;
*)
echo "Usage: $0 {start|stop|status}"
exit 1
;;
esac
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
- 添加执行权限:
chmod +x ~/oracle-forward.sh
1
- 使用以下命令来管理端口转发:
- 启动转发:
./oracle-forward.sh start
1
- 查看状态:
./oracle-forward.sh status
1
- 停止转发:
./oracle-forward.sh stop
1
# 数据库连接配置
设置好端口转发后,你的数据库连接配置应该使用本地转发的端口。例如,如果你使用的是Spring框架,可以这样配置:
spring:
datasource:
url: jdbc:oracle:thin:@localhost:1521/your_service_name
username: your_username
password: your_password
1
2
3
4
5
2
3
4
5
这样,你就可以通过本地转发的端口连接到远程数据库了。
编辑 (opens new window)