我正在创建一个从主机 A 执行的脚本,以连接到远程主机 B,在主机 B 上运行 bash 脚本(从顶部等生成监控数据),并将输出附加回主机 A 上的文件。当我使用 ssh 进行连接时,我不会使用 ssh-keys,因为环境中的服务器太多了。
我的期望脚本:
"#!/usr/bin/expect
"#!/usr/bash
set timeout 10
set hostname [sample_hostname]
set user "(sample_user)"
set password "(sample_password)"
spawn ssh $user@$hostname /path/to/bash/script/script.sh | cat >> /tmp/file
expect "Password:"
send "$password\r";
expect "$"
====================================
上述脚本将 bash 脚本的输出附加到主机 B/tmp/file,而不是所需的主机 A/tmp/file。如何更改以将脚本附加到主机 A 而不是主机 B?
附注
- 手动登录主机 A
- cd 到脚本位置
- 运行 ssh user@hostname/path/to/script/script.sh | cat >> 主机 A 上的/tmp/file
- 猫/tmp/文件
上述手动步骤按需要执行;因此我认为问题出在expect中的bash。
任何想法都值得赞赏!
问候,
艾伦
最佳答案
如果您只想获取该脚本的输出,请按照以下方式继续。
#!/usr/bin/expect
set timeout 10
set hostname host
set user dinesh
set password pwd
set script "/home/dinesh/mypgms/demo.sh"
spawn ssh $user@$hostname
expect "password:"
send "$password\r";
expect "\\\$"; # Matching the literal dollar prompt sign of terminal
send "$script\r"
expect -re "\r\n(.*)\\\$"; # Matching the output
# Getting first sub-match as result
puts "\nResult : --->$expect_out(1,string)"
这将给出输出
dinesh@dinesh-VirtualBox:~/stackoverflow$ ./alan
spawn ssh dinesh@host
dinesh@host's password:
Last login: Tue Apr 21 13:30:35 2015
[dinesh@ ~]$ /home/dsivaji/mypgms/demo.sh
{\"INFO\":0}\0\r
{\"INFO\":0}\0\r
[dinesh@~]$
Result : --->{\"INFO\":0}\0\r
{\"INFO\":0}\0\r
[dinesh@~]
dinesh@dinesh-VirtualBox:~/stackoverflow$
注意结果为
{\"INFO\":0}\0\r
{\"INFO\":0}\0\r
[dinesh@~]
由于我们正在匹配提示符 $
,因此它包含到该点为止。您还可以根据 shell 输出自定义正则表达式。
关于linux - SSH 命令在 Expect 脚本中的行为有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29759537/