How to implement a command history on a telnet cli

2019-03-25 08:01发布

问题:

I have a server that accept telnet connections for management. I miss the command history so I want to make my telnet session support it. My questions:

1) Do I have to implement that on the server side, so the server will send the past commands to the client and then the client can re-execute?

2) Is there anyway to implement this functionality in the telnet client (not messing with the server) ?

If answer is 1) then I need to know how to capture and send the up and down arrow keys on my telnet session without having to press enter.

回答1:

This isn't a server issue. Just use rlwrap with your telnet client. It gives you readline with no programming.

$ rlwrap telnet server port

(I actually use nc instead of telnet since it is easier to use and is more robust.)



回答2:

use socat:

socat readline,history=$HOME/.telnet_history TCP:host:23


回答3:

I'm assuming this is a service you have written in Perl, based on your tags.

You can use the Term::ReadLine module from CPAN to do what you want. From the CPAN website, here's a basic example:

use Term::ReadLine;
    my $term = Term::ReadLine->new('My Management Service');
    my $prompt = "Enter your management command: ";
    my $OUT = $term->OUT || \*STDOUT;
    while ( defined ($_ = $term->readline($prompt)) ) {
        my $res = eval($_);
        warn $@ if $@;
        print $OUT $res, "\n" unless $@;
        $term->addhistory($_) if /\S/;
    }