少点错误 04月17日 23:17
Host Keys and SSHing to EC2
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

文章分享了在EC2实例上使用SSH连接时遇到的问题,即每次实例启动都会获得新的主机名,导致SSH的“首次信任”机制失效。作者通过修改`~/.ssh/known_hosts`文件,为EC2主机添加别名,并在SSH脚本中设置`HostKeyAlias`,解决了这个问题,提高了连接的安全性和便利性。

🔑 每次启动EC2实例时,由于其主机名(由IP地址派生)会发生变化,导致SSH的“首次信任”机制无法正常工作,每次连接都需要确认主机身份。

🛠️ 解决该问题的方法是编辑`~/.ssh/known_hosts`文件,为每个常用的EC2主机添加一个条目,并使用一个别名。例如,将`ec2-44-222-215-215.compute-1.amazonaws.com`的SSH密钥复制一份,并将其别名设置为`ec2nf`。

⚙️ 进一步,修改SSH脚本,添加`-o "StrictHostKeyChecking=yes" -o "HostKeyAlias=ec2nf"`参数,明确指定使用`ec2nf`作为主机密钥别名,从而实现更安全、更便捷的连接方式。

Published on April 17, 2025 3:10 PM GMT

I do a lot of work on EC2, where I ssh into a few instances Iuse for specific purposes. Each time I did this I'd get a promptlike:

$ ssh_ec2nfThe authenticity of host 'ec2-54-224-39-217.compute-1.amazonaws.com(54.224.39.217)' can't be established.ED25519 key fingerprint is SHA256:...This host key is known by the following other names/addresses:    ~/.ssh/known_hosts:591: ec2-18-208-226-191.compute-1.amazonaws.com    ~/.ssh/known_hosts:594: ec2-54-162-24-54.compute-1.amazonaws.com    ~/.ssh/known_hosts:595: ec2-54-92-171-153.compute-1.amazonaws.com    ~/.ssh/known_hosts:596: ec2-3-88-72-156.compute-1.amazonaws.com    ~/.ssh/known_hosts:598: ec2-3-82-12-101.compute-1.amazonaws.com    ~/.ssh/known_hosts:600: ec2-3-94-81-150.compute-1.amazonaws.com    ~/.ssh/known_hosts:601: ec2-18-234-179-96.compute-1.amazonaws.com    ~/.ssh/known_hosts:602: ec2-18-232-154-156.compute-1.amazonaws.com    (185 additional names omitted)Are you sure you want to continue connecting (yes/no/[fingerprint])?

The issue is that each time I start my instance it gets a new hostname(which is just derived from the IP) and so SSH's trust on firstuse doesn't work properly.

Checking that "185 additional names omitted" is about the number I'dexpect to see is ok, but not great. And it delays login.

I figured out how to fix this today:

    Edit ~/.ssh/known_hosts to add an entry for eachEC2 host I use under my alias for it. So I havec2-44-222-215-215.compute-1.amazonaws.com ssh-ed25519AAAA... and I duplicate that to add ec2nf ssh-ed25519AAAA... etc.

    Modify my ec2ssh script to set HostKeyAlias:ssh -o "StrictHostKeyChecking=yes" -o "HostKeyAlias=ec2nf"...

More secure and more convenient!

(What got me to fix this was an interaction with my auto-shutdownscript, where if I did start_ec2nf && sleep 20 &&ssh_ec2nf but then went and did something else for a minute ortwo the machine would often turn itself off before I came back and gotaround to saying yes.)

Comment via: facebook, mastodon, bluesky



Discuss

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

EC2 SSH known_hosts HostKeyAlias
相关文章