Ubuntu SSH更新密钥的完整步骤
更新SSH密钥对是保障服务器安全的重要操作,以下是详细流程(适用于Ubuntu客户端和服务器):
在本地Ubuntu机器上,使用ssh-keygen命令生成新的密钥对(替换your_email@example.com为你的标识,如姓名或项目名):
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
~/.ssh/id_rsa(私钥)和~/.ssh/id_rsa.pub(公钥),可直接按Enter使用默认路径;若需自定义,输入新路径(如~/.ssh/new_key)。Enter留空。使用ssh-copy-id命令将新公钥自动复制到服务器的~/.ssh/authorized_keys文件中(替换username为服务器用户名,server_ip为服务器IP地址,~/.ssh/new_key.pub为新公钥路径):
ssh-copy-id -i ~/.ssh/new_key.pub username@server_ip
执行后会提示输入服务器用户的密码,输入后公钥会自动追加到服务器的authorized_keys文件中。
使用新密钥测试SSH连接(替换username和server_ip):
ssh -i ~/.ssh/new_key username@server_ip
测试通过后,为避免旧密钥泄露风险,建议删除本地旧密钥(替换id_rsa和id_rsa.pub为旧密钥文件名):
rm ~/.ssh/id_rsa ~/.ssh/id_rsa.pub
若旧密钥仍在authorized_keys文件中,需登录服务器删除对应公钥(替换username和server_ip):
ssh username@server_ip "sed -i '/旧公钥内容的/d' ~/.ssh/authorized_keys"
(注:需将“旧公钥内容”替换为实际旧公钥的完整字符串,可通过cat ~/.ssh/old_key.pub查看)。
~/.ssh目录权限为700(chmod 700 ~/.ssh),authorized_keys文件权限为600(chmod 600 ~/.ssh/authorized_keys),否则可能导致密钥认证失败。/etc/ssh/sshd_config文件,将PasswordAuthentication yes改为no,然后重启SSH服务:sudo systemctl restart ssh)。通过以上步骤,即可完成Ubuntu SSH密钥的更新,确保服务器访问的安全性。