2

When I connect to the AWS EC2 instance using ssh for the first time, I got an error like below because the host key is not stored in ssh known_hosts file.

The authenticity of host 'x.x.x.x' can't be established. ECDSA key fingerprint is xx:yy:.... Are you sure you want to continue connecting (yes/no)?

Now, I'm automating ssh. I often just add StrictHostKeyChecking option to ssh command to avoid this message. But, I feel that is not very safe way and possibly cause Man in the middle attack. Is there any (or good) way to get host key safely on AWS EC2?

sawa
  • 165,429
  • 45
  • 277
  • 381
Tsuneo Yoshioka
  • 7,504
  • 4
  • 36
  • 32
  • Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) or [Information Security Stack Exchange](http://security.stackexchange.com/) would be a better place to ask. – jww Oct 09 '17 at 15:23
  • IMO question is about programming because it is about automation. – xdhmoore Jul 19 '18 at 01:40

1 Answers1

3

I think the only way is to parse the console output.

#get the console output of the instance
aws ec2 get-console-output --instance-id <instance id> |\
#use jq to get the Output field
jq .Output -r |\
#use sed to find the interesting bits
sed -n -e '1,/-----BEGIN SSH HOST KEY KEYS-----/d; /-----END SSH HOST KEY KEYS-----/q; p'

Caveats, which might not matter depending on your application:

Community
  • 1
  • 1
nfirvine
  • 1,479
  • 12
  • 23