am1
am1

Reputation: 347

linux - telnet - script with expect

I was writing an expect-script which communicate with a server via telnet, but right now i need to evaluate the reply from server.

Usage:

./edit.expect

EXPECT script:

#!/usr/bin/expect<br>
spawn telnet ip port
expect "HUH?"
send "login testuser pass\r"
expect "good"
send "select 1\r"
expect "good"
send "me\r"
expect "nick=testuser id=ID group=testgroup login=testuser"
send "edit id=ID group=3\r"
expect "good"
send "quit\r"

If i send the command "me" i get a reply from the server which i need to evaluate. The reply from server looks like this example... "nick=NICK id=ID group=GROUP login=LOGIN".

How do i extract the id of the reply and use it in a send-command?

I hope you could help me with that. Thanks a lot!

Upvotes: 1

Views: 1188

Answers (2)

evil otto
evil otto

Reputation: 10582

expect lets you match the incoming strings with regular expressions and get the submatches in the expect_out() array. In your example, you could use

send "me\r"
expect -re {nick=([^ ]*) id=([^ ]*) group=([^ ]*) login=([^ ]*)}
set nick $expect_out(1,string)
set id $expect_out(2,string)
set group $expect_out(3,string)
set login $expect_out(4,string)
puts "GOT nick: $nick  id: $id  group: $group  login: $login"
send "edit id=$id group=3\r"
etc...

EDIT: string must be in {} to avoid command expansion

Upvotes: 1

Dinesh
Dinesh

Reputation: 16428

You can try this way too.

set user_id {}
expect -re {nick=(.*)\s+id=(.*)\s+group=(.*)\s+login=(.*)\n} {
        #Each submatch will be saved in the the expect_out buffer with the index of 'n,string' for the 'n'th submatch string
        puts "You have entered : $expect_out(0,string)"; #expect_out(0,string) will have the whole expect match string including the newline
        puts "Nick : $expect_out(1,string)"
        puts "ID : $expect_out(2,string)"
        puts "Group : $expect_out(3,string)"
        puts "Login : $expect_out(4,string)"
        set user_id $expect_out(2,string)
}

send "This is $user_id, reporting Sir! ;)"
#Your further 'expect' statements goes below.

You can customize the regexp as per your wish and note the use of braces {} with -re flag in the expect command.

If you are using braces, Tcl won't do any variable substitution and if you need to use variable in the expect then you should use double quotes and correspondingly you need to escape the backslashes and wildcard operators.

Upvotes: 2

Related Questions