我想创建一个脚本,该脚本使用来自TCP输出的几个参数,并将某些内容打印回TCP输入。
我正在尝试使用bash解决此问题,我尝试过:
exec 3<>/dev/tcp/url/port;
msg=$(head -2 <&3)
arg1=$( some grep and sed operation on msg) #is a number
arg2=$( some grep and sed operation on msg) #is a string
counter=0
while [ $counter -lt $arg1 ]
do
#here I want to print something to netcat input
echo "$arg2 sometext" >&3;
((counter++))
done
#then print the awnser from the server
cat <&3
但是脚本无法写回netcat输入。 (没有错误,ist在echo "$arg2 sometext" >&3
之后什么也不做)
答案 0 :(得分:1)
如果避免使用/dev/tcp
并使用socat
在将stdin和stdout连接到套接字的情况下运行代码,则可以减少头痛。
myfunc() {
local msg msg1 msg2 arg1 arg2 counter
IFS= read -r msg1 # first line of msg
IFS= read -r msg2 # second line of msg
msg="$msg1"$'\n'"$msg2"
# FYI: There are usually better ways to do string manipulation in bash than grep/sed/etc
arg1=$(do-something-with "$msg" </dev/null)
arg2=$(do-something-with "$msg" </dev/null)
for (( counter=0; counter<arg1; counter++ )); do
echo "$arg2 sometext"
done
cat >&2 # write to stderr, since anything to stdout will go to the remote socket
}
export -f myfunc
socat TCP:"$host":"$port" "SYSTEM:bash -xc myfunc"