首页 > 解决方案 > 如何在一行中通过 SSH 进行命令替换

问题描述

我需要检查 remote_server 的正常运行时间是否小于 600 秒,如果大于它则打印通过,否则打印失败。我知道它可以使用 HERE 文档,但我需要在一行中执行此操作。以下是使用 shell one liner 和 HERE doc 的两次失败尝试

使用一行的原因:我会将这一行提供给 ansible 的 shell 模块。我尝试了以下命令并使用单引号来防止扩展,但它不起作用。

ssh remote_server "if [ '$(grep -oP \"^[0-9]+\" /proc/uptime)' -le 600 ];then echo  remote_server Failed ;exit 1;else echo remote_server passed ;fi"

我还尝试了以下方法将 if 条件转换为 ansible 中的多行。但它也不起作用。

  - name: get the uptime of all nodes
    shell:  |
    ssh {{ item }} " bash <<'EOF'
    if [ '$(grep -oP \"^[0-9]+\" /proc/uptime)' -le 600 ];then
        echo  {{ item }} Failed ;
        exit 1;
     else
        echo {{item }} passed ;
     fi
     "
     EOF
    with_items:
      - "{{ node_list.stdout_lines }}"
    become: true

违规行似乎是:

       ssh {{ item }} " bash <<'EOF'
        if [ '$(grep -oP \"^[0-9]+\" /proc/uptime)' -le 600 ];then
        ^ here

exception type: <class 'yaml.scanner.ScannerError'>
exception: while scanning a simple key
  in "<unicode string>", line 51, column 9
could not find expected ':'
  in "<unicode string>", line 52, column 9

更新:

 shell:  ssh {{ item }} 'if [ "$(grep -oP '^[0-9]+' /proc/uptime) -le 600 ]; then echo failed; exit 1; else echo passed; fi'

错误:

"start": "2019-02-07 15:05:36.740756",
"stderr": "bash: -c: line 0: unexpected EOF while looking for matching `\"'\nbash: -c: line 1: syntax error: unexpected end of file",
"stderr_lines": [
    "bash: -c: line 0: unexpected EOF while looking for matching `\"'",
    "bash: -c: line 1: syntax error: unexpected end of file"
],
"stdout": "",
"stdout_lines": []

标签: bashansible

解决方案


推荐阅读