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.
JavaScript
x
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void main(){
int num;
srand(time(NULL));
num=(rand()%2);
printf("%dn",num);}
If you can provide me some sample, it will be very helpful. Thank you very much.
Advertisement
Answer
You want to launch netcat, recognize that text, then return a random value in (0,1), yes?
JavaScript
#!/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.
JavaScript
#!/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