将远程 (Paramiko) ssh 命令的输出评估为 success/failure 布尔值

Evaluating a remote (Paramiko) ssh command's output into a success/failure boolean

我有一个检查文件是否存在的函数,它 returns 'True'/'False',现在我 'converting' 它与 eval(),但我不认为这是最聪明的解决方案,但我不确定在没有不必要的情况下如何做到这一点 ifs

>>> foo = 'False'
>>> type(eval(foo))
<class 'bool'>
>>> type(foo)
<class 'str'>

比如我是运行这个表达式,在ssh连接的机器上

"test -e {0} && echo True || echo False".format(self.repo)

像这样,我的结果将是字符串。

def execute(command):
    (_, stdOut, _) = ssh.exec_command(command)
    output = stdOut.read()
    return output.decode('utf-8')

还有其他方法可以实现吗?

您可以使用 ast.literal_eval()。这比 eval() 更安全,因为它只计算文字,而不是任意表达式。

python 中的最佳做法是 return 确定 python 中的布尔值的操作,而不是像这样做:

if something:
    return True
else:
    return False

使用文件检查器的示例(这不需要包装在函数中,但为了举例:

import os

def check_file(infile):
    return os.path.isfile(infile)

print(type(check_file('fun.py'))) # is true # <class 'bool'>
print(type(check_file('nonexistent.txt'))) # is false # <class 'bool'>

在将文件名包含在可能被解析为代码的上下文中之前,应始终引用文件名。

在这里,我们使用 How can you get the SSH return code using Paramiko? 中介绍的技术直接从 SSH 通道检索退出状态,无需解析通过 stdout 传递的任何字符串。

try:
  from pipes import quote  # Python 2.x
except ImportError:
  from shlex import quote  # Python 3.x

def test_remote_existance(filename):
    # assuming that "ssh" is a paramiko SSHClient object
    command = 'test -e {0} </dev/null >/dev/null 2>&1'.format(quote(remote_file))
    chan = ssh.get_transport().open_session()
    chan.exec_command(command)
    return chan.recv_exit_status() == 0

要通过 SSH 测试文件是否存在,请使用标准 API – SFTP,而不是 运行 shell 命令。

使用 Paramiko,您可以通过以下方式做到这一点:

sftp = ssh.open_sftp()
try:
    sftp.stat(path)
    print("File exists")
except IOError:
    print("File does not exist or cannot be accessed")