我是 expect
的新手命令。
我正在尝试 ssh 到 server1
通过 server2
.以下脚本连接到 server2
.
#!/usr/bin/expect
spawn ssh user2@server2
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "password2\r"
interact
问题是如何进行。如何连接到
server1
来自 server2
.
最佳答案
基本上,到 Expect
,您只需发送一些命令并获得响应。来自 Expect
的观点,你必须产生一个 ssh
session 然后你可以发送任何你想要的命令。任何命令也可以是 ssh
命令。
方法一:
#!/usr/bin/expect
set server1 190.x.x.x
set user1 root
set pwd1 "mypwd1"
set server2 130.x.x.x
set user2 dinesh
set pwd2 "mypwd2"
spawn ssh $user2@$server2
expect "password:"
send "$pwd2\r";
expect "\\\$"
send "pwd\r"; # Just executing the 'pwd' command
expect "\\\$"
send "hostname\r" ; # Also executing 'hostname' command for your reference
expect "\\\$"
send "ssh $user1@$server1\r"
expect "password:"
send "$pwd1\r";
expect "# $"
send "pwd\r"
expect "# $"
send "hostname\r"
expect "# $"
方法二:
令人惊讶的是,还有一种更简单的方法。 ssh 本身将支持通过添加
-t
来级联命令标志在里面。 ssh -t user@outerhost ssh root@innerhost
在我们的代码中应用这个逻辑,我们可以有,
#!/usr/bin/expect
set pwd1 "mypwd1"
set pwd2 "mypwd2"
spawn ssh -t user@outerhost ssh user@innerhost
expect "password:"
send "$pwd2\r"
expect "password:"
send "$pwd1\r";
expect "# $"
send "pwd\r"; # Just executing 'pwd' command
expect "# $"
方法 2 引用:https://stackoverflow.com/a/15161956
注:如果您的主要目的是仅在内部主机中执行命令,而外部主机就像一个旁路,那么方法 2 更可取。
关于ubuntu - 与期望级联ssh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333561/