bash - 如何在一行中通过 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": []
解决方案
推荐阅读
- wpf - wpf 动态用户安全
- php - foreach 中的变量命名
- php - 如何将自定义价格等自定义选项传递给 WooCommerce 购物车
- ruby-on-rails - 来自自己的控制器方法的嵌套资源 - 或创建全新的控制器?
- javascript - 使用 $.getJSON 将 $_GET 中的城市替换为经纬度
- google-apps-script - 我可以制作与域用户和协作者共享的 GSuite 插件吗
- java - 我是否需要担心使用 ENUM 的默认操作?
- python - 在 PyTorch 中索引多维张量中的最大元素
- css - 断点对引导间距意味着什么?
- math - 十进制相同二进制整数的有符号负数和正数版本之间的关系是什么?