SSH免密码登陆和免ip连接

2018-01-15  本文已影响0人  YellowLayne

1.本地设置

我们假设原来在~/.ssh目录下已经生成了一个密钥对:

id_rsa
id_rsa.pub

1.1 生成第二个key

接下来我们生成第二个ssh key:

ssh-keygen -t rsa -C "yourmail@mail.com"

这里不要一路回车,我们自己手动填写保存路径:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/layne/.ssh/id_rsa)): /home/layne/.ssh/id_rsa/id_rsa_server

<剩下两个直接回车>
这里我们用id_rsa_github来区别原有密钥对,避免被覆盖。
完成之后,我们可以看到~/.ssh目录下多了两个文件,变成:

id_rsa
id_ras.pub
id_rsa_server
id_rsa_server.pub
known_hosts

1.2 添加私钥

ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_server

如果提示文件或目录不存在,就使用绝对地址。

1.3 创建config文件

在~/.ssh目录下创建名为config的文件。
添加一下内容:

# gitlab
    Host git.example.com
    HostName git.example.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa

# server
    Host server-alias           # server-alias为SSH链接的服务器别名
    HostName server-ip  # 服务器地址
    Port 22
    User username           # 服务器端用户名
    PreferredAuthentications publickey 
    IdentityFile ~/.ssh/id_rsa_server   # 私钥地址,默认为 ~/.ssh/id_rsa

其中,Host和HostName填写服务器的域名。
IdentityFile指定私钥的路径。
在github和gitlab上添加公钥即可。

2.拷贝公钥

scp ~/.ssh/id_rsa_server.pub username@hostname.com:~/.ssh/
如果.ssh目录尚未建立,需要先创建并且修改权限:

3.服务器设置

mkdir ~/.ssh
chmod 700 ~/.ssh

如果authorized_keys文件是新创建的,需修改文件权限

chmod 600 ~/.ssh/authorized_keys

在服务器上添加公钥

cat ~/.ssh/id_rsa_server.pub >> ~/.ssh/authorized_keys 

验证是否设置成功

ssh username@server-ip
ssh server-alias

如果登录未成功,请仔细检查每项的配置是否正确。

https://www.jianshu.com/p/03effb53705c
https://www.awaimai.com/2200.html

上一篇 下一篇

猜你喜欢

热点阅读