Telnet: shell script to issue commands to telnet session.

This is a quick post to show how one can issue commands to telnet session from a shell script or command line with out going into interactive mode. I use this to get stats from our memcache servers or issue a flush_all via telnet from a script/cron.

So without further delay, following command will telnet to local memcached server on port 11211 and issue one of the memcached commands, stats

(sleep .5;echo stats) | telnet localhost 11211
You may have to play with the sleep timer to get it to work for your environment but in our .5 was the sweet spot. Good luck and let me know if you have another shell command. Obviously we can do this from perl, php, python, etc but the beauty of this is that you do not need any other dependencies plus its a very short command.

Since “jsled” commented about nc (thanks jsled), here is the syntax to do the same thing with nc:

echo "stats" | nc localhost 11211

5 thoughts on “Telnet: shell script to issue commands to telnet session.

  1. jsled

    What’s the point of the sleep command?

    You might want to look into netcat (nc) as a telnet alternative; it has a whole section of its manpage about “why not just use telnet to connect to arbitrary ports?”.

    Cheers

  2. Sunny Walia Post author

    It allows telnet session to be opened before sending the command. I had some problems on some of the servers without sleep. In some cases, I even had to jack it up to .8 so it had enough time:

    [[email protected] /]# (echo stats) | telnet localhost 11211
    Trying 127.0.0.1…
    Connected to localhost.
    Escape character is ‘^]’.
    Connection closed by foreign host.
    [[email protected] /]# (sleep .5;echo stats) | telnet localhost 11211
    Trying 127.0.0.1…
    Connected to localhost.
    Escape character is ‘^]’.
    STAT pid 28466
    STAT uptime 23892687
    STAT time 1231444944
    STAT version 1.2.5
    STAT pointer_size 32
    STAT rusage_user 0.120007
    STAT rusage_system 0.064004
    STAT curr_items 0
    STAT total_items 0
    STAT bytes 0
    STAT curr_connections 2
    STAT total_connections 9
    STAT connection_structures 3
    STAT cmd_get 0
    STAT cmd_set 0
    STAT get_hits 0
    STAT get_misses 0
    STAT evictions 0
    STAT bytes_read 35
    STAT bytes_written 1894
    STAT limit_maxbytes 268435456
    STAT threads 1
    END
    Connection closed by foreign host.

    And since you mentioned the nc command, I will update the post with that command as well. Thanks.

  3. Aaron Bish

    # Wait for the reply and then hang up:
    # echo “stats” | nc -w1 localhost 11211
    That produces an error, since the ‘”‘ confuses memcached. The following does work:
    echo stats | nc -w1 localhost 11211

  4. fgarat

    (sleep .2; echo ‘GET cache_object://192.168.108.11:3128/info HTTP/1.0’;echo)|netcat -t localhost 3128

Leave a Reply

Your email address will not be published. Required fields are marked *