从python paramiko获取标准输出的问题

最后发布: 2017-10-06 14:41:39


问题

我正在尝试使用paramiko和AWS,但无法使SSH正常工作。 当我手动SSH进入服务器并且没有收到任何错误消息时,它可以工作。 我能帮我弄清楚我在做什么错吗?

我已经尝试过stdout.read()和stdout.readlines()。 两者都是空的。

码:

#Load the key into a file and attempt to SSH in
key = paramiko.RSAKey.from_private_key_file('TestInstanceKey.pem')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("Connecting")
#Try to ssh in and run and display ifconfig
try:
    ssh.connect(hostname=instance.public_ip_address, username="ec2-user", 
    pkey=key)
    print("Connected")
    print("Executing ifconfig")
    stdin, stdout, stderr = ssh.exec_command("ifconfig")
    lines = stdout.read()
    print(lines)
    for line in lines:
        print(line)
    ssh.close()
except Exception as e:
    print(e)
    input("Press enter to continue...")

输出:

Connecting
Connected
Executing ifconfig
b''

SSH进入服务器时的输出:

ssh -i TestInstanceKey.pem ec2-user@XXXXXXXXXX

       __|  __|_  )
       _|  (     /   Amazon Linux AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-ami/2016.09-release-notes/
22 package(s) needed for security, out of 67 available
Run "sudo yum update" to apply all updates.
Amazon Linux version 2017.09 is available.
[ec2-user@ip-XXXXXXXXX ~]$ ifconfig
eth0      Link encap:Ethernet  HWaddr XXXXXXXXXXX 
          inet addr:XXXXXXXXX  Bcast:Xxxxxxxxx.255  Mask:255.255.240.0
          inet6 addr: xxxxxxx Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
python amazon-web-services amazon-ec2 ssh paramiko
回答

我需要走完整的路。 因此,/ sbin / ifconfig不只是ifconfig。