Expect

期望具有多個命令的命令

  • January 25, 2017

因為我的遠端伺服器有問題

$$ authorized_keys… $$我在本地機器上寫了一個腳本,它使用expect命令 ssh 進入伺服器,然後執行cd,然後git pull 但我不能讓這個東西工作:

#!/usr/bin/expect
spawn ssh USER@IP_ADDRESS   
expect {
   "USER@IP_ADDRESS's password:"  {
       send "PASSWORD\r"
   }
   "[USER@server ~]$" {
       send "cd public_html"
   }
}   
interact

我需要逃避一些字元嗎?即使我嘗試它仍然會忽略該cd命令。

[對於 TCL 來說是特殊的,因此需要通過"\[quotes]"大括號或用花括號替換引號來進行適當的處理{[quotes]}。一個更完整的例子看起來像

#!/usr/bin/env expect

set prompt {\[USER@HOST[[:blank:]]+[^\]]+\]\$ }
spawn ssh USER@HOST

expect_before {
   # TODO possibly with logging, or via `log_file` (see expect(1))
   timeout { exit 1 }
   eof { exit 1 }
}

# connect
expect {
   # if get a prompt then public key auth probably logged us in
   # so drop out of this block
   -re $prompt {}
   -ex "password:" {
       send -- "Hunter2\r"
       expect -re $prompt
   }
   # TODO handle other cases like fingerprint mismatch here...
}

# assuming the above got us to a prompt...
send -- "cd FIXMESOMEDIR\r"

expect {
   # TWEAK error message may vary depending on shell (try
   # both a not-exist dir and a chmod 000 dir)
   -ex " cd: " { exit 1 }
   -re $prompt {}
}

# assuming the above got us to a prompt and that the cd was
# properly checked for errors...
send -- "echo git pull FIXMEREMOVEDEBUGECHO\r"

expect -re $prompt
interact

引用自:https://unix.stackexchange.com/questions/325096