处理缺失的SSH连接

发布于 2025-02-11 14:52:14 字数 294 浏览 0 评论 0原文

为了通过SSH连接,我使用以下代码:

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP, username=USER, password=PSW,look_for_keys=False)

我的问题是,如何处理丢失的连接? 特别是我想要的,如果没有建立连接,则代码(也许是goto?)到了代码的另一点,我基本上是我重新启动服务器。

In order to connect via SSH I'm using the following code:

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP, username=USER, password=PSW,look_for_keys=False)

my question is, how can I handle a missing connection?
In particular I'd like that in case the connection is not established the code goes (maybe with a GOTO?) to another point of the code where basically I restart the server.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温馨耳语 2025-02-18 14:52:14

您可以简单地尝试尝试捕获异常
martin-prikryl ,例如:

try:
    client.connect(host="192.168.0.8",
                   username="user1",
                   password="password1234"
                   )
except AuthenticationException:
    print("Authentication failed, please verify your credentials: %s")
except SSHException as sshException:
    print("Unable to establish SSH connection: %s" % sshException)

对于SSH例外的其他示例,您可以查看 https://www.programcreek.com/python/example/example/7495/paramiko.sshexception

You could simply use a try and catch the exception as mentioned by
martin-prikryl, such as:

try:
    client.connect(host="192.168.0.8",
                   username="user1",
                   password="password1234"
                   )
except AuthenticationException:
    print("Authentication failed, please verify your credentials: %s")
except SSHException as sshException:
    print("Unable to establish SSH connection: %s" % sshException)

For other examples of ssh exceptions you can look at https://www.programcreek.com/python/example/7495/paramiko.SSHException

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文