paramiko.ssh_exception.SSHException client.connect 格式

paramiko.ssh_exception.SSHException client.connect format

我正在尝试登录远程计算机 (EC2)。但它一直说有 SSHException 并且密钥无效。

paramiko.ssh_exception.SSHException: Invalid key (class: RSAKey, data type: oQIBAAKCAQEApkTX3as35p1TF9W..............

这是我的代码:

import paramiko

amznKey = "MIIEoQIBAAKCAQEApkTX3as35p1TF9W............."
key = paramiko.RSAKey(data=bytes(amznKey, 'utf-8'))
client = paramiko.SSHClient()
client.get_host_keys().add('ubuntu@ec2-3-123-12-80.us-east-2.compute.amazonaws.com', 
'ssh-rsa', key)
client.connect('ubuntu@ec2-2-134-99-80.us-east-2.compute.amazonaws.com', username='', password='')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print('... ' + line.strip('\n'))
client.close()

此外,是否有更好的方法通过 python 通过 SSH 连接到 EC2?

最终在朋友的帮助下找到了答案。虽然这是我犯的一个简单错误,但我还是要在这里提及它,因为很难追溯错误。

因为我把 host= 写成了 user@host。如果有人需要,这是一个工作代码。用户名通常是您在 AWS 中使用的 OS。例如ubuntu 对于 Ubuntu。

import paramiko


hostname = "ec2-3-123-12-80.us-east-2.compute.amazonaws.com"  # Remote machine's public DNS
username = "ubuntu"  # Username for SSH                                     
pass_key = "amzonLinux16.pem"  # Your Private Key for AWS EC2

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname, username=username, key_filename=pass_key)
for command in 'echo "Hello, world!"', 'cat ~/test', 'uptime', 'ifconfig':
    stdin, stdout, stderr = client.exec_command(command)
    stdin.close()
    print(stdout.read().decode('utf-8'))
    stdout.close()
    stderr.close()
client.close()