如何将给定的文本拆分为 bash 中的 3 个变量并发送到端口的主机?
How to split given text into 3 variables in bash and send to host at port?
我想编写一个命令来侦听某个端口(比如端口 22222),接收单行文本,并将该行按空格拆分为端口、主机和按空格的文本。文本中也可以有空格。因此,例如,1234 localhost blah de blah 将被拆分为端口 1234、主机 localhost 和文本 blah de blah。如果端口为 0,则程序退出。否则程序将文本的值发送到端口的主机并循环回监听。
所以我在终端里有:
nc -k -l localhost 22222|some code goes here I think
和
echo 2016 localhost blah blah|nc localhost 22222
将导致 blah blah 被发送到 2016 端口的本地主机
echo 0 localhost blah blah|nc localhost 22222
会导致程序退出
我的问题是 "some code goes here I think" 部分究竟包含哪些内容?
由于您将 netcat (nc) 的输出通过管道传输到 "some code goes here I think","some code goes here I think" 需要是一个程序或脚本,它可以读取标准输入并使用该数据执行您想要的操作。
在命令行上使用管道并不是获取 netcat 输出并对其进行处理的唯一方法。既然你提到你正在使用 bash,那么最简单的事情可能就是在 nc 上获取输出,然后将其存储在一个变量中,然后你可以使用另一个程序,如 cut 或 awk 来拆分字符串:
raw=`nc -k -l localhost 22222`
part1=`echo $raw | cut -f 1`
part2=`echo $raw | cut -f 2`
part3=`echo $raw | cut -f 3-`
这应该让你得到你想要存储在 bash 环境变量中的部分,你可以稍后做你想做的事(例如,如果 $part1=0 就退出)。
请注意,在我的示例中这些是反引号,而不是引号。 bash 中的反引号将其中命令的结果作为字符串 return。
收到后nc
会将数据回显到标准输出,因此您可以按如下方式处理它:
nc -k -l localhost 22222 | while read line
do
# "$line" contains the received text, do whatever you need with it
...
done
我想编写一个命令来侦听某个端口(比如端口 22222),接收单行文本,并将该行按空格拆分为端口、主机和按空格的文本。文本中也可以有空格。因此,例如,1234 localhost blah de blah 将被拆分为端口 1234、主机 localhost 和文本 blah de blah。如果端口为 0,则程序退出。否则程序将文本的值发送到端口的主机并循环回监听。
所以我在终端里有:
nc -k -l localhost 22222|some code goes here I think
和
echo 2016 localhost blah blah|nc localhost 22222
将导致 blah blah 被发送到 2016 端口的本地主机
echo 0 localhost blah blah|nc localhost 22222
会导致程序退出
我的问题是 "some code goes here I think" 部分究竟包含哪些内容?
由于您将 netcat (nc) 的输出通过管道传输到 "some code goes here I think","some code goes here I think" 需要是一个程序或脚本,它可以读取标准输入并使用该数据执行您想要的操作。 在命令行上使用管道并不是获取 netcat 输出并对其进行处理的唯一方法。既然你提到你正在使用 bash,那么最简单的事情可能就是在 nc 上获取输出,然后将其存储在一个变量中,然后你可以使用另一个程序,如 cut 或 awk 来拆分字符串:
raw=`nc -k -l localhost 22222`
part1=`echo $raw | cut -f 1`
part2=`echo $raw | cut -f 2`
part3=`echo $raw | cut -f 3-`
这应该让你得到你想要存储在 bash 环境变量中的部分,你可以稍后做你想做的事(例如,如果 $part1=0 就退出)。 请注意,在我的示例中这些是反引号,而不是引号。 bash 中的反引号将其中命令的结果作为字符串 return。
收到后nc
会将数据回显到标准输出,因此您可以按如下方式处理它:
nc -k -l localhost 22222 | while read line
do
# "$line" contains the received text, do whatever you need with it
...
done