SSH配置Linux免密登录

有一台Linux服务器,当我在本地的电脑上通过git上传代码到这台Linux服务器时,希望实现免密登录,就需要用到SSH秘钥,

首先,你需要确认自己是否已经拥有密钥。 默认情况下,用户的 SSH 密钥存储在其 ~/.ssh 目录下,打开git,输入命令:

$ cd ~/.ssh
$ ls
id_dsa  id_dsa.pub  known_hosts 

其中id_dsa 是私钥,id_dsa .pub是你的公钥,如果找不到这样的文件(或者根本没有 .ssh 目录),你可以通过运行 ssh-keygen 程序来创建它们:

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/schacon/.ssh/id_rsa):
Created directory "/home/schacon/.ssh".
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/schacon/.ssh/id_rsa.
Your public key has been saved in /home/schacon/.ssh/id_rsa.pub.
The key fingerprint is:
d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 schacon@mylaptop.local

首先 ssh-keygen 会确认密钥的存储位置(默认是 .ssh/id_rsa),然后它会要求你输入两次密钥口令。如果你不想在使用密钥时输入口令,将其留空即可。

 查看公钥具体内容:

$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU
GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3
Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA
t3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En
mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx
NrRFi9wrf+M7Q== schacon@mylaptop.local

然后就是远程免密登录的配置,介绍两种常用方法:

方法一:

通过 ssh-copy-id 命令设置,最后一个参数是我们要免密钥登录的服务器 ip 地址。

ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.1.1

方法二:

通过手工复制,将本地 id_rsa.pub 文件的内容复制到远程服务器的 /.ssh/authorized_keys 文件中也完全可以的

$ cd .ssh
$ ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts
$ vi authorized_keys 

到此,SSH免密钥登录就大功告成。