由于我的远程服务器 [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
命令。
答案1
[
对于 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