Linux ssh公钥写入

  1. 生成密钥对
1
ssh-keygen -t rsa -b 4096 -f ./id_rsa -C "your_comment"

当前路径会生成id_rsa和id_rsa.pub

  1. 上传公钥到靶机
1
2
3
cat /tmp/pub > ~/.ssh/authorized_keys
chmod 600 authorized_keys
chmod 700 .ssh
  1. 验证有效性
1
ssh-keygen -l -f authorized_keys
  1. 修改ssh配置
1
2
3
4
5
sed -i \
-e 's/^#*PermitRootLogin.*/PermitRootLogin yes/' \
-e 's/^#*PubkeyAuthentication.*/PubkeyAuthentication yes/' \
-e 's/^#*PasswordAuthentication.*/PasswordAuthentication no/' \
/etc/ssh/sshd_config
  1. 重启ssh
1
2
3
4
systemctl restart sshd
systemctl restart ssh
service sshd restart
service ssh restart

ssh使用私钥连接命令:

1
2
3
4
5
ssh -i ./id_rsa \
-o PreferredAuthentications=publickey \
-o HostKeyAlgorithms=ecdsa-sha2-nistp256,ssh-rsa \
-o PubkeyAcceptedAlgorithms=+ssh-rsa \
root@192.168.234.139