加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 使用expect脚本帮助,在远程comp上运行cat并将其输出到变

发布时间:2020-12-15 18:29:31 所属栏目:安全 来源:网络整理
导读:我有一个bash expect脚本,它必须通过ssh连接到远程comp,在那里读取文件,找到带有“hostname”的特定行(如“hostname aaaa1111”)并将此主机名存储到while之后要使用的变量中.如何获
我有一个bash expect脚本,它必须通过ssh连接到远程comp,在那里读取文件,找到带有“hostname”的特定行(如“hostname aaaa1111”)并将此主机名存储到while之后要使用的变量中.如何获取“hostname”参数的值?我认为行内容将在$expect_out(缓冲区)变量中(因此我可以扫描并分析),但事实并非如此.我的脚本是:
#!/bin/bash        
    ----bash part----
    /usr/bin/expect << ENDOFEXPECT
    spawn bash -c "ssh root@$IP"  
    expect "password:"
    send "xxxxr"
    expect ":~#"
    send "cat /etc/rc.d/rc.local |grep hostname n"
    expect ":~#"
    set line $expect_out(buffer)
    puts "line = $line,expect_out(buffer) = $expect_out(buffer)"
    ...more script...
    ENDOFEXPECT

这里http://en.wikipedia.org/wiki/Expect有一个例子:

# Send the prebuilt command,and then wait for another shell prompt.
    send "$my_commandr"
    expect "%"
    # Capture the results of the command into a variable. This can be displayed,or written to disk.
    set results $expect_out(buffer)

似乎它在这种情况下不起作用,或者脚本有什么问题?

首先,你的heredoc就像一个双引号字符串,因此$expect_out变量在expect开始之前被shell替换.你需要确保你的heredoc没被shell接触.因此,需要以不同的方式获取任何shell变量.在这里,我假设IP是一个shell变量,我将它传递给环境.
export IP
/usr/bin/expect << 'ENDOFEXPECT'
  set prompt ":~#"
  spawn ssh root@$env(IP)  
  expect "password:"
  send "xxxxr"
  expect $prompt
  send "grep hostname /etc/rc.d/rc.local n"
  expect $prompt
  set line $expect_out(buffer)
  ...more script...
ENDOFEXPECT

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读