linux - SSH 命令在 Expect 脚本中的行为有所不同

标签 linux bash shell ssh expect

我正在创建一个从主机 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?

附注

  1. 手动登录主机 A
  2. cd 到脚本位置
  3. 运行 ssh user@hostname/path/to/script/script.sh | cat >> 主机 A 上的/tmp/file
  4. 猫/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/

相关文章:

使用 GCC 编译 C 程序时找不到 -lgcc -s

bash - 协助 awk/bash 捕获内存差异

bash - 通过 .csv 文件中的链接下载文件

windows - 如何通过 START 命令运行多个命令

Linux:获取 sctp 连接的套接字选项时出错

linux - 命令行(甚至以编程方式)检索图像的一部分

linux - TIME_WAIT 连接太多,得到 "Cannot assign requested address"

bash set -e and i=0;让i++不同意

mysql - BASH:在测试条件之前检查错误

linux - 用于选择单词中特定字母并打印该单词的 Shell 脚本忽略 linux 中的其他字母