如果有一台远端服务器,需要在本地连接,这里展示三种登录方式:
导航
1.服务器上生成秘钥对
$ ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
$ cp ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
其中
~/.ssh/id_rsa 即为自己的私钥文件
~/.ssh/authorized_keys存储客户端公钥文件,用于客户端免密登录
2.本地电脑登录
(1)使用密码登录
❯ ssh zhangsan@192.168.1.1 ─╯
zhangsan@192.168.1.1's password:
Last login: Fri Oct 27 16:15:21 2023 from 192.168.1.47
[zhangsan@centos8 ~]$
(2)使用公钥登录
A.本地(MAC电脑或者Linux电脑)生成秘钥对文件
$ ssh-keygen -t rsa -C "test@qq.com"
或者是
$ ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
B.Windows电脑可以考虑下载GitBash工具,打开即跟terminal一样操作。
C.将公钥上传至服务器(前提是可密码登录,此时需要输入登录密码)
$ ssh-copy-id -i ~/.ssh/id_rsa.pub -p 2222 username@host_ip
❯ ssh-copy-id -i ~/.ssh/id_rsa.pub -p 2222 zhangsan@192.168.1.1 ─╯
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/lisi/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
zhangsan@192.168.1.1's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -p '2222' 'zhangsan@192.168.1.1'"
and check to make sure that only the key(s) you wanted were added.
或者直接将 ~/.ssh/id_rsa.pub 文件里的内容追加拷贝到服务器端的 ~/.ssh/authorized_keys 里
完成以上操作后,即可免密登录远端服务器。
(3)使用私钥登录
将服务器端的~/.ssh/id_rsa文件拷贝到自己的本地,可以命名为zhangsan.id
$ chmod 600 zhangsan.id
$ ssh -i zhangsan.id zhangsan@192.168.1.1 -p 2222