Linux-ssh的rsa認證登錄配置


首先看一下實驗環境:

 

[root@localhost ~]# cat /proc/version #ip 192.168.254.130
Linux version 2.6.32-431.el6.x86_64 (mockbuild@c6b8.bsys.dev.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) ) #1 SMP Fri Nov 22 03:15:09 UTC 2013
[root@wulaoer ~]# cat /proc/version   #ip 192.168.254.131
Linux version 2.6.32-431.el6.x86_64 (mockbuild@c6b8.bsys.dev.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) ) #1 SMP Fri Nov 22 03:15:09 UTC 2013
wlof@wlof-virtual-machine:~$ sudo cat /proc/version #192.168.254.129
[sudo] wlof 的密碼: 
Linux version 4.2.0-16-generic (buildd@lcy01-07) (gcc version 5.2.1 20151003 (Ubuntu 5.2.1-21ubuntu2) ) #19-Ubuntu SMP Thu Oct 8 15:35:06 UTC 2015

 

兩台centos和一台ubuntu,兩台centos版本相同,為了區分我把每台的用戶用紅色進行區分。如果你的是剛剛安裝的系統那就需要你安裝ssh,centos直接yum -y install ssh 如果是ubuntu的話就用sudo apt-get install openssh-server很簡單的,一條命令執行就可以了。

第一:密鑰生成  

[root@wulaoer ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.  #私鑰文件
Your public key has been saved in /root/.ssh/id_rsa.pub.  #公鑰文件
The key fingerprint is:
8e:5f:78:ca:fc:79:cc:e0:c7:18:2a:31:2f:0a:8d:40 root@wulaoer
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
| E               |
|.                |
|.       S        |
| . o  oo .o      |
|  o . .+oooB     |
|   .  o+o+o.*    |
|    .. o=.oo     |
+-----------------+
[root@wulaoer ~]# cd /root/.ssh/ #如果是ubuntu的話是家目錄下的用戶名下的.ssh目錄下。
[root@wulaoer .ssh]# ls
id_rsa  id_rsa.pub

第二:可以直接在本地修改公鑰文件名也可以在傳送的過程修改,這個根據自己習慣。

[root@wulaoer .ssh]# ll
總用量 12
-rw-------. 1 root root 1675 5月  12 23:10 id_rsa
-rw-r--r--. 1 root root  394 5月  12 23:10 id_rsa.pub
-rw-r--r--. 1 root root  397 5月  12 20:13 known_hosts
[root@wulaoer .ssh]# mv id_rsa.pub authorized_keys   #或者
[root@wulaoer .ssh]# scp -r authorized_keys 192.168.254.130:/root/.ssh/
root@192.168.254.130's password: 
authorized_keys 100% 394 0.4KB/s 00:00

第三:測試直接登錄看一下需不需要使用密碼。

[root@wulaoer .ssh]# ssh 192.168.254.130
Last login: Fri May 13 00:28:12 2016 from 192.168.254.131
[root@localhost ~]# 

這里需要注意下,主機名已經發送變化,說明已經登錄成功。  

一台機器名wulaoe和一台ubuntu同時免密碼登錄localhost,wulaoer已經設置好了,下面是設置ubuntu。

wlof@wlof-virtual-machine:~$ cd /home/wlof/.ssh/  #這里的wolf是我的用戶名下的家目錄
wlof@wlof-virtual-machine:~/.ssh$ ls
known_hosts
wlof@wlof-virtual-machine:~/.ssh$ ssh-keygen -t rsa #如果這里要是加sudo的話認證的用戶就是root了,要看一下認證文件的路徑
Generating public/private rsa key pair.
Enter file in which to save the key (/home/wlof/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/wlof/.ssh/id_rsa.   #私鑰文件路徑
Your public key has been saved in /home/wlof/.ssh/id_rsa.pub.  #公鑰文件路徑
The key fingerprint is:
SHA256:fE+oB2MQ4GFwWa4Misx8BsTTPRBtcztHWgkoUA/G78A wlof@wlof-virtual-machine
The key's randomart image is:
+---[RSA 2048]----+
|.o*BX++.. . |
|.o.B+X o + |
| .+ =.* = |
|=..E o * . . |
|o+ o= S o . |
| o . . = o |
| . . . |
| . |
| |
+----[SHA256]-----+
wlof@wlof-virtual-machine:~/.ssh$ ls
id_rsa id_rsa.pub known_hosts

ssh驗證測試

wlof@wlof-virtual-machine:~/.ssh$ scp -r id_rsa.pub root@192.168.254.130:/root/.ssh/authorized_keys  #在這里要注意必須要在連接的IP前加root@,要不系統默認會用當前用戶名,在這里已經要用追加的方式加進去        
root@192.168.254.130's password: 
id_rsa.pub                            100%  407     0.4KB/s   00:00    
wlof@wlof-virtual-machine:~/.ssh$ ssh 192.168.254.130
wlof@192.168.254.130's password: 

wlof@wlof-virtual-machine:~/.ssh$ ssh root@192.168.254.130
Last login: Fri May 13 00:28:44 2016 from 192.168.254.131
[root@localhost ~]#     #主機名已經切換過來,說明登錄成功

一台登錄多台設置,現在兩台centos已經可以相互之間直接登錄,現在讓ubuntu直接訪問兩台centos。

首先把ubuntu的公鑰復制到兩台centos上:

wolf@wolf-virtual-machine:~$ cd /home/wolf/.ssh/
wolf@wolf-virtual-machine:~/.ssh$ ls
id_rsa  id_rsa.pub  known_hosts
wolf@wolf-virtual-machine:~/.ssh$ scp -r id_rsa.pub root@192.168.254.130:/root/.ssh/authorized_keyss     #復制到130上,這里為了和131的公鑰區分我在后邊多加了一個‘s’   
root@192.168.254.130's password: 
id_rsa.pub                                                             100%  407     0.4KB/s   00:00    
wolf@wolf-virtual-machine:~/.ssh$ scp -r id_rsa.pub root@192.168.254.131:/root/.ssh/authorized_keyss      #復制到131上,同上  
The authenticity of host '192.168.254.131 (192.168.254.131)' can't be established.
RSA key fingerprint is SHA256:tzpgk9Y/bBiToYmQz3URfDxUKseZ739+kk4TKuDBa5U.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.254.131' (RSA) to the list of known hosts.
root@192.168.254.131's password: 
id_rsa.pub        

下面就需要在兩個centos里設置了,把ubuntu的公鑰追加到authorized_keys里,記得是追加不是覆蓋。

[root@localhost .ssh]# cat authorized_keyss >> authorized_keys    #130上的公鑰追加
[root@localhost .ssh]# cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAriBZExBXEVl6lzlP5e+ZipchsKQUN9CXQ/oP+tJsfSu8pVt+u1EA8bzNBFg8wSTLqkWIXw9Ko+soPu3cuUzf3ChGWxyutIjYIDbzQ8dm/Ikns6UYGbFAKBmzm+K+mdxKlRvc0DlfM4mBmXwGvp5Mu4bmOU5tBcXxeBACduv4hFwi3fHZ7Kk5WNCuuhHsSmC9udhOTd9eohaY243hYMf7DXssUqR3jltk6Lyl7Cty9/a9Qh/U42/VEEmJ8LaWscRcViLLHv+CCXTlp5s5p9N2HIByHYRQI179hIvZqnmT4GLNpX6vweLWAOqNIragjqUf7PeZxOBhxSQaTNrJJdm71w== root@localhost.localdomain
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVul880Bj7HmbtObRXODujHNjpYa65dfr+D+k03KL9Woij77jj7oLhpdMk80bINGftCkY612Ou/xCNjPB07UNa1uyoSuXZxGZX4k+f0N4JS9R2qUw9aJKlpciohLrPItXo+Syq7TUOGfi9mB/WoF1aAPdCWYhO8J+J8voFjoAqFDlONzId/xBdELGLBSv6FUG1O2YDVyvHnlrfalxSZvSKdpM/dl8KdogZ8qjDGbLKkkYg7be+na9RRnMt/L8I+Dvww/sxpdZ7JHn23nxkf4Yrln88jcUrJDxYChchD/JBHtV2mFg32w1FPQ2Y3lPSpW6GriQWHc5qeRuGg7JkT1sN wolf@wolf-virtual-machine

在后面查看的時候可以看出是兩個公鑰了,131上的設置同上,。

[root@wulaoer .ssh]# cat authorized_keyss >> authorized_keys
[root@wulaoer .ssh]# cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEArcYpkcSlOgMWzeihri9aFkQC0ggV8s/lhycAo04UuEBhkFVCOk/y3mEXK+16LgHaCekrKyXQakKfRo8/Qdkl87gSFTgU9thA+bMAPf6hwCbHQ4t0Hi+4d0I/rQrI3MTsDNxXGzMfH1w7ZpV6DkYlQ4gcGRGaywyryyuBgypsxsG2ejlZ8Zaa6nv+VYhRe5CzzwC8tCkgCJ6fXGfCP8LWxOPTKKg9AwmIEceuJe0PErrZNADCBmqOGsY/jx6hFqeUNN38QllIta7H9dfogcWsYCEm1PxfDrkBu/eX8qS9qHc5YU64akN1uojPE4Ar5vsT3A083cyiu7Eo91X7T+s1mw== root@localhost.localdomain
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVul880Bj7HmbtObRXODujHNjpYa65dfr+D+k03KL9Woij77jj7oLhpdMk80bINGftCkY612Ou/xCNjPB07UNa1uyoSuXZxGZX4k+f0N4JS9R2qUw9aJKlpciohLrPItXo+Syq7TUOGfi9mB/WoF1aAPdCWYhO8J+J8voFjoAqFDlONzId/xBdELGLBSv6FUG1O2YDVyvHnlrfalxSZvSKdpM/dl8KdogZ8qjDGbLKkkYg7be+na9RRnMt/L8I+Dvww/sxpdZ7JHn23nxkf4Yrln88jcUrJDxYChchD/JBHtV2mFg32w1FPQ2Y3lPSpW6GriQWHc5qeRuGg7JkT1sN wolf@wolf-virtual-machine

實驗結構測試,在ubuntu上直接登錄兩個不同的centos:

wolf@wolf-virtual-machine:~/.ssh$ ssh root@192.168.254.130    #登錄到130上了
Last login: Fri May 13 16:09:15 2016 from 192.168.254.131
[root@localhost ~]# ls
anaconda-ks.cfg              install.log         Python-2.7.3          rdo-release-liberty-3.noarch.rpm
epel-release-6-8.noarch.rpm  install.log.syslog  Python-2.7.3.tar.bz2
[root@localhost ~]# exit
logout
Connection to 192.168.254.130 closed.
wolf@wolf-virtual-machine:~/.ssh$ ssh root@192.168.254.131    #登錄到131上了
Last login: Sat May 14 00:06:54 2016 from 192.168.254.1
[root@wulaoer ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog

以下是關於sshd服務端的配置詳解ubuntu和centos的文件都一樣,這里以centos為例:

[root@localhost ~]# vi /etc/ssh/sshd_config     #ssh的主配置文件,基本的ssh相關設置都在這里

#       $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options change a
# default value.

#Port 22                                     #sshd服務默認的端口22,為了安全建議修改成其它端口
#AddressFamily any
#ListenAddress 0.0.0.0                        #監聽的主機,可以監聽所有的ssh連接
#ListenAddress ::

# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2                                    #ssh的協議版本,這里是2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h                    #每個一個小時重新建立一次連接,這里沒有開啟
#ServerKeyBits 1024                            #server key的長度

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV                        #當有人使用ssh登入系統的時候,ssh會記錄信息
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin yes                        #是否允許root登錄,默認是允許的,建議設置成no
#StrictModes yes                            #當使用者的host key改變之后,server就不接受其它連接
#MaxAuthTries 6                                #最多root嘗試6次連接
#MaxSessions 10

#RSAAuthentication yes                        #是否使用rsa認證,只針對version1
#PubkeyAuthentication yes                    #是否允許public key,只針對version2
#AuthorizedKeysFile     .ssh/authorized_keys    #認證文件,客戶端連接過來的公鑰默認文件命
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no                    #是否僅適用於rhost認證,為了安全一定設置為否
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no                    #是否忽略掉~/.shosts files中的用戶
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes                    #是否需要密碼認證
#PermitEmptyPasswords no                    #不允許空密碼
PasswordAuthentication yes                    #開啟密碼認證

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no            #不挑戰任何的密碼認證,任何login.conf規定的認證方式,都禁用

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
#GSSAPIAuthentication no
GSSAPIAuthentication yes
#GSSAPICleanupCredentials yes
GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no                                    #啟用pam模塊
UsePAM yes

# Accept locale-related environment variables        #環境變量
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes                            #登錄后是否顯示一些默認信息
#PrintLastLog yes                        #顯示上次登錄的信息
#TCPKeepAlive yes                        #ssh server會傳keepalive信息給client以此確保兩者的聯機正常,任何一斷死后。馬上斷開
#UseLogin no
#UsePrivilegeSeparation yes                #使用者的權限設定
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem       sftp    /usr/libexec/openssh/sftp-server        #sftp服務的設置

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       ForceCommand cvs server            
sshd服務端配置

以下是關於ssh客戶端的文件

[root@localhost ~]# vi /etc/ssh/ssh_config 

#       $OpenBSD: ssh_config,v 1.25 2009/02/17 01:28:32 djm Exp $

# This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

# Host *                                #只匹配設定的主機,這里默認是匹配所有的主機
#   ForwardAgent no                        #連接是否經過驗證代理
#   ForwardX11 no                        #x11連接是否被自動重定向到安全的通道和顯示集;
#   RhostsRSAAuthentication no            #是否使用rsa算法的基於rhosts的安全驗證
#   RSAAuthentication yes                #是否使用rsa算法驗證
#   PasswordAuthentication yes            #是否使用密碼驗證
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   GSSAPIKeyExchange no
#   GSSAPITrustDNS no
#   BatchMode no
#   CheckHostIP yes                        #是否驗證ip
#   AddressFamily any
#   ConnectTimeout 0                    #連接超時時間
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   Port 22                                #連接遠程主機的端口
#   Protocol 2,1                        #采用的協議版本
#   Cipher 3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160
#   EscapeChar ~                        #設置escape字符
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
Host *
        GSSAPIAuthentication yes
# If this option is set to yes then remote X11 clients will have full access
# to the original X11 display. As virtually no X11 client supports the untrusted
# mode correctly we set this to yes.
        ForwardX11Trusted yes
# Send locale-related environment variables
        SendEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
        SendEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
        SendEnv LC_IDENTIFICATION LC_ALL LANGUAGE
        SendEnv XMODIFIERS
ssh客戶端配置文件

最后,說一下~/.ssh/known_hosts文件的作用

ssh 會把每個你訪問過的計算機的公鑰(public key)都記錄到~/.ssh/known_hosts文件中,當你下次訪問該計算機時,openss會核對公鑰。如果公鑰不同,那openssh就會發出警告,避免你收到DNSHijack等攻擊


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM