【问题标题】:Is a conditional response possible with netcat是否可以使用 netcat 进行条件响应
【发布时间】:2017-01-19 13:44:57
【问题描述】:

我想运行 netcat (netcat-openbsd 1.105-7ubuntu1) 并模拟聊天序列。我想要 netcat 自动响应。

我想要的示例。

NETCAT: nc -l 8080

CLIENT: nc localhost 8080

CLIENT: hello

NETCAT: (if statment) 
        if hello
           do hello friend

        if bye
           do bye friend
           send a FIN tcp 

        default
           date()

我复制了这个问题的代码(在@wooghie 的asnwer 中):run a command conditionally with netcat and grep ...但是消息没有发送给客户端。 Netcat 处于监听模式。

#!/bin/bash

netcat -l 8080 | while read line
do
    match=$(echo $line | grep -c 'Hello')
    if [ $match -eq 1 ]; then
        printf "Hello friend\r\n\r\n"
    fi
done

【问题讨论】:

  • 没有。您需要同时提供标准输入 由标准输出提供。因此,使用 netcat -l 比在 perl 或 python 中重新实现整个 netcat -l 要复杂得多/脆弱。
  • @kubanczyk - 你完全可以使用命名管道。 Bash 的 coproc 让它变得更容易:stackoverflow.com/a/36327396/477563
  • 尝试将expect 添加到标签中,@GlennJackman 可能会在这些事情上分享他的巨大智慧......
  • 也许this 会有所帮助

标签: bash netcat


【解决方案1】:

我想你想要expect(1)。大致如下:

#!/usr/bin/env expect
spawn nc localhost 8080
expect {
  hello {
     send "hello dude"
  } bye {
     close
  } -re .* {
     send [date]
  }
}

请注意,expect 是真正的 Tcl,它本身就非常强大。
未测试。 YMMV。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多