zoukankan      html  css  js  c++  java
  • 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等攻击

  • 相关阅读:
    保存会话数据——cookie学习
    HttpServletRequest学习
    HttpServletResponse 学习
    Servlet学习
    Http协议简单学习笔记
    利用tomcat配置网站
    PHPCMS-V9 获取一级栏目、二级栏目、三级栏目
    PHP判断当前访问的是 微信、iphone、android 浏览器
    二维数组根据某个字段排序
    动物界的再生一个故事
  • 原文地址:https://www.cnblogs.com/wulaoer/p/5486579.html
Copyright © 2011-2022 走看看