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?
1 Answer
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
-
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
orsocat
so I'm unable to test– bendlAug 30, 2017 at 13:22 -
2No worries. I updated my answer with a simple version using
bash
that might work for you.– meuhAug 30, 2017 at 18:09