Python 执行 expect 命令不匹配引号问题:python -c 'os.system("expect -c ...")'

Python executing expect command unmatching quotes issue: python -c 'os.system("expect -c ...")'

python -c 'import os; os.system("/usr/bin/expect -c \'spawn ssh root@localhost; expect \"password:\" { send \"root\r\"}; interact\'")'

当我在 CLI 中执行上述命令时出现不匹配引号问题(> 提示)

但是在 python 脚本中而不是在命令行中 运行 中执行它是可行的。此外,expect 脚本语法是正确的。

如何balance/level这种情况下的引号?我想了解其中的窍门。 有没有像正则表达式解析器在线检查的在线验证检查工具?

首先,在shell(我用的是Bash)中,正确写出expect -c "...":

[STEP 101] # expect -c "spawn ssh foo@localhost date; expect \"assword:\" { send \"foobar\r\"}; expect eof"
spawn ssh foo@localhost date
foo@localhost's password:
Wed 13 Jan 2021 10:26:53 AM CST
[STEP 102] #

(这里我只用了双引号,所以python -c '...'后面加单引号会更方便)

然后,写一个python -c 'print(...)',它会输出前面的expect -c:

[STEP 103] # python -c 'print("""expect -c "spawn ssh foo@localhost date; expect \"assword:\" { send \"foobar\r\"}; expect eof" """)'
expect -c "spawn ssh foo@localhost date; expect \"assword:\" { send \"foobar\r\"}; expect eof"
[STEP 104] #

然后,将 print 替换为 os.system:

[STEP 105] # python -c 'import os; os.system("""expect -c "spawn ssh foo@localhost date; expect \"assword:\" { send \"foobar\r\"}; expect eof" """)'
spawn ssh foo@localhost date
foo@localhost's password:
Wed 13 Jan 2021 10:27:33 AM CST
[STEP 106] #