Bash – help with expect script, run cat on remote comp and get output of it to the variable

bashcatexpect

I have a bash+expect script which has to connect via ssh to the remote comp, read the file there, find specific line with the "hostname" (like "hostname aaaa1111") and store this hostname into the variable to be used after while. How can i get the value of the "hostname" parameter? I thought that line content will be in $expect_out(buffer) variable (so i can scan it and analyze), but it's not. My script is:

    #!/bin/bash        
    ----bash part----
    /usr/bin/expect << ENDOFEXPECT
    spawn bash -c "ssh root@$IP"  
    expect "password:"
    send "xxxx\r"
    expect ":~#"
    send "cat /etc/rc.d/rc.local |grep hostname \n"
    expect ":~#"
    set line $expect_out(buffer)
    puts "line = $line, expect_out(buffer) = $expect_out(buffer)"
    ...more script...
    ENDOFEXPECT

Here http://en.wikipedia.org/wiki/Expect there is an example:

    # Send the prebuilt command, and then wait for another shell prompt.
    send "$my_command\r"
    expect "%"
    # Capture the results of the command into a variable. This can be displayed, or written to disk.
    set results $expect_out(buffer)

seems that it doesn't work in this case, or what's wrong with the script?

Best Answer

First thing, your heredoc acts like a double quoted string, so the $expect_out variable is being substituted by the shell before expect starts. You need to ensure your heredoc is not being touched by the shell. Therefore, any shell variables need to be fetched in a different way. Here, I'm assuming IP is a shell variable, and I'm passing it through the environment.

export IP
/usr/bin/expect << 'ENDOFEXPECT'
  set prompt ":~#"
  spawn ssh root@$env(IP)  
  expect "password:"
  send "xxxx\r"
  expect $prompt
  send "grep hostname /etc/rc.d/rc.local \n"
  expect $prompt
  set line $expect_out(buffer)
  ...more script...
ENDOFEXPECT