Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27652

Simplest way to script slowly sending data through a socket connection

I need to periodically connect to a server from a Linux client and send some commands, so I wrote this script:

#!/bin/sh
telnet theserver.somewhere.com 9999 <<EOF
command 1
command 2
command 3
EOF

The problem is that I need to wait between commands. This script sends the commands and disconnects too quickly, which the server detects, and drops the commands. It works if I open the connection from the command line and then paste the commands one at a time, and it works from non-local clients, but from local clients the script fails. It would be enough to just pause for a second or so between each command.

I can write a C or Java program that does this, but what is the simplest way? The usual scripting languages (Perl and Python) are available, if you need them.

Upvotes: 0

Views: 3798

Answers (5)

Chris DuPuis
Chris DuPuis

Reputation: 201

This is the kind of problem that Expect was designed to solve.

http://expect.sourceforge.net/

Upvotes: 0

Miles
Miles

Reputation: 32488

Shell commands to echo a line at a time from a file to telnet:

cat commands.txt | 
    ( while read line; do echo $line; sleep 1; done ) |
    telnet theserver.somewhere.com 9999

Upvotes: 3

user173973
user173973

Reputation:

set s [socket $HOST $PORT]
fconfigure $s -buffering line
puts $s $command1
sleep $no_of_sec
puts $s $command2

My TCL is a bit rusty but I think it's the easiest way to go. You can also use some Tk to do wonders. http://www.tcl.tk/man/tcl/tutorial/tcltutorial.html

Upvotes: 1

RoeeK
RoeeK

Reputation: 1162

first, if the server code is in your control then i suggest you fix this problem in the server, cause there is no actual reason why 'closing the connection too fast' would have a problem.

then, i would write a little and simple python script:

#!/bin/python

import socket,time

s=socket.socket(socket.AF_INET)
s.connect(("theserver.somewhere.com",9999))
s.sendall("1")
time.sleep(1)
s.sendall("2")
time.sleep(1)
s.close()

Upvotes: 2

Blue316
Blue316

Reputation: 1

Have you tried to use the Sleep command? I am not sure if this will work as it might try to issue that command on the other server but it is worth a shot just issue something like sleep 2 to pause for acouple seconds.

Upvotes: 0

Related Questions