Reputation: 1
I need to pass some commands to terminal throw C program and get it's input after that. As a part of it, I have a line where Expect script must be placed.
FILE *command = popen("script here","r");
Script I need to execute is:
expect -c 'spawn ssh user@host cat /proc/stat
expect {
-re ".*yes/no.*" {
send "yes\r"
exp_continue
}
"password:" {
send -- "password\r"
}
}
interact'
So, I need to escape several characters so script worked as it need to work. I tried different sequences of escaping, but all of them are not right.
And thank you for your attention.
UPD:
Without escaping I get error while compiling ( "syntax error before `*'" , "stray '\' in program" and others). I think that problem caused by new lines, but script don't work if I simply write it in one line. I tried to use \n , but this did not helped me.
So, I cannot simply copy and paste script to C file, it need some processing
Upvotes: 0
Views: 671
Reputation: 106076
If you're hardcoding the "script" in your C program, you need to follow the C rules: that means escaping the embedded double-quotes and backslashes...
const char script[] =
"expect -c 'spawn ssh user@host cat /proc/stat\n"
"expect { -re \".*yes/no.*\" { send \"yes\\r\" exp_continue }\n"
" \"password:\" { send -- \"password\\r\" }\n"
" }\n"
"interact'\n"
Notice I've also terminated the lines with the C newline escape code '\n'.
Upvotes: 2
Reputation: 104040
First things first, C's stringification can help you make multiline-strings easier on the eyes:
char *script = "expect -c 'spawn ssh user@host cat /proc/stat\n\n"
"expect {\n"
"-re \".*yes/no.*\"\n"
"send \"yes\\r\"\n"
...
The compiler will happily smash all those strings together for you.
Note of course that the \n
are turned into newline characters in the string at compile time, while \\r
is turned into \r
in the string at compile time, which expect is hopefully turning into a carriage return at run time.
Second thing, are you sure embedding an expect script into an executable program is the right approach? Perhaps the host you are logging into will change along the way; replacing the script is much easier if it is broken out separate from the executable. (I can't tell you how many hundreds of pppd chat scripts I have written in my life, I'm just glad it didn't require a recompile of pppd to make them work!)
Upvotes: 3