使用Expect脚本从远程计算机执行SSH

Ksh*_*pta 0 ssh expect

我是新来的期待脚本的人,并且有一个用例,其中需要从已经使用Expect脚本执行过ssh的计算机上执行ssh。这是我的代码片段

#!/usr/bin/expect -f
set timeout 60
spawn ssh username@machine1.domain.com

expect "Password: "
send "Password\r"

send "\r" # This is successful. I am able to login successfully to the first machine

set timeout 60
spawn ssh username@machine2.domain.com  #This fails
Run Code Online (Sandbox Code Playgroud)

这需要花费一些时间,并且无法说出ssh:连接到host machine2.domain.com端口22:操作超时。我知道22是ssh运行的默认端口,我可以通过给ssh提供-p选项来手动覆盖它。

如果我尝试在没有期望脚本的情况下独立进行ssh操作,则会出现提示要求我输入的提示(是/否)。如果我不使用期望脚本直接执行ssh,将从何处获取正确的端口。如果我不需要在Shell上输入端口号,那么如果我使用的是期望脚本,为什么还要输入端口号。

gle*_*man 5

到那时,您无需产生新的ssh:spawn在本地计算机上创建新的进程。您只需将命令发送到远程服务器

#!/usr/bin/expect -f
set timeout 60
spawn ssh username@machine1.domain.com

expect "Password: "
send "Password\r"

send "\r" # This is successful. I am able to login successfully to the first machine

# at this point, carry on scripting the first ssh session:
send "ssh username@machine2.domain.com\r"
expect ...
Run Code Online (Sandbox Code Playgroud)