0

I am connecting to a telnet listener. Telnet server sends some data for every second. I want to read the messages while X seconds and write it into a file (we'll take 6 seconds for the example).

Note: The IP address has been changed to 'IP' for the example. Same for 'Port'.

I already tried some things:

#!/bin/bash
#myScript.sh

telnet IP Port >> myFile.txt
sleep 6
pkill myScript.sh

This solution write in my file but my script never ends.

Here my 2nd proposition:

#!/bin/bash
#myScript.sh

timeout 6 telnet IP Port >> myFile.txt

Here, it's another issue, timeout is respected, the script ends after 6 seconds but in 'myFile.txt', I have

Trying IP...
Connected to IP.
Escape character is '^]'

How can I make this script right?

Note: I must use Telnet.

Romain
  • 5
  • 7

1 Answers1

0
  1. In your first solution you could try try:

    telnet IP Port 2>&1 | tee myFile.txt &
    sleep 6
    exit
    

This will send the telnet command to a background process and then exit after 6 seconds.

  1. In your second solution you could try:

    timeout 6 telnet IP Port 2>&1 | tee myFile.txt
    

This sends stderr and stdoutt to myFile.txt

https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html

  1. Or, as others have suggested, use netcat:

    timeout 6 nc -vz IP Port 2>&1 | tee myFile.txt
    

http://netcat.sourceforge.net/

Paul Dawson
  • 1,332
  • 14
  • 27
  • It's works in the console but in my script it's the same issue, only the 3 lignes are printed in the file. I tried netcat and it's works – Romain Jul 05 '19 at 10:04
  • The first solution doesn't work but the second is better: the file contains the data but after 6 seconds, the script restarts again and again, it's strange. Netcat works for me, thanks. – Romain Jul 05 '19 at 11:51