为什么boto3的connect方法中的主机名不接受变量值

时间:2018-12-27 17:25:24

标签: python-3.x amazon-web-services

此代码有什么问题? boto3的hostname方法中的connect不接受变量值

import boto3
import paramiko
import time
from collections import defaultdict


class Instance:
  def __init__(self):
    self.ec2 = boto3.resource('ec2', aws_access_key_id = "AKIAJDYFPVWG2FDFFUTQ", aws_secret_access_key = "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", region_name='ap-south-1')
    self.vpc = self.ec2.Vpc('vpc-09d0e1e9ebd43cdc8')
    self.memory = input("Enter quantity of memory you want (Min =8gb): ")
    self.instanceid = 'i-0a4edec7e97bf1157'



  def createInstances(self):
     response = self.ec2.create_instances(
         BlockDeviceMappings=[
        {
        'DeviceName': '/dev/xvda',
        'Ebs': {

            'DeleteOnTermination': True,
            'VolumeSize': int(self.memory),
            'VolumeType': 'gp2'
           },
       },
     ],
         UserData = open("E:\Python\Project\config").read(),
         ImageId='ami-0ad42f4f66f6c1cc9',
         InstanceType='t2.micro',
         MaxCount=1,
         MinCount=1,
         KeyName = 'sarthak',
         NetworkInterfaces = [{'DeviceIndex': 0,'SubnetId':'subnet-00ae76e793a3b3b41','Groups':[
    'sg-05d357fbdf6d60ccc'
         ],'AssociatePublicIpAddress':True}],
    )
     self.ec2.create_tags(Resources = [response[0].id], Tags = [{'Key': 'Name', 'Value': 'WebServerdemo'}])
     self.instanceid = response[0].instance_id
     print(self.instanceid)
     print("Created")

  def connect_to_instance(self):
    key = paramiko.RSAKey.from_private_key_file('C:\\Users\\Rishabh\\Desktop\\Inframind\\sarthak.pem')
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ec2info = defaultdict()

    instances = self.ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
    for instance in instances:
        if(instance.id == self.instanceid):
            ec2info[instance.id] = {
            'Public IP': instance.public_ip_address,
        }
    attributes = ['Public IP']
    for self.instanceid, instance in ec2info.items():
        for key in attributes:
            hostname = instance[key]

    try:
        # Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2
        client.connect(hostname= hostname, username="ec2-user", pkey=key)
        print("connected")

        # Execute a command(cmd) after connecting/ssh to an instance
        print("Enter the command you want to execute or enter exit:")
        flag = 1
        while (flag == 1):
            command = input("Commmand: ")
            # close the client connection once the job is done
            if command in ("exit", "logout"):
                client.close()
                flag = 0
            else:
                stdin, stdout, stderr = client.exec_command(command)
                print(stdout.readlines())

    except Exception as e:
        print(e)

0 个答案:

没有答案