Using expect to SSH to server and execute commands

2019-07-07 06:47发布

问题:

I want to write a generic expect script to login through SSH to a system and execute some commands. An example I found had the following:

#!/usr/bin/expect

set fid [open ./.secret]
set password [read $fid]
close $fid
spawn /usr/bin/ssh root@[lindex $argv 0]
expect {
  -re ".*Are.*.*yes.*no.*" {
    send "yes\n"
    exp_continue
    #look for the password prompt
  }

  "*?assword:*" {
    send $password
    send "\n"
  }
}

send -- "PS1='>'\r"
expect -re ">$" { send "hostname\r" }
expect -re ">$" { send "pwd\r" }

...the script seems to login properly but it didn't execute the last 2 sends. Ideas?

Edit: After enabling exp_internal, I noticed the following:

expect: does "" (spawn_id exp4) match glob pattern "*"? yes
expect: set expect_out(0,string) ""
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) ""
send: sending "PS1='>'\r" to { exp4 }
Gate keeper glob pattern for '>$' is '>'. Activating booster.

expect: does "" (spawn_id exp4) match regular expression ">$"? Gate ">"? gate=no


expect: does "\r\n" (spawn_id exp4) match regular expression ">$"? Gate ">"? gate=no
Last login: Tue Nov  6 14:13:31 2012 from 1.x.x.x

expect: does "\r\nLast login: Tue Nov  6 14:13:31 2012 from 1.x.x.x\r\r\n" (spawn_id exp4) match regular expression ">$"? Gate ">"? gate=no

I'm trying to send PS1='>'\r because I want to override the prompt. I don't think there's any way for me to predict what the prompt will be and therefore, I wouldn't know what pattern to expect. From the above, it looks like the prompt wasn't changed. How do you tackle a problem like this?

回答1:

There doesn't appear to be anything obviously wrong with your script (though using a different prompt might make matching a bit easier). Which means it is something subtle. I suggest adding this:

exp_debug 1

to somewhere early in your script. It will make the Expect engine print a lot more about what it is doing, which will (probably) help you understand what is going wrong, or failing that help the people here help you…



标签: tcl expect