内容:

1、openssh的介绍和使用

    (1)sshd的服务端配置

    (2)基于密钥登陆ssh的使用

    (3)scp的使用

    (4)rsync的使用

2、sudo的介绍和配置使用


一、openssh

        OpenSSH与SSH协议是远程登录的首选连接工具。它加密所有流量,以消除窃听,连接劫持和其它***。

    OpenSSH的套件包括以下工具:

    远程操作使用 SSH, SCP,和 SFTP。

    密钥管理 ssh-add, ssh-keysign, ssh-keyscan和ssh-keygen

    服务端组成 sshd, SFTP服务器和 ssh-agent的。

    因此我们使用的ssh只是openssh的其中一个工具

    1、ssh

        ssh服务是C/S架构,分为客户端和服务端,都有各自的配置文件,ssh的登陆支持两种方式,一个传统的密码登陆,一种是基于密钥的登陆,下面会详细介绍

        (1)sshd(server),sshd是ssh服务端的进程,默认开机会自动运行,可以在/etc/init.d目录下看到该开机服务脚本sshd

[11:35 root@centos6.8/etc/ssh]# ll /etc/init.d/sshd 
-rwxr-xr-x. 1 root root 4621 May 11 07:10 /etc/init.d/sshd

        sshd的配置文件位于/etc/ssh的目录下,该目录其实还包括的客户端的配置文件,其中pub结尾的文件表示存放公钥,对于的是私钥,其权限是严格控制的

[11:43 root@centos6.8/etc/ssh]# ll
total 156
-rw-------. 1 root root 125811 May 11 07:10 moduli
-rw-r--r--. 1 root root   2047 May 11 07:10 ssh_config
-rw-------. 1 root root   3879 May 11 07:10 sshd_config
-rw-------. 1 root root    668 Sep 17 18:29 ssh_host_dsa_key
-rw-r--r--. 1 root root    590 Sep 17 18:29 ssh_host_dsa_key.pub
-rw-------. 1 root root    963 Sep 17 18:29 ssh_host_key
-rw-r--r--. 1 root root    627 Sep 17 18:29 ssh_host_key.pub
-rw-------. 1 root root   1675 Sep 17 18:29 ssh_host_rsa_key
-rw-r--r--. 1 root root    382 Sep 17 18:29 ssh_host_rsa_key.pub


        查看sshd的配置文件:

[12:14 root@centos6.8/etc/ssh]# cat sshd_config 
#       $OpenBSD: sshd_config,v 1.93 2014/01/10 05:59:19 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:/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 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
#这里默认端口是22,可以改成其他端口,在作为服务器使用事建议改为其他端口,不要监听默认端口,不要监听默认端口,不要监听默认端口
#AddressFamily any
ListenAddress 0.0.0.0
#这里0.0.0.0代表监听在本机的所有地址上
#ListenAddress ::
 
# The default requires explicit activation of protocol 1
#Protocol 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
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
 
# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024
 
# Ciphers and keying
#RekeyLimit default none
 
# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
 
#这是主机日志的记录方式。主机登录日志的位置在 /var/log/secure 
SyslogFacility AUTHPRIV
 
#LogLevel INFO
 
# Authentication:
 
#LoginGraceTime 2m
 
#PermitRootLogin yes
#这里表示是否允许管理员登录,改成no之后就只能允许普通用户登录
 
#StrictModes yes
#MaxAuthTries 6
#这是最大认证尝试次数,默认为6次
#MaxSessions 10
#这是最大会话数,默认10个
 
#RSAAuthentication yes
#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
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and 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!
#PasswordAuthentication yes
#PermitEmptyPasswords no
 
#这里表示是否支持口令认证
PasswordAuthentication yes
 
# 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
# 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'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM yes
 
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
UsePrivilegeSeparation sandbox          # Default for new installations.
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
 
#UseDNS no
#这里表示是否反解DNS,建议改为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
#支持sftp远程连接
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

        此配置#注释的有提示默认的设置值,包括默认端口、默认登陆时间等等,可以按需要来进行设置调整,注意:修改完配置后,要重启服务或reload配置才能生效!

    常用参数:

        Port

        ListenAddressip

        PermitRootLoginyes

        ClientAliveInterval0

        UseDNSyes

    限制可登录用户的办法:

        AllowUsers user1 user2 user3

        DenyUsers

        AllowGroups

        DenyGroups

一个安全的ssh服务器,应该进行严格的设置:
1、不要使用默认端口
2、禁止使用protocol version 1(在centos6、7版本的基本都是默认version2版本了)
3、限制可登录用户
4、设定空闲会话超时时长
5、利用防火墙设置ssh访问策略
6、仅监听特定的IP地址
7、使用基于密钥的认证
8、禁止使用空密码
9、禁止root用户直接登录
10、限制ssh的访问频度和并发在线数


    (2)ssh客户端的使用:

    语法:ssh[user@]host [COMMAND]

    ssh[-l user] host [COMMAND]

        -p port:远程服务器监听的端口

        -b:指定连接的源IP

        -v:调试模式

        -C:压缩方式

        -X: 支持x11转发

        -Y:支持信任x11转发

        -t: 强制伪tty分配

    其配置文件:

[root@localhost ssh]# vim /etc/ssh/ssh_config
 
#       $OpenBSD: ssh_config,v 1.28 2013/09/16 11:35:43 sthen 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 *
#选项“Host”只对能够匹配后面字串的计算机有效。“*”表示所有的计算机。
ForwardAgent no
#“ForwardAgent”设置连接是否经过验证代理(如果存在)转发给远程计算机。
ForwardX11 no
#“ForwardX11”设置X11连接是否被自动重定向到安全的通道和显示集(DISPLAY set)。
RhostsAuthentication no
#“RhostsAuthentication”设置是否使用基于rhosts的安全验证。
RhostsRSAAuthentication no
#“RhostsRSAAuthentication”设置是否使用用RSA算法的基于rhosts的安全验证。
RSAAuthentication yes
#“RSAAuthentication”设置是否使用RSA算法进行安全验证。
PasswordAuthentication yes
#“PasswordAuthentication”设置是否使用口令验证。
FallBackToRsh no
#“FallBackToRsh”设置如果用ssh连接出现错误是否自动使用rsh。
UseRsh no
#“UseRsh”设置是否在这台计算机上使用“rlogin/rsh”。
BatchMode no
#“BatchMode”如果设为“yes”,passphrase/password(交互式输入口令)的提示将被禁止。当不能交互式输入口令的时候,这个选项对脚本文件和批处理任务十分有用。
CheckHostIP yes
#“CheckHostIP”设置ssh是否查看连接到服务器的主机的IP地址以防止DNS欺骗。建议设置为“yes”。
StrictHostKeyChecking no
#“StrictHostKeyChecking”如果设置成“yes”,ssh就不会自动把计算机的密匙加入“$HOME/.ssh/known_hosts”文件,并且一旦计算机的密匙发生了变化,就拒绝连接。
IdentityFile ~/.ssh/identity
#“IdentityFile”设置从哪个文件读取用户的RSA安全验证标识。
Port 22
#“Port”设置连接到远程主机的端口。
Cipher blowfish
#“Cipher”设置加密用的密码。
EscapeChar ~
#“EscapeChar”设置escape字符。

        在这个配置文件中,我们一般只修port的端口,因为默认端口很容易受到***,ssh的默认端口为22号端口

    2、基于密钥认证登陆

        (1) 在客户端生成密钥对

        ssh-keygen -t rsa #默认会生成一对密钥,并保存至家目录的.ssh隐藏目录中

        (2) 把公钥文件传输至远程服务器对应用户的家目录

            ssh-copy-id [-i[identity_file]] [user@]host

        (3) 测试

        (4)重设私钥口令:#ssh-keygen –p

#生成密钥对
[root@localhost ~]# ssh-keygen  -t rsa #-t表示使用的加密类型,其中rsa1表示version1版本,rsa、dsa、ecdsa的加密对于的是version2版本
Generating public/private rsa key pair.
#这里询问你要把生成的密钥文件保存在哪里,默认是在家目录下的.ssh文件夹中,回车保存默认目录
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
#这里是对密钥文件加密,不输入则表示不加密
Enter passphrase (empty for no passphrase): 
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:
04:9f:cb:9c:9d:1e:47:d7:e1:d4:c1:87:71:c3:a4:22 root@localhost.localdomain
The key's randomart p_w_picpath is:
+--[ RSA 2048]----+
|      .       =O+|
|       o .    ===|
|        +E .....o|
|       + +.o..   |
|        S + .    |
|         . o     |
|          .      |
|                 |
|                 |
+-----------------+
#已经成功生成了一对密钥
[root@localhost ~]# ls /root/.ssh
id_rsa  id_rsa.pub
#其中id_rsa为私钥,id_rsa.pub为公钥
#在生成完密钥对之后将公钥上传给服务器对应用户的家目录
[root@localhost ~]# ssh-copy-id -i .ssh/id_rsa.pub root@172.18.0.9
The authenticity of host '172.18.0.9 (172.18.0.9)' can't be established.
ECDSA key fingerprint is 63:b9:6d:20:f0:22:b2:21:44:26:91:03:97:21:ff:b7.
Are you sure you want to continue connecting (yes/no)? yes       
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@172.18.0.9's password:
 
Number of key(s) added: 1
 
Now try logging into the machine, with:   "ssh 'root@172.18.0.9'"
and check to make sure that only the key(s) you wanted were added.
#第一次输入密码后回车就上传成功了
然后尝试登录
[root@localhost ~]# ssh 172.18.0.9
Last login: Tue Mar 22 10:01:02 2016 from 172.18.0.239
#可以看出不需要密钥就成功登录到了172.18.0.9这台服务器上了



3、scp:远程复制命令

        常用选项:

            -r: 递归复制;

            -p: 保持原文件的属性信息;

            -q: 静默模式

            -P PORT: 指明remote host的监听的端口;

        下载:scp    远程主机上的账户@远程主机:远程主机对应的文件    本机目录

[root@localhost ~]# scp -r root@172.16.9.9:/root/tmp /root

        上传:scp    本机文件    远程主机上的账户@远程主机:远程主机对应的目录

[root@localhost ~]# scp -r /root root@172.16.9.9:/root/tmp


4、rsync,功能与scp相似,都是具有复制功能,而且比scp更快,同时有一个特点,rsync只复制不同的文件

        使用安全的shell连接做为传输方式

        rsync –av /etc server1:/tmp 复制目录和目录下文件

    rsync –av /etc/ server1:/tmp 只复制目录下文件


        选项:

        -n 模拟复制过程

        -v 显示详细过程

        -r 递归复制目录树

        -p 保留权限

        -t 保留时间戳

        -g 保留组信息

        -o 保留所有者信息

        -l 把符号链接文件做为符号文件进行复制

        -L 将软链接文件指向文件复制

        -a 存档模式,相当于–rlptgoD,但不保留ACL(-A)和SELinux属性(-X)



二、sudo使用

        sudo:可以定义某用户以另一个用户的身份在某主机执行某命令(四个某),从而进一步提高的系统的安全性以及可追溯性

        (1)sudo作用:

        1.sudo能够授权指定用户在指定主机上运行某些命令。如果未授权用户尝试使用sudo,会提示联系管理员

        2.sudo可以提供日志,记录每个用户使用sudo操作

        3.sudo为系统管理员提供配置文件,允许系统管理员集中地管理用户的使用权限和使用的主机

        4.sudo使用时间戳文件来完成类似“检票”的系统,默认存活期为5分钟的“入场券”

        5.通过visudo命令编辑配置文件,具有语法检查功能

        其配置文件为/etc/sudoers,该文件权限有严格控制,所以不建议直接vim该文件进行编辑,sudo提供了专门的具有语法检测的编辑工具:visudo

        visudo编辑格式:who which_host=(who_runs) command

[15:16 root@centos6.8~]# ll /etc/sudoers
-r--r-----. 1 root root 3729 Dec  8  2015 /etc/sudoers


        (2)sudo授权格式:授权某用户在某主机上以某用户的身份运行指定的管理命令(command一般要写绝对路径)   

       WHO     HOST=(WHOM)     COMMAND

        (3)别名定义:别名必须使用全大写字符

    WHO别名定义:

        User_Alias   NAME = item1,item2,item3,….

        item:可以是用户名,%组名,#UID,$#GID,User_Alias

    HOST别名定义:

        Host_Alias  NAME = item1,item2,item3,….

        item:可以是hostname,ip,network,Host_Alias

    WHOM别名定义:

        Runas_Alias  NAME = item1,item2,item3,….

        item:可以是用户名,%组名,#UID,$#GID,User_Alias

    COMMANDb别名定义:

        Cmnd_Alias  NAME = item1,item2,item3,…..

        item:可以是命令,目录(目录下的所有命令),"sudoedit",Cmnd_Alias

    (4)常用的标签

        PASSWD: 执行操作时,需要输入密码,来验证用户身份

        NOPASSWD: 执行操作时,无需输入密码,不能确定用户身份 

    (5)用户的使用

        sudo[-u user] COMMAND

            -V 显示版本信息等配置信息

            -u user 默认为root

            -l,ll 列出用户在主机上可用的和被禁止的命令

            -v 再延长密码有效期限5分钟,更新时间戳

            -k 清除时间戳,下次需要重新输密码

            -K 与-k类似,还要删除时间戳文件

            -b在后台执行指令

            -p 改变询问密码的提示符号

        如-p”password on %h for user %p"

        给用户添加useradd的sudo权限,测试成功

[hill@centos6 ~]$ sudo useradd nihao
[sudo] password for hill: 
[hill@centos6 ~]$ tail -1 /etc/passwd
nihao:x:501:501::/home/nihao:/bin/bash
[hill@centos6 ~]$ useradd nihao
-bash: /usr/sbin/useradd: Permission denied

更多文章请关注 我的博客