Python在启动无密码SSH连接时的try和except使用

0 投票
1 回答
506 浏览
提问于 2025-04-18 08:15

我想知道在这种情况下,使用try和except来处理ssh是否有效。如果try部分要求输入ssh密码,那么它应该跳到except部分。以下是我的代码:

 import os,sys,subprocess

         def ProcesS (input):
            print input
            A = subprocess.Popen (input,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            output,error = A.communicate()
            return output,error

 try:
         ProcesS('ssh system1@123.123.123.123 \'ls\'')
 except:
         ProcesS('ssh system2@10.101.10.1 \'ssh system1@123.123.123.123 \'ls\' \'')

在我的情况下,即使是ssh超时也没有起作用。

1 个回答

1

你这样写是行不通的,因为 ssh 会一直等着你输入密码,而不会失败。

不过,由于你没有给这个命令发送任何输入,你可以给 ssh 加上 -n 这个选项,这样如果它想要询问什么,它就会失败。所以加上 -n 后就应该能正常工作了。

撰写回答