esllin esllin - 5 months ago 12
Linux Question

Expect script on linux

I would like to make a expect script which can answer the question by using srand functuon.

For example,
I will use netcat to connect to the server,
and I will get a question from server like "please enter 0 or 1";
then I hope my script can answer the question automatically by using the code like above.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

void main(){
int num;
srand(time(NULL));
num=(rand()%2);
printf("%d\n",num);}


If you can provide me some sample, it will be very helpful.
Thank you very much.

Answer

You want to launch netcat, recognize that text, then return a random value in (0,1), yes?

#!/usr/bin/env expect
expr {srand([clock seconds])}    ;# initialize RNG
spawn netcat 127.0.0.1
expect "please enter 0 or 1"
send "[expr {int(rand() * 2)}]\r"
expect eof

See documentation: http://tcl.tk/man/tcl8.6/TclCmd/expr.htm and http://tcl.tk/man/tcl8.6/TclCmd/mathfunc.htm

Tcl's expr command gets some flak for being a standalone mini-language inside Tcl. The syntax can be ... cleaned up somewhat.

#!/usr/bin/env expect
namespace import ::tcl::mathfunc::*
namespace import ::tcl::mathop::\*
srand [clock seconds]    ;# initialize RNG
spawn netcat 127.0.0.1
expect "please enter 0 or 1"
send "[int [* 2 [rand]]]\r"
expect eof