import paramiko
import hashlib
import base64
import getpass
def get_host_key_fingerprint(hostname, port=22):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, port=port, username='dummy', password='dummy')
except:
pass
key = client.get_transport().get_remote_server_key()
fingerprint = hashlib.sha256(key.get_fingerprint()).hexdigest()
client.close()
return ':'.join(a+b for a,b in zip(fingerprint[::2], fingerprint[1::2]))
def ssh_login_with_otp(hostname, username, password, otp_func):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 获取 fingerprint
fingerprint = get_host_key_fingerprint(hostname)
print(f"Host key fingerprint: {fingerprint}")
# 验证 fingerprint
if input("Verify fingerprint (y/n): ").lower() != 'y':
print("Fingerprint verification failed")
return
# 获取动态密码
otp = otp_func()
try:
client.connect(hostname, username=username, password=password+otp)
print("Login successful!")
# 执行命令
stdin, stdout, stderr = client.exec_command('ls -l')
print(stdout.read().decode())
except Exception as e:
print(f"Login failed: {str(e)}")
finally:
client.close()
# 模拟获取动态密码的函数
def get_otp():
return input("Enter OTP: ")
# 使用示例
hostname = '
example.com'
username = 'your_username'
password = getpass.getpass("Enter password: ")
ssh_login_with_otp(hostname, username, password, get_otp)
gpt yyds