期望:SSH 到远程主机,运行 一个命令,并将其输出保存到一个变量

Expect: SSH into a remote host, run a command, and save its output to a variable

我正在尝试通过 ssh 连接到服务器,运行 一个命令,并将其输出保存到一个变量,但没有成功。

spawn $env(SHELL)
expect "$ "
send "ls\r"
expect "$ "
send "ssh myserver1\r"
expect "$ "
send "cd /tmp/remotedir1\r"
expect "$ "
send "ls\r"
expect "$ "
set myvar1 [exec ls]
puts "The value of $myvar1 is: "
puts $myvar1
send "exit\r"
expect "$ "
send "exit\r"
expect eof

当我 运行 它时,我得到:

spawn /bin/bash
$ ls
localfile1      localfile2       localfile3
$ ssh myserver1
Last login: Tue Sep 10 15:45:07 2017 from 192.168.0.100
myserver1$ cd /tmp/remotedir1
myserver1$ ls
remotefile1
myserver1$ The value of $myvar1 is:
localfile1
localfile2
localfile3
exit
logout
Connection to myserver1 closed.
bash-3.2$ exit
exit

显然,它没有将 $myvar1 设置为 "remotefile1",而是设置为本地主机上 $cwd 中的那 3 个文件。

提前感谢您的帮助!

使用exec将在本地执行命令。

发送 ls 命令后,您必须使用 expect_out 数组来获取响应。

set prompt "(.*)(#|%|>|\$) $"
send "ls\r"
expect -re $prompt
puts $expect_out(1,string)