7

I'm working a lot with netcat recently to test a server, and having use of the up arrow to repeat previous commands would be extremely helpful. Right now however, it only enters ^[[A. Is there any way I can change this behavior?

bendl
  • 171

1 Answers1

10

There are 2 possibilities. The first is to use rlwrap to wrap a readline history library around your netcat program. Another is to use socat which has readline built-in as an option.

For example, if you were doing a telnet with netcat you might just say

rlwrap nc -t remotehost 23

and then each line you enter is kept in file ~/.nc_history and can be navigated with the usual readline keys. Rerunning the same command preserves the existing history.

With socat, there is no telnet option, but for other sorts of connection you can do for example

socat readline,history=$HOME/.socat.hist TCP4:remotehost:port

If you do not have rlwrap you can use socat to run your netcat:

socat readline,history=$HOME/.socat.hist exec:'nc -t remotehost 23'

A third possibility if you have neither of these programs, but do have a bash shell with built-in readline, is to get bash to read the commands from the terminal and send them to the stdin of netcat. The following is a fairly simplistic example of a script to do this, using the same nc command, and saving and restoring the history in file /tmp/myhistory.

#!/bin/bash
# emulate rlwrap nc -t localhost 23
HISTFILE=/tmp/myhistory
history -r              # read old history
while IFS= read -p 'netcat> ' -e    # sets REPLY, -e enables readline
do  history -s "$REPLY" # add to history
    history -w          # save to file
    echo "$REPLY"       # write to netcat
done |
nc -t remotehost 23
meuh
  • 51,383
  • I'm coming back late to say that the only reason I'm not accepting this answer is because my company's firewall is blocking me from installing rlwrap or socat so I'm unable to test – bendl Aug 30 '17 at 13:22
  • 2
    No worries. I updated my answer with a simple version using bash that might work for you. – meuh Aug 30 '17 at 18:09