Expect脚本:将ls命令的输出设置为变量 [英] expect script: set the output of ls command to a variable

查看:656
本文介绍了Expect脚本:将ls命令的输出设置为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Shell脚本和导航不同脚本语言的新手.

I'm new to shell scripting and navigating different script languages.

我正在编写一个Expect脚本,我想在其中将ssh ls命令的输出设置为要循环通过的变量,例如以下bash脚本

I'm writing an expect script where I want to set the output of a ssh ls command to a variable to loop through, like the following bash script

#!/bin/bash
var=$(ssh user@host ls path | grep 'keyword')

echo $var

for x in $var;
# do stuff 
done

但是我不确定如何在期望脚本中执行此操作.我搜索的其他示例似乎正在将send的输出设置为变量-这是路由吗?

But I'm not sure how to do this in an expect script. Other examples I searched seem to be setting the output of send to a variable--is this the route?

感谢您的帮助.

推荐答案

将已发送命令的输出捕获到Expect变量中实际上是PITA.捕获的输出包含命令和提示:假设您的提示是"> ",并且您发送了date命令.期望会看到这个:

Capturing the output of a sent command into an expect variable is actually a PITA. The captured output contains the command and the prompt: suppose your prompt is "> " and you send the date command. Expect will see this:

"date\r\nTue Nov 15 11:34:16 EST 2016\r\n> "

因此,您需要执行以下操作以捕获输出:

So you need to do this to capture the output:

send -- "date\r"
expect -re {^[^\n]+\n(.*)\r\n> $}
set output $expect_out(1,string)

在这种复杂的模式中:

  • ^[^\n]+\n将匹配您发送的命令(直到第一行)-这是date\r\n
  • (.*)\r\n是命令的输出(直到最后一行结束)
    • expect将捕获的文本存储在变量expect_out(1,string)
    • ^[^\n]+\n will match the command you send (up to the first newline) -- this is date\r\n
    • (.*)\r\n is the output of the command (up to the last line ending)
      • expect will store the captured text in the variable expect_out(1,string)

      所以您的程序将是:

      #!/usr/bin/env expect
      spawn ssh user@host
      expect -re {\$ $}      ;# regular expression to match your prompt
      
      send -- "ls path | grep keyword\r"
      expect -re {^[^\n]+\n(.*)\r\n$ $}
      set output $expect_out(1,string)
      
      send -- "exit\r"
      expect eof
      
      puts $output
      

      这篇关于Expect脚本:将ls命令的输出设置为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆