实验:ssh免密码登录

椰子ya Linux 2020-09-05

模拟实验通过密钥免密码登录
ssh密钥登录.png
服务端IP:39.105.28.110
客户端IP:120.92.211.10

1.首先在客户端创建密钥
-t 指定密钥类型,默认是 rsa ,可以省略。
-C 设置注释文字,比如邮箱。
-f 指定密钥文件存储文件名。

[root@liukai ~]#ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):    //回车
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:
SHA256:DffrB1rtctrvyfGiiB6E2kFNlQR7Je8O5wL7Zzsw5OQ root@liukai
The key's randomart image is:
+---[RSA 3072]----+
|        o++..    |
|       o ..+     |
|      . + o .    |
|     . . =oo     |
|      o S=o +.   |
|     o o oE=o..  |
|    . . o .=+o . |
|         +.+=.* +|
|       .o oo=O.*+|
+----[SHA256]-----+

[root@liukai .ssh]#cd .ssh/            //跳转到存放目录通过ls可以看到生成的密钥
[root@liukai .ssh]# ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts

2.将公钥上传到客户端

[root@liukai .ssh]# scp id_rsa.pub  root@39.105.28.110:    //通过scp拷贝至服务端用户根目录
root@39.105.28.140's password:                             //输入服务端密码

3.在服务端查看ssh配置文件,方便后续配置。(星号部分为本次实验需要注意的)

[root@liukai ~]# cat /etc/ssh/sshd_config 
#    $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj 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:/usr/bin:/usr/local/sbin:/usr/sbin

# 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 override the
# default value.

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
#Port 22                         //端口
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# System-wide Crypto policy:
# This system is following system-wide crypto policy. The changes to
# Ciphers, MACs, KexAlgoritms and GSSAPIKexAlgorithsm will not have any
# effect here. They will be overridden by command-line options passed on
# the server start up.
# To opt out, uncomment a line with redefinition of  CRYPTO_POLICY=
# variable in  /etc/sysconfig/sshd  to overwrite the policy.
# For more information, see manual page for update-crypto-policies(8).

# Logging
#SyslogFacility AUTH

#LogLevel INFO

# Authentication:

#LoginGraceTime 2m

#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

**PubkeyAuthentication yes**

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
**AuthorizedKeysFile    .ssh/authorized_keys**

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PermitEmptyPasswords no


# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

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

# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users 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
# 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
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Fedora and may cause several
# problems.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes

# It is recommended to use pam_motd in /etc/pam.d/sshd instead of PrintMotd,
# as it is more configurable and versatile than the built-in version.
PrintMotd no

#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# 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

# override default of no subsystems
Subsystem    sftp    /usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#    X11Forwarding no
#    AllowTcpForwarding no
#    PermitTTY no
#    ForceCommand cvs server

UseDNS no
AddressFamily inet
SyslogFacility AUTHPRIV
**PermitRootLogin yes**          //是否允许root登录
PasswordAuthentication yes

4.在用户目录下查看,公钥是否上传成功,将上传的公钥添加到authorized_keys中

[root@liukai ~]# ls
id_rsa.pub            //上传成功

[root@liukai ~]# cat id_rsa.pub >>.ssh/authorized_keys   //添加

5.修改权限,并重启服务

[root@liukai ~]chmod 700 /root               //权限可能导致无法免密码登录
[root@liukai ~]chmod 700 .sshd
[root@liukai ~]chmod 600 authorized_key
[root@liukai ~]service sshd restart

6.在客户端测试测试

[root@liukai ~]# ssh root@39.105.28.110

Welcome to Alibaba Cloud Elastic Compute Service !

Activate the web console with: systemctl enable --now cockpit.socket

Last login: Sat Sep  5 15:37:53 2020 from 120.92.211.10
[root@liukai ~]#

试验成功Yes

PREV
滴滴 dd命令
NEXT
实验:Rsync镜像同步,可以通过rsync、crontab配合ssh定时备份重要数据到另一台服务器