Is a conditional response possible with netcat

2019-09-14 01:06发布

问题:

I want to run netcat (netcat-openbsd 1.105-7ubuntu1) and simulate a chat sequence. I want the netcat response automatically.

Example of what I want.

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()

I copied the code of this question (in the asnwer by @wooghie): run a command conditionally with netcat and grep ...but the message wasn't sent to the client. Netcat was on listen mode.

#!/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

回答1:

I think you want expect(1). Something along the lines of:

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

Note that expect is really Tcl, which is very powerful in its own right.
Not tested. YMMV.



标签: bash netcat