在没有单独文件的情况下从 Python 调用 `expect`

Calling `expect` from Python without a separate file

我有以下预期文件,我想将其嵌入到 python 脚本中。目前它是我从 python 脚本中调用的独立文件,但我想合并这两个文件:

do_remote.sh

#!/usr/bin/expect
spawn ssh -i priv.key user@ip touch test.txt
expect "Enter passphrase for key 'priv.key':"
send "<passphrase>\n"
interact;

call_remote.py

import os
...
os.system('./do_remote.sh')
...

我不能使用任何未包含在标准 python 中的库(例如 Paramiko 或 Pexpect)。

我没有明确需要使用 ssh 命令的输出(但它会很好)。明确地说,我只想拥有 1 个源代码文件而不是 2 个。我可以使用 os.system().

这不是真正的 bash 文件,因为此文件的第一行:

#!/usr/bin/expect

实际上声明解释器是预期的。 不要尝试从 python 中 运行 shell 文件,而是尝试启动 expect 并提供 expect 文件作为参数:

os.system('/usr/bin/expect do_remote.sh')

您可以在命令行中使用 expect -c:

指定 Expect 脚本
import subprocess

subprocess.call(["expect", "-c", """
    spawn ssh -i priv.key user@ip touch test.txt
    expect "Enter passphrase for key 'priv.key':"
    send "<passphrase>\n"
    interact;
    """])