删除服务器上的ssh授权密钥的命令


30

是否有命令(或单线)来删除服务器上的ssh密钥?类似于ssh-copy-id的东西吗?


2
一些SSH服务器软件支持用于管理授权SSH密钥的RFC 4819协议,但是非常罕见,它在Linux上几乎不存在:(
grawity 2012年

3
很好的问题,这确实是ssh-copy-id缺少用于促进密钥旋转的功能。
Zabuzzman

1
值得注意的是,ssh-keygen确实提供了-R从中删除密钥选项known_hosts,但遗憾的ssh-keygen -R <HOSTNAME> -f ~/.ssh/authorized_keys是它不起作用。我会改用sed下面的选项。
Digital Trauma

Answers:


10

正如Ignatio所建议的,可以使用来完成grep -v

这是一个删除包含密钥some unique string或仅authorized_keys在没有其他密钥的情况下删除文件的示例。

if test -f $HOME/.ssh/authorized_keys; then
  if grep -v "some unique string" $HOME/.ssh/authorized_keys > $HOME/.ssh/tmp; then
    cat $HOME/.ssh/tmp > $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp;
  else
    rm $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp;
  fi;
fi

替换some unique string为仅在您要删除的密钥中存在的密钥。

作为ssh的oneliner,这成为

ssh hostname 'if test -f $HOME/.ssh/authorized_keys; then if grep -v "some unique string" $HOME/.ssh/authorized_keys > $HOME/.ssh/tmp; then cat $HOME/.ssh/tmp > $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp; else rm $HOME/.ssh/authorized_keys && rm $HOME/.ssh/tmp; fi; fi'

在Linux(SLES)和HP-UX上进行了测试。


2
看到下面的答案:sed更好地做到这一点
woohoo '16

25

sed 提供了一个紧凑的解决方案:

sed -i.bak '/REGEX_MATCHING_KEY/d' ~/.ssh/authorized_keys

这会将原始文件保存在authorized_keysauthorized_keys.bak。如果您不希望备份,则只需更改-i.bak为即可-i

您甚至可以删除多个键:

sed -i.bak '/REGEX1/d; /REGEX2/d' ~/.ssh/authorized_keys

唯一棘手的地方是正则表达式中的特殊字符需要转义


如果仅在公共密钥文件中使用base64字符(例如awk '{print $2}' ~/.ssh/id_rsa.pub),则无需担心转义任何特殊字符。
胡安(Juan)


0

菲尔(Phil)已经回答了这个问题,但我想做加法,让您更轻松。并且由于您要反向输入ssh-copy-id,因此我假设您要在授权计算机上运行它。

ssh密钥仅包含base64字符。因此,您可以使用不在该列表中的char作为sed分隔符。让我们使用“#”。

ssh root@<hostname> -o PasswordAuthentication=no "sed -i.bak 's#`cat ~/.ssh/id_rsa.pub`##' ~/.ssh/authorized_keys"

用服务器IP替换主机名。

如果要求输入密码,PasswordAuthentication选项将导致ssh失败


pub键中的“注释”可能没有base64字符。如果它带有“#”,那么您的示例将中断。也许使用awk '{print $2}' ~/.ssh/id_rsa.pub一些sedgrep -v代替。
胡安(Juan)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.