使用Bash进行Netcat TCP编程 [英] Netcat TCP Programming with Bash

查看:132
本文介绍了使用Bash进行Netcat TCP编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用严格的bash脚本进行一些基本的TCP客户端通信.我可以使用netcat,因此到目前为止,我已经编写了以下循环:

I'm attempting to do some basic TCP client communication by using strictly bash scripting. I have netcat at my disposal and so I've written this loop so far:

nc 10.0.0.104 4646 | while read line
do
   if [ "$line" == '{"cmd": 1}' ]
   then
      # Send text back to the TCP server
      echo '{"error": 0}'
   fi
done

该脚本可以成功连接到我正在使用的服务器应用程序,但是我很难确定如何将文本发送回netcat进程.

The script can successfully connect to the server application I'm using but I'm having difficulties figuring out how to send text back to the netcat process.

推荐答案

在Bash≥4的情况下,您可以使用coproc:

With Bash≥4 you can use coproc:

#!/bin/bash

coproc nc { nc 10.0.0.104 4646; }

while [[ $nc_PID ]] && IFS= read -r -u${nc[0]} line; do
    case $line in
        ('{"cmd": 1}')
            printf >&${nc[1]} '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done

这避免了使用临时fifos.没有coproc,我想剩下的唯一选择就是显式使用fifos.这是一个示例:

This avoids using temporary fifos. Without coproc, I guess the only option left is to use fifos explicitly. Here's an example:

#!/bin/bash

mkfifo fifo_in

while IFS= read -r line; do
    case $line in
        ('{"cmd": 1}')
            printf '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done < <(nc 10.0.0.104 4646 < fifo_in) > fifo_in

为此,您必须管理fifo的创建和删除:您需要使用mktemp创建一个临时目录,在其中创建fifo,然后在脚本中trap以便退出一切都被清理了.

For this, you'll have to manage the creation and deletion of the fifo: you'll need to create a temporary directory with mktemp, in there create the fifo, then trap your script so that on exit everything is cleaned.

如果您的Bash已通过网络重定向支持进行编译,则可以完全摆脱nc以及fifos和协同处理:

If your Bash has been compiled with net redirections support, you can get rid of nc and of the fifos and coprocesses altogether:

#!/bin/bash

# open TCP connection, available on file descriptor 3
exec 3<> /dev/tcp/10.0.0.104/4646 || exit

while IFS= read -r -u3 line; do
    case $line in
        ('{"cmd": 1}')
            printf >&3 '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done

这很可能是最甜蜜的解决方案!

This is very likely the sweetest solution!

这篇关于使用Bash进行Netcat TCP编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆