Using expect to SSH to server and execute commands

China☆狼群 提交于 2019-12-12 15:37:05

问题


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…



来源:https://stackoverflow.com/questions/13037623/using-expect-to-ssh-to-server-and-execute-commands

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!