【问题标题】:Remove send command from terminal output while keeping needed output从终端输出中删除发送命令,同时保留所需的输出
【发布时间】:2014-03-06 00:40:01
【问题描述】:

我正在尝试创建一个脚本,该脚本将登录到服务器,运行一些命令,同时向用户提供信息。 我可以使用脚本很好地登录服务器,我的问题是我得到的输出。我的脚本是这样的:

#!/bin/bash

/usr/bin/expect << SSHLOGIN

set timeout 600

spawn ssh user@myServer.com
expect {
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\n";exp_continue
    }
        Password: {
            send "$2\n"
        }
}
expect {
    "# " {
        send "echo \"Current Directory is:\" \n"
    }
}
expect "# " {
        send "pwd \n"
}
expect {
    "# " {
        send "exit \n"  
    }   
}
wait
SSHLOGIN

&我的输出如下:

spawn ssh user@myServer.com
Password: 
You have new mail.
DISPLAY set to user.myServer:0.0
# echo "Current Directory is:" 
Current Directory is:
# pwd 
/home/user/

我想要达到的输出是这样的:

spawn ssh user@myServer.com
Password: 
You have new mail.
DISPLAY set to user.myServer:0.0
Current Directory is:
/home/user/

我尝试过使用 log_user 0/1、stty 等。但我似乎无法正确使用这些...

任何帮助将不胜感激。

【问题讨论】:

    标签: bash ssh scripting expect


    【解决方案1】:

    问题在于衍生进程的标准输出包括程序输出发送的命令,后者只是因为来自远程设备的回显。

    您可以通过 log_user 命令操作 stdout,在仍然期待和捕获的同时将其关闭,并通过“puts”命令自己打印输出。最后重新启用,如果需要的话。下面的工作是因为 Expect 在 expect 命令之前不会读取回显的命令。

    我现在无法测试所以我会留给你正则表达式以匹配 pwd 输出(注意当前路径的提示),但由于你的问题不是正则表达式,我认为以下将为您做:

    #!/bin/bash
    
    /usr/bin/expect << SSHLOGIN
    
    set timeout 600
    
    spawn ssh user@myServer.com
    expect {
        "Are you sure you want to continue connecting (yes/no)?" {
            send "yes\n";exp_continue
        }
            Password: {
                send "$2\n"
            }
    }
    expect {
        "# " {
            send "pwd \n"
            log_user 0
            expect -re "(include_here_between_the_parenthesis_a_regexp_that_matches_your_pwd_output)" {
                puts "Current directory is: $expect_out(1,string)"
            }
            log_user 1
    }
    expect {
        "# " {
            send "exit \n"  
        }   
    }
    wait
    SSHLOGIN
    

    作为最后的评论...为什么不将第一行更改为 #!/usr/bin/expect 并使其成为一个期望脚本,而不是一个带有此处文档网(或其他任何名称)的 bash 脚本?毕竟这几乎是纯粹的期望代码。

    让我知道这是怎么回事,如果确实有帮助,请不要忘记投票或标记答案。 :-)

    【讨论】:

    • 嗨詹姆斯,这很好用。花了一段时间才弄清楚正则表达式,但我到了那里。我还听取了您关于更改为纯期望而不是 bash 的建议。谢谢你的帮助。 =)
    猜你喜欢
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多