如何使用 Expect 从一台机器登录到另一台机器时执行 运行 命令
How to run commands while logging from one machine to another using Expect
我想编写一个 expect 脚本,它应该首先登录到 Linux 机器 m1,然后在 m1 中它应该登录到机器 m2。然后在 m2 中,我必须 运行 一些命令。
我尝试使用以下脚本,但是这里的预期脚本只是 运行 命令 "spawn ssh -X root@$m2"。然后它在没有 运行ning 命令 cmd1 和 cmd2 的情况下终止。
/usr/bin/expect <<EOF
set timeout -1
spawn ssh -X root@$m1
expect "assword:"
send "m1Password\r"
expect "#"
spawn ssh -X root@$m2
#Not given password here because the second machine doesn't ask for a password when logged in via m1.
send "cmd1\r"
expect "Cmd1 Res"
send "cmd2\r"
expect "Cmd2 Res"
EOF
我如何改进这个脚本,以便命令 cmd1 和 cmd2 应该通过这个 expect 脚本得到 运行?
您想 运行 第二个 ssh
在您已经打开到机器 m1 的连接中,所以您不需要第二个 spawn
因为这将尝试打开一个来自本地机器的新连接。因此,而不是第二个 spawn
,使用 send
到 运行 m1 上的 ssh 命令,然后在发送命令之前使用 expect
等待 m2 上的提示:
send "ssh -X root@$m2"
expect "#"
我想编写一个 expect 脚本,它应该首先登录到 Linux 机器 m1,然后在 m1 中它应该登录到机器 m2。然后在 m2 中,我必须 运行 一些命令。
我尝试使用以下脚本,但是这里的预期脚本只是 运行 命令 "spawn ssh -X root@$m2"。然后它在没有 运行ning 命令 cmd1 和 cmd2 的情况下终止。
/usr/bin/expect <<EOF
set timeout -1
spawn ssh -X root@$m1
expect "assword:"
send "m1Password\r"
expect "#"
spawn ssh -X root@$m2
#Not given password here because the second machine doesn't ask for a password when logged in via m1.
send "cmd1\r"
expect "Cmd1 Res"
send "cmd2\r"
expect "Cmd2 Res"
EOF
我如何改进这个脚本,以便命令 cmd1 和 cmd2 应该通过这个 expect 脚本得到 运行?
您想 运行 第二个 ssh
在您已经打开到机器 m1 的连接中,所以您不需要第二个 spawn
因为这将尝试打开一个来自本地机器的新连接。因此,而不是第二个 spawn
,使用 send
到 运行 m1 上的 ssh 命令,然后在发送命令之前使用 expect
等待 m2 上的提示:
send "ssh -X root@$m2"
expect "#"