2017-02-06 91 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