Python 测试 SSH 可用性的优雅方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14236346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:50:30  来源:igfitidea点击:

Elegant way to test SSH availability

pythonsshparamiko

提问by nightowl

I need a Python program I'm using to poll a remote server for SSH connectivity and notify when it is available. I am currently doing this using paramiko; attempt to connect, if failure, wait and retry until success or max retries. This works, but it's a bit clunky. Also paramiko seems to either connect or throw an error, so the only way I could see to do this was with a try/except block which is bad, bad, bad. Here is the method:

我需要一个 Python 程序来轮询远程服务器以进行 SSH 连接并在它可用时通知。我目前正在使用 paramiko 执行此操作;尝试连接,如果失败,等待并重试,直到成功或最大重试。这有效,但有点笨重。此外,paramiko 似乎要么连接要么抛出错误,所以我能看到的唯一方法是使用 try/except 块,它很糟糕,很糟糕,很糟糕。这是方法:

def check_ssh(self, ip, user, key_file, initial_wait=0, interval=0, retries=1):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    sleep(initial_wait)

    for x in range(retries):
        try:
            ssh.connect(ip, username=user, key_filename=key_file)
            return True
        except Exception, e:
            print e
            sleep(interval)
    return False

There must be a more elegant solution than this. Paramiko is my SSH library of choice but am open to any suggestions here.

必须有比这更优雅的解决方案。Paramiko 是我选择的 SSH 库,但我对这里的任何建议持开放态度。

To clarify, I want to avoid using try / except as a means to control the normal flow of code execution - it should be used for catching actual errors such as bad host key, invalid user etc.

澄清一下,我想避免使用 try / except 作为控制正常代码执行流程的手段——它应该用于捕获实际错误,例如主机密钥错误、用户无效等。

采纳答案by silvado

As mentioned in the comment by frb, a try ... exceptblock is a good approach to test availability of a specific service. You shouldn't use a "catch-all" exceptblock though, but limit it to the specific exceptions that occur if the service is unavailable.

正如 frb 的评论中提到的,try ... except块是测试特定服务可用性的好方法。不过,您不应使用“全能”except块,但应将其限制为服务不可用时发生的特定异常。

According to documentation, paramiko.SSHClient.connectmay throw different exceptions, depending on the problem that occured while connecting. If you want to catch all those, your try ... exceptblock would look like this:

根据文档,paramiko.SSHClient.connect可能会抛出不同的异常,具体取决于连接时发生的问题。如果您想捕获所有这些,您的try ... except块将如下所示:

try:
    ssh.connect(ip, username=user, key_filename=key_file)
    return True
except (BadHostKeyException, AuthenticationException, 
        SSHException, socket.error) as e:
    print e
    sleep(interval)

If just a subset of these exceptions is relevant to your case, put only those into the tuple after except.

如果这些异常中只有一部分与您的情况相关,请仅将这些异常放入except.