gpt4 book ai didi

linux - Expect 模块中字符串中的字符转义单引号

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:35 28 4
gpt4 key购买 nike

我已经创建了一个 .YML 剧本。

将一些代码放入其中,工作正常。

然后我遇到了一个问题 - 我正在尝试自动部署某个应用程序。应用程序提示用户交互。不幸的是,“yes | command”不起作用。它只是被忽略,并且仍然提示。

所以,我决定使用 Expect 模块。

当前代码如下所示:

- hosts: all
remote_user: someuser
gather_facts: yes

tasks:
- name: "Copy files"
copy: src=../somefiles/ dest=/tmp

- name: "Execute some script"
shell: sudo /tmp/script.sh

- name: "Execute app"
expect:
command: /bin/bash -c 'sudo /tmp/app arguments'
responses:
"'Press 'y' to confirm ('s' to skip, 'a' to abort):'": "y"
echo: y

我用双引号将 Expected 行括起来。但是,由于 Expected Line 有单引号 ('),它似乎违反了语法。

错误输出如下:

ERROR! Syntax Error while loading YAML.


The error appears to have been in 'deploy.yml': line 16, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

responses:
"'Press 'y' to confirm ('s' to skip, 'a' to abort):'": "y"
^ here
This one looks easy to fix. It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote. For instance:

when: "ok" in result.stdout

Could be written as:

when: '"ok" in result.stdout'

Or equivalently:

when: "'ok' in result.stdout"
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes. If starting a value with a quote, make sure the
line ends with the same set of quotes. For instance this arbitrary
example:

foo: "bad" "wolf"

Could be written as:

foo: '"bad" "wolf"'

我已经尝试过使用反斜杠 () 对单引号进行字符转义,并对单引号进行双引号。他们都没有工作。根据我引用的顺序,我要么得到This one looks easy to fix.,要么直接得到bad wolf

最佳答案

问题不是引号而是字符串中的特殊字符。 Expect 模块执行正则表达式匹配,因此响应字符串必须符合正则表达式

这意味着必须转义括号和逗号等特殊字符

工作示例是这样的:

/tmp/run.sh:

#!/bin/bash
echo "Press 'y' to confirm ('s' to skip, 'a' to abort):"
read response
echo $response

ansible 剧本:

- connection: local
hosts: localhost
tasks:
- name: "Execute app"
expect:
command: /tmp/run.sh
responses:
Press 'y' to confirm \('s' to skip\, 'a' to abort\):: "y"
echo: yes

关于linux - Expect 模块中字符串中的字符转义单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50565339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com