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.
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.
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
Or, as others have suggested, use netcat:
timeout 6 nc -vz IP Port 2>&1 | tee myFile.txt