如何在没有登录信息的情况下验证 SSH 连接是否可行?
How can I verify that an SSH connection is possible without login information?
我正在尝试编写一个 python2.7 函数来判断是否可以使用 SSH 协议连接到特定 IP 地址(主机)。问题是我必须在没有我正在连接的设备的登录信息的情况下这样做。我的计划是尝试连接一个空字符串作为用户名和密码,然后使用它抛出的异常来确定它是否可以连接。我的理由是,如果它抛出一个 AuthenticationException,它一定已经尝试连接但只是确定登录信息无效。到目前为止,这是我的代码:
def ssh(host):
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(host, username=None, password=None)
except(paramiko.ssh_exception.AuthenticationException,
paramiko.ssh_exception.BadAuthenticationType,
paramiko.ssh_exception.BadHostKeyException,
paramiko.ssh_exception.PasswordRequiredException,
paramiko.ssh_exception.PartialAuthentication):
return True
except Exception as e:
print(e)
return False
当我 运行 这个时,它总是 returns false 并输出:No authentication methods available
我的问题是:
- 这是实现我想要的目标的可行策略吗?
- 哪些异常是由错误的凭据引起的,哪些是由更严重的问题引起的,即使使用正确的凭据也会阻止连接?
- 哪个函数正在打印到控制台,我该如何停止它?我想自己处理错误消息。
提前致谢!
只需尝试连接目标端口:
import socket
def check_ssh(server_ip, port=22):
try:
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_socket.connect((server_ip, port))
except Exception, ex:
# not up, log reason from ex if wanted
return False
else:
test_socket.close()
return True
我正在尝试编写一个 python2.7 函数来判断是否可以使用 SSH 协议连接到特定 IP 地址(主机)。问题是我必须在没有我正在连接的设备的登录信息的情况下这样做。我的计划是尝试连接一个空字符串作为用户名和密码,然后使用它抛出的异常来确定它是否可以连接。我的理由是,如果它抛出一个 AuthenticationException,它一定已经尝试连接但只是确定登录信息无效。到目前为止,这是我的代码:
def ssh(host):
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(host, username=None, password=None)
except(paramiko.ssh_exception.AuthenticationException,
paramiko.ssh_exception.BadAuthenticationType,
paramiko.ssh_exception.BadHostKeyException,
paramiko.ssh_exception.PasswordRequiredException,
paramiko.ssh_exception.PartialAuthentication):
return True
except Exception as e:
print(e)
return False
当我 运行 这个时,它总是 returns false 并输出:No authentication methods available
我的问题是:
- 这是实现我想要的目标的可行策略吗?
- 哪些异常是由错误的凭据引起的,哪些是由更严重的问题引起的,即使使用正确的凭据也会阻止连接?
- 哪个函数正在打印到控制台,我该如何停止它?我想自己处理错误消息。
提前致谢!
只需尝试连接目标端口:
import socket
def check_ssh(server_ip, port=22):
try:
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_socket.connect((server_ip, port))
except Exception, ex:
# not up, log reason from ex if wanted
return False
else:
test_socket.close()
return True