我正在尝试编写一个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
当我运行它时,它总是返回 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