socat使用指南:3:5种常见的使用方法

这篇文章继续介绍一下socat常见的5种使用方法。

使用方法1:当作cat来使用

liumiaocn:~ liumiao$ socat - `pwd`/greetings
hello liumiao
liumiaocn:~ liumiao$ 

但是需要注意的是相对路径或者绝对路径写完整,毕竟还是socket方式的实现,直接使用文件名可能会出现下面类似的错误。

liumiaocn:~ liumiao$ socat - greetings 
2020/03/01 09:28:08 socat[26732] E unknown device/address "greetings"
liumiaocn:~ liumiao$

相对路径也可以使用

liumiaocn:~ liumiao$ socat - ./greetings 
hello liumiao
liumiaocn:~ liumiao$

使用方法2: 写文件

通过管道将内容传递给指定名称的文件

liumiaocn:~ liumiao$ echo "hi, liumiao" |socat - ./hellomsg
liumiaocn:~ liumiao$ cat hellomsg 
hi, liumiao
liumiaocn:~ liumiao$

这种方式缺省情况下是append的方式追加内容的,再次执行即可确认

liumiaocn:~ liumiao$ echo "greetings " |socat - ./hellomsg 
liumiaocn:~ liumiao$ cat ./hellomsg 
hi, liumiao
greetings 
liumiaocn:~ liumiao$ 

使用方法3: 指定端口和类型进行监听

比如在8088端口指定TCP方式的监听,客户端连接此端口发送的数据都可以被socat确认到。

步骤1: 使用socat启动监听

执行命令:socat tcp-listen:8088 -

步骤2: 使用nc发送数据

执行命令:nc 127.0.0.1 8088

另启一个终端执行上述命令之后,输入的信息都可以在socat终端看到,实际上是socket通信方式的数据传输。

liumiaocn:~ liumiao$ nc 127.0.0.1 8088
hello, this is greetings from liumiao

而此时在socat监听的终端即可确认到信息的传递

liumiaocn:~ liumiao$ socat tcp-listen:8088 -
hello, this is greetings from liumiao

使用方法4: 活用EXEC当作shell代理

使用者可以使用如下命令即可在目标机器上设立一个shell代理,结合进程隐藏可能更难以被发现,自己使用自己的资源还可以,在别人的机器上获取权限和端口来做这个事情不就太好了。

执行命令:socat TCP-LISTEN:8848 EXEC:/bin/bash

比如在本地机器上进行验证,通过nc进行连接,可以看到shell命令就可以正常执行了,这里我们生成一个文件,然后执行copy命令,然后删掉生成的文件

liumiaocn:~ liumiao$ nc 127.0.0.1 8848
pwd
/Users/liumiao
hostname
liumiaocn
echo "hello, nice to see you..." >create_new_file.txt
cp create_new_file.txt copy_file.txt
rm create_new_file.txt
^C
liumiaocn:~ liumiao$

进行结果确认发现,正常的动作都可以执行

liumiaocn:~ liumiao$ ls create_new_file.txt
ls: create_new_file.txt: No such file or directory
liumiaocn:~ liumiao$ cat copy_file.txt
hello, nice to see you...
liumiaocn:~ liumiao$ 

使用方法5: 活用exec进行回显

在很多demo的示例中,对输入进行回复能够更加清晰地确认到执行的正确性,比如这里使用exec结合cat命令,即可实现输出和输入一样内容的回显功能。

执行命令:socat -v tcp-l:8181 exec:"/bin/cat"

执行上述命令之后通过nc进行连接,然后输入一行消息,回车之后,信息会立即回显

liumiaocn:~ liumiao$ nc 127.0.0.1 8181
hello, this is greetings from liumiao
hello, this is greetings from liumiao

而确认socat的终端信息由于使用了-v参数,也可以看到详细信息

liumiaocn:~ liumiao$ socat -v tcp-l:8181 exec:"/bin/cat"
> 2020/03/01 10:17:41.144841  length=38 from=0 to=37
hello, this is greetings from liumiao
< 2020/03/01 10:17:41.145345  length=38 from=0 to=37
hello, this is greetings from liumiao

总结

socat使用非常方便,这里总结了常见的5种使用方法,但是只是其中非常小的使用方法的一部分,还有关于转发、SSL支持等很多特性都非常好用。

发布了1106 篇原创文章 · 获赞 1311 · 访问量 406万+

猜你喜欢

转载自blog.csdn.net/liumiaocn/article/details/104586980
今日推荐