2017-02-06 89 views
1

在我用下面的步骤手动连接的那一刻:如何自动EC2实例启动和ssh连接

  1. 开放的EC2实例网络
  2. 操作 - >实例状态单击开始
  3. 连接标签
  4. 手动复制SSH命令例如: -

    ssh -i "mykey.pem" [email protected]

什么是最好的做法,这样我可以简化这些茎通过命令行中我的本地计算机?这样我就可以使用一个命令。

+0

您可以使用EC2的命令行。创建一个批处理或shell脚本。可以通过命令完成以下操作:启动,检查状态,无论是运行还是挂起,都会获得自动分配的dns名称。然后你可以在dns上发送ssh。请查看手册中的确切命令。我使用java,但你有很多选择。 – inquisitive

回答

3

awscli一种方法是

# Start the instance 
aws ec2 start-instances --instance-ids i-xxxxxxxxxxx 

status=0 

# Wait for the instance until the 2/2 checks are passed 
while [ $status -lt 2] 
do 
    status=`aws ec2 describe-instance-status --instance-ids i-xxxxxxxxxxx --filters Name="instance-status.reachability,Values=passed" | grep '"Status": "passed"' | wc -l` 
    # add sleep time 
done 

# Associate an Elastic IP if already have one allocated (skip if not reqd) 
aws ec2 associate-address --instance-id i-xxxxxxxxxxx --public-ip elastic_ip 

# Get the Public DNS, (If the instance has only PrivateIp, grep "PrivateIpAddress") 
public_dns=`aws ec2 describe-instances --instance-ids i-xxxxxxxxxxx | grep "PublicDnsName" | head -1 | awk -F: '{print $2}' | sed 's/\ "//g;s/",//g'` 

ssh -i key.pem [email protected]_dns 
+1

或者,分配一个** Elastic IP地址**并保持相同的IP地址,即使在实例停止/启动后(额外收费)。 –

+1

@JohnRotenstein,不确定OP是否需要它。将它添加到答案中,有人可能会觉得它有用。 – franklinsijo

+0

@JohnRotenstein如何添加*弹性IP地址*到franklinsijo的代码? – neversaint