Search code examples
tcltelnetexpect

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!


Solution

  • 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.