将远程(paramiko)ssh命令的输出评估为成功/失败布尔值

问题描述 投票:0回答:4

我有一个检查文件是否存在的函数,它返回'True' / 'False',现在我正在将其“转换”为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')

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

python paramiko
4个回答
3
投票

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

[这里,我们使用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

5
投票

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


1
投票

在python中,最好的方法是返回确定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'>

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.