【问题标题】:Storing the output of a ssh/shell command as a regular string将 ssh/shell 命令的输出存储为常规字符串
【发布时间】:2014-06-21 04:27:16
【问题描述】:

我想将 ssh 命令的输出存储为字符串,以便我可以围绕它编写一些脚本,如下所示:

ssh_command = %x(ssh -t -t user@ip.ip.ip.ip)

问题是 'ssh_command' 实际上似乎并没有存储任何字符串。 它应该存储这个(对于一个无效的 IP):

ssh: connect to host ip.ip.ip.ip port 22: No route to host

它确实在 irb 中输出它,但不是作为 'ssh_command' 变量引用的字符串。

有趣的是,以下工作按预期工作:

uname_cmd = %x(uname -a)

在这种情况下,当我打印“uname_cmd”时,我确实得到了字符串输出,正如预期的那样。

所以我的问题是,有没有办法将 ssh 命令的输出存储为常规字符串,就像使用 uname 一样?

谢谢,

【问题讨论】:

    标签: ruby shell ssh scripting


    【解决方案1】:

    %x(..) 捕获标准输出,而 ssh 错误消息写入标准错误。

    您可以将 stderr 重定向到 stdout,以便使用 shell 重定向语法 2>&1 捕获它们:

    ssh_command = %x(ssh -t -t user@ip.ip.ip.ip 2>&1)
    

    【讨论】:

    • 正是我想要的!
    猜你喜欢
    • 2020-07-28
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 2011-09-13
    • 2023-01-12
    相关资源
    最近更新 更多