Save an specific part of a expect_out in a variable

I have a expect file like this

#!/opt/tools/unsupported/expect-5.39/bin/expect

spawn ssh -l user ip
expect_after eof {exit 0}
set timeout 10
log_file /report.txt

expect "Password:" { send "pasword\r" }
expect "$ " { send "date\r" }

expect "$ " { send "readlink /somelink\r" }

set CCM_BUILD $expect_out(buffer)

send_log "CCM: $CCM_BUILD"

expect "$ " { send "date\r" }
expect "$ " { send "exit\r" }
~

The result of the readlink will be a number like 447. that's what I want in my log file. but what I'm getting is:

Password:
Last login: Tue Feb 28 09:49:42 2017 from gbplr6gn01.genband.com^M
^[[?1034h-bash-4.1$ date
Tue Feb 28 09:50:42 CST 2017
-bash-4.1$ CCM: readlink /localdisk2/jenkins/jobs/CCM/jobs/Deploy_CCM_build/builds/lastSuccessfulBuild
447
-bash-4.1$ date
Tue Feb 28 09:50:42 CST 2017
-bash-4.1$

how can I get just CCM: 447?

echo "CCM: $(readlink /localdisk2/jenkins/jobs/CCM/jobs/Deploy_CCM_build/builds/lastSuccessfulBuild)"

echo doesn't work with expect

I guess I don't understand something very basic what you're after..

From the EXPECT manual: "any matching and previously unmatched output is saved in the variable expect_out(buffer)"

You could use regexp to do a substring match of that, or just use expect again
My expect is rusty, try something like this:

expect "$ " { send "readlink /somelink\r" }
expect -re {\n([0-9]*)}

set CCM_BUILD $expect_out(1,string)

nope didn't work :frowning: gave me the same output

Try this:

#!/opt/tools/unsupported/expect-5.39/bin/expect --

set timeout 10
match_max 256
expect_after eof {exit 0}
log_file -noappend report.txt

puts -nonewline "Fetching link from ip..."
spawn -noecho ssh -l user ip
log_user 0

expect "Password:" { send "pasword\r" }
expect "$ " { send "date\r" }

expect "$ " { send "readlink /somelink\r" }
expect -r "readlink .*\r\n(.*)\r\n" {
    set CCM_BUILD $expect_out(1,string)
}

send_log "CCM: $CCM_BUILD"
puts ""
expect "$ " { send "date\r" }
expect "$ " { send "exit\r" }
1 Like

It works beautifully thanks. Now I will figure out what every part does in your code :stuck_out_tongue: