我正在尝试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个文件。
提前感谢您的帮助!
答案 0 :(得分:1)
使用exec
将在本地执行命令。
发送ls
命令后,您必须使用expect_out
数组来获取响应。
set prompt "(.*)(#|%|>|\\\$) $"
send "ls\r"
expect -re $prompt
puts $expect_out(1,string)