SSH服务、sudo授权、PAM模块及时间同步服务全解析

目录

一、SSH服务

1、公钥交换原理

2、ssh加密通讯原理

3、openssh服务

① 客户端ssh命令

② 客户端scp命令

③ rsync命令

④ 自动登录ssh工具sshpass

4、ssh登陆验证方式介绍

 5、实现基于密钥的登陆方式

6、ssh服务器配置

二、利用sudo实现授权

三、PAM

1、PAM相关文件

2、PAM工作原理

3、PAM 配置文件格式说明

4、常用PAM模块

①pam_nologin.so 模块

②pam_limits.so 模块

③pam_google_authenticator 模块

四、时间同步服务

1、ntp

2、chrony

①chrony文件组成

②配置文件说明

③NTP客户端工具

④时间工具timedatctl

⑤实现私有时间服务


一、SSH服务

        SSH(Secure Shell Protocol)一种基于密码验证或密钥验证的安全协议,用于加密客户端和服务器之间的通信,它通过使用加密技术,确保数据在传输过程中的机密性、完整性和可用性,有效防止远程管理过程中的信息泄露问题。主要功能:远程登陆、文件传输、端口转发和执行远程命令。

        

        SSH服务默认使用TCP的22端口

        

具体实现:

        openSSH:ssh协议的开源实现,centos默认安装。

        dropbear:openssh轻量化替代。

        

SSH协议版本:

        v1:存在安全风险,易受中间人攻击。

        v2:双方主机协议选择安全的MAC方式,基于DH算法做密钥交换,基于RSA或DSA实现身份认证。

1、公钥交换原理

        客户端与服务端通信时,通过对称和非对称加密确保通信过程中数据的机密性、完整性、可用性,前提是双方互换公钥,但可能发生中间人攻击,双方互换证书,但我们在远程登陆的时候,是没有证书而是直接互换公钥,此时会出现中间人攻击,如何解决?

        

1、客户端向服务端发送TCP连接请求。

2、服务端接收到连接请求,返回自己的公钥,以及一个会话ID(服务端接收请求后动态生成)。

3、客户端生成临时密钥对(无实体文件,仅用于本次会话),并用自己的公钥异或会话ID计算一个结果Res,接着用服务端的公钥加密Res。

4、客户端发送加密后的值到服务器,服务端用自己的私钥解密,得到Res。

5、服务端用机密后的Res异或会话ID,可计算出客户端的公钥,此时双方公钥交换成功。

6、总结:双方各自持有三个密钥,自己的一对密钥+对方的公钥,之后所有通讯都会被加密。

2、ssh加密通讯原理

3、openssh服务

        OpenSSH(OpenBSD Secure Shell)是一个广泛使用的开源实现SSH(Secure Shell)协议的工具集,它提供了一种安全的方式来远程登录和管理网络设备,以及在本地和远程系统之间安全地传输文件。

        一般在各种Linux版本中会默认安装,基于C/S 结构。

        

        Windows中安装了openssh客户端,但是没有安装服务端。

#查看相关包
[root@rocky8-153 ~]#yum list openssh*
Last metadata expiration check: 2:52:45 ago on Sun 12 Oct 2025 10:30:55 AM CST.
Installed Packages
openssh.x86_64                                    8.0p1-24.el8                                 @anaconda
openssh-clients.x86_64                            8.0p1-24.el8                                 @anaconda
openssh-server.x86_64                             8.0p1-24.el8                                 @anaconda
...

[root@ubuntu-158 ~]#apt list openssh*
openssh-client-gssapi/plucky-updates 1:9.9p1-3ubuntu3.2 all
openssh-client-ssh1/plucky 1:7.5p1-17 amd64
openssh-client/plucky-updates,now 1:9.9p1-3ubuntu3.2 amd64 [installed,automatic]
openssh-known-hosts/plucky 0.6.3-1 all
openssh-server-gssapi/plucky-updates 1:9.9p1-3ubuntu3.2 all
openssh-server/plucky-updates,now 1:9.9p1-3ubuntu3.2 amd64 [installed]
openssh-sftp-server/plucky-updates,now 1:9.9p1-3ubuntu3.2 amd64 [installed,automatic]
openssh-tests/plucky-updates 1:9.9p1-3ubuntu3.2 amd64

① 客户端ssh命令

        ssh命令是ssh客户端,允许实现对远程系统经验证地加密安全访问。

        
        当用户远程连接ssh服务器时,会复制ssh服务器/etc/ssh/ssh_host*key.pub文件中的公钥到客户机的~/.ssh/know_hosts中。下次连接时,会自动匹配相对应的私钥,不能匹配,将拒绝连接。

#首次连接,会显示目标主机的指纹信息,并提示是否继续
#敲yes后会将目标主机的公钥保存在当前用户的~/.ssh/know_hosts 文件中
#ubuntu-rocky
[root@ubuntu-158 ~]#ssh root@10.0.0.153
The authenticity of host '10.0.0.153 (10.0.0.153)' can't be established.
ED25519 key fingerprint is SHA256:k5pG1fthpE6freZ1KyyJIRxyH1+ReBMt/fElrzfQYd8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.153' (ED25519) to the list of known hosts.
root@10.0.0.153's password: 
Web console: https://rocky8-153:9090/ or https://10.0.0.153:9090/

Last login: Sun Oct 12 11:58:43 2025 from 10.0.0.1
[root@rocky8-153 ~]#

#客户端上查看远端主机的公钥
[root@ubuntu-158 ~]#ls -l .ssh/
total 8
-rw------- 1 root root   0 Sep 20 10:40 authorized_keys
-rw------- 1 root root 978 Oct 12 13:32 known_hosts
-rw-r--r-- 1 root root 142 Oct 12 13:32 known_hosts.old
[root@ubuntu-158 ~]#cat .ssh/known_hosts
|1|e0fO4F/WBAvzAFtkG6SmN7wekIY=|RvoQbEgh4wux5nTKkGrb6YxHVHo= ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINDYsFXaiXtbH6nt8vBqnVJF0uRS3owKeK7UnTa48lJ5
|1|mRf+U1Xig2goUTeNxROh53Q0Qbk=|/YdUI9r1xTfsFSv55X4F+ttl6rw= ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDI4YkQGtAcnUzNHFADiW+cwEi/+DqjTwNnfWFDqoROyFB8uoLDAAmszDY2KsUsGoyCh0Ee2uSc/WlH0sbVz5rgNn+TQVdaVCDn5E4/+9a+SdNPONb19gnqKOnGlz/FDhkp9nCDftuUeQXlW4/SPTIKcJhUnSfwwst2OrQoFdSjTKdiyrh66EeFcvW4cD/MBsAjBUV6wsVQoe+GjNkKXPOOUUwNRxMz0C2G2MVQe35GEK41vXRC2GI1aGTkXduSEXQ8GvNc7gVZ3P6KvlWLPfbFwRxtw4DyMoWM4O7tTpKhBXiKWrggav5bB0a/1SGlENJKsJyW/9+ocsdV0+hi8pfILApFrpa78CY3JvaPNsTGs/KkDBM+Arkwslz5gjN1RbSGQk3kschWrzqGeT0j9jNLJENtJnB2kt6slW4Deo5vjghOx/IKtHj7vF94a9EkmTx0XhVaZ/Ql/jayhadXNBD1WJMXAcxixsvVqQ/piXIIUevxeT//+sxp01h7tUVHh08=
|1|NOyG3ThMSv6Xb83KBxsin9TybvE=|PealiGwj21AiY2M4cwZbyjJWn/Q= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJSJyVu+VvLuTqjgWTT5YJMx908RXBynUSPday6thGRsJX9njQ34NMw0N2e7ZeeQ8cgrmyAYFRCZS30U7GfST7o=

#文件中的内容在远端主机都能对应到
[root@rocky8-153 ~]#ls /etc/ssh/
moduli        sshd_config             ssh_host_ed25519_key      ssh_host_rsa_key.pub
ssh_config    ssh_host_ecdsa_key      ssh_host_ed25519_key.pub
ssh_config.d  ssh_host_ecdsa_key.pub  ssh_host_rsa_key

#远端主机基于不同算法的公钥
[root@rocky8-153 ~]#ls /etc/ssh/*pub
/etc/ssh/ssh_host_ecdsa_key.pub    /etc/ssh/ssh_host_rsa_key.pub
/etc/ssh/ssh_host_ed25519_key.pub

[root@rocky8-153 ~]#cat /etc/ssh/ssh_host_ed25519_key.pub 
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINDYsFXaiXtbH6nt8vBqnVJF0uRS3owKeK7UnTa48lJ5 

[root@rocky8-153 ~]#cat /etc/ssh/ssh_host_rsa_key.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDI4YkQGtAcnUzNHFADiW+cwEi/+DqjTwNnfWFDqoROyFB8uoLDAAmszDY2KsUsGoyCh0Ee2uSc/WlH0sbVz5rgNn+TQVdaVCDn5E4/+9a+SdNPONb19gnqKOnGlz/FDhkp9nCDftuUeQXlW4/SPTIKcJhUnSfwwst2OrQoFdSjTKdiyrh66EeFcvW4cD/MBsAjBUV6wsVQoe+GjNkKXPOOUUwNRxMz0C2G2MVQe35GEK41vXRC2GI1aGTkXduSEXQ8GvNc7gVZ3P6KvlWLPfbFwRxtw4DyMoWM4O7tTpKhBXiKWrggav5bB0a/1SGlENJKsJyW/9+ocsdV0+hi8pfILApFrpa78CY3JvaPNsTGs/KkDBM+Arkwslz5gjN1RbSGQk3kschWrzqGeT0j9jNLJENtJnB2kt6slW4Deo5vjghOx/IKtHj7vF94a9EkmTx0XhVaZ/Ql/jayhadXNBD1WJMXAcxixsvVqQ/piXIIUevxeT//+sxp01h7tUVHh08= 

[root@rocky8-153 ~]#cat /etc/ssh/ssh_host_ecdsa_key.pub 
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJSJyVu+VvLuTqjgWTT5YJMx908RXBynUSPday6thGRsJX9njQ34NMw0N2e7ZeeQ8cgrmyAYFRCZS30U7GfST7o= 
————————————————————————————————————————————————————————————————————————————————————————
#rocky-ubuntu
[root@rocky8-153 ~]#ssh root@10.0.0.158
The authenticity of host '10.0.0.158 (10.0.0.158)' can't be established.
ECDSA key fingerprint is SHA256:jbIyXS9RUWhcEj7xycSttAV3TVnbBSBcv15foHQJtQY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.158' (ECDSA) to the list of known hosts.
Ubuntu 25.04
root@10.0.0.158's password: 
Welcome to Ubuntu 25.04 (GNU/Linux 6.14.0-33-generic x86_64)
...
Last login: Sun Oct 12 13:32:14 2025 from 10.0.0.1
root@ubuntu-158:~#

#客户端查看已知主机列表
[root@rocky8-153 ~]#cat .ssh/known_hosts 
10.0.0.158 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEdV9pd2puhnw+otgOuN8FwkmfWLoCm97AVLwVZSA1ne1MZK7fpLj+NXBJvEFf05lIjUaOyVxMikRTxO892v+M4=

#查看服务端公钥
[root@ubuntu-158 ~]#ls /etc/ssh/*pub
/etc/ssh/ssh_host_ecdsa_key.pub    /etc/ssh/ssh_host_rsa_key.pub
/etc/ssh/ssh_host_ed25519_key.pub
[root@ubuntu-158 ~]#cat /etc/ssh/ssh_host_ecdsa_key.pub 
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEdV9pd2puhnw+otgOuN8FwkmfWLoCm97AVLwVZSA1ne1MZK7fpLj+NXBJvEFf05lIjUaOyVxMikRTxO892v+M4= root@ubuntu
#首次连接时并不能确定远端主机的真伪,但是下载公钥之前可以查看远端的指纹信息
#在连接前,可以先自己连自己,查看一下指纹
[root@rocky8-153 ~]#ssh 127.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:uihuTTkydcKoY3ouzbl01M7RtreW2u9UuXzHTR9YDRk.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 

#154远程连接153,指纹信息一致
[root@rocky-154 ~]# ssh root@10.0.0.153
The authenticity of host '10.0.0.153 (10.0.0.153)' can't be established.
ECDSA key fingerprint is SHA256:uihuTTkydcKoY3ouzbl01M7RtreW2u9UuXzHTR9YDRk.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 

        总结:在SSH服务中,客户端连接远程主机,首先会在客户端显示一段提示是否要继续连接,是一个人为确定的过程,同时本地系统对于远程主机身份尚未确定,因此首次连接在未输入yes之前,公钥尚未实际交换,此时也会给客户端显示远程主机的公钥指纹(客户端请求远程主机,远程主机发送公钥,客户端对公钥通过哈希算法计算生成)来验证远程主机身份。输入yes之后,确认接受远程主机的公钥指纹,表示信任主机。当开始输入远程主机密码时,公钥已经交换并且存储完毕。

ssh [options...] destination [command]
#常用选项

-p PORT #指定远程服务器的端口,默认22
-b IP   #指定本地主机此次连接使用的IP
-v      #调试模式,可以追踪此次连接的过程
-C      #开启压缩
-t      #强制伪终端分配,可用于在远程系统上执行任意基于屏幕的程序,跳转
-o option     #以K=V格式指定选项
-i <file>     #指定私钥文件路径,实现基于key验证
-F configfile #指定客户端配置文件
#如果不指定用户名,默认使用当前用户去登录远程主机
[root@rocky8-153 ~]#ssh 10.0.0.158
The authenticity of host '10.0.0.158 (10.0.0.158)' can't be established.
ECDSA key fingerprint is SHA256:jbIyXS9RUWhcEj7xycSttAV3TVnbBSBcv15foHQJtQY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.158' (ECDSA) to the list of known hosts.
Ubuntu 25.04
root@10.0.0.158's password: 

[hu@rocky8-153 ~]$ssh 10.0.0.158
The authenticity of host '10.0.0.158 (10.0.0.158)' can't be established.
ECDSA key fingerprint is SHA256:jbIyXS9RUWhcEj7xycSttAV3TVnbBSBcv15foHQJtQY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.158' (ECDSA) to the list of known hosts.
Ubuntu 25.04
hu@10.0.0.158's password: 
#首次连接会下载远程主机公钥,分别保存对应用户known_hosts下
#指定本机IP
[root@rocky8-153 ~]#ip addr add dev eth0 10.0.0.114/24

[root@rocky8-153 ~]#ip a s eth0

[root@rocky8-153 ~]#ip a s eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:b4:f4:99 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    altname ens160
    inet 10.0.0.153/24 brd 10.0.0.255 scope global dynamic noprefixroute eth0
       valid_lft 1665sec preferred_lft 1665sec
    inet 10.0.0.114/24 scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:feb4:f499/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

#远程主机查看,10.0.0.153连接
[root@ubuntu-158 ~]#ss -tn
State        Recv-Q        Send-Q               Local Address:Port               Peer Address:Port         
ESTAB        0             0                       10.0.0.158:22                   10.0.0.153:55736        
ESTAB        0             52                      10.0.0.158:22                     10.0.0.1:58784 

#指定本机IP连接远程主机
[root@rocky8-153 ~]#ssh -b 10.0.0.114 root@10.0.0.158

[root@ubuntu-158 ~]#ss -tn
State        Recv-Q        Send-Q               Local Address:Port               Peer Address:Port         
ESTAB        0             52                      10.0.0.158:22                     10.0.0.1:58784        
ESTAB        0             0                       10.0.0.158:22                   10.0.0.114:36155 
#多次连接 158->153->154
[root@ubuntu-158 ~]#ssh -t 10.0.0.153 ssh -t 10.0.0.154

#154查看,有153的远程连接
[root@rocky-154 ~]# ss -tn
State      Recv-Q      Send-Q           Local Address:Port            Peer Address:Port       Process      
ESTAB      0           0                   10.0.0.154:22                  10.0.0.1:62476                                      
ESTAB      0           0                   10.0.0.154:22                10.0.0.153:38318                   
 
#153远程连接154,154公钥被保存
[root@rocky8-153 ~]#ls .ssh/
known_hosts
[root@rocky8-153 ~]#cat .ssh/known_hosts 
10.0.0.154 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAfL2hCZGdQcBCprGbQ1u3Ad1eZwDkOxsi04nIaj/3i/RZpiccmtr3Jxb6jpb1EFmFlmQ9ZhRPts6stWxNcwhpk=

#断开,先断开154,在断开153
[root@rocky-154 ~]# exit
logout
Connection to 10.0.0.154 closed.
Connection to 10.0.0.153 closed.
#执行命令
#在远程主机执行完命令后就断开
[root@ubuntu-158 ~]#ssh 10.0.0.154 "hostname -I"
The authenticity of host '10.0.0.154 (10.0.0.154)' can't be established.
ED25519 key fingerprint is SHA256:MWItps0K3a6Ci0RAC/5t7i8OId+XSVn0uB4hdICH8O8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.154' (ED25519) to the list of known hosts.
root@10.0.0.154's password: 
10.0.0.154 

[root@ubuntu-158 ~]#ssh 10.0.0.154 "touch /tmp/158-test"
root@10.0.0.154's password: 

[root@rocky-154 ~]# ls /tmp
158-test
#在远程主机运行本地脚本
[root@ubuntu-158 ~]#cat 158.sh 
#!/bin/bash

hostname -I

[root@ubuntu-158 ~]#chmod a+x 158.sh 

#本机执行
[root@ubuntu-158 ~]#./158.sh
10.0.0.158 

#远程主机执行
[root@ubuntu-158 ~]#ssh 10.0.0.154 /bin/bash < 158.sh
root@10.0.0.154's password: 
10.0.0.154 
[root@ubuntu-158 ~]#ssh 10.0.0.154 
The authenticity of host '10.0.0.154 (10.0.0.154)' can't be established.
ED25519 key fingerprint is SHA256:MWItps0K3a6Ci0RAC/5t7i8OId+XSVn0uB4hdICH8O8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

#加选项,首次连接时自动回答yes,自动下载公钥
[root@ubuntu-158 ~]#ssh -o StrictHostKeyChecking=no 10.0.0.154 
Warning: Permanently added '10.0.0.154' (ED25519) to the list of known hosts.
root@10.0.0.154's password: 

#也可以直接在客户端配置修改
[root@rocky-154 ~]# vim /etc/ssh/ssh_config
#   StrictHostKeyChecking ask
    StrictHostKeyChecking no

[root@ubuntu-158 ~]#ssh 10.0.0.154 
Warning: Permanently added '10.0.0.154' (ED25519) to the list of known hosts.
root@10.0.0.154's password: 

#客户端配置,每次执行重新读取,不需要重启

② 客户端scp命令

#scp 命令利用ssh协议在两台主机之间复制文件
scp [options] SRC... DEST/

#常用选项
-C         #压缩数据流
-r         #递归复制
-p         #保持原文件的属性信息
-q         #静默模式
-P PORT    #指定远程服务器的端口,默认22

将本地文件复制到远程

#将当前主机/root/hu/1012下的a.sh文件复制到远程主机hu的家目录下
[root@rocky8-153 ~]#id hu
uid=1000(hu) gid=1000(hu) groups=1000(hu)

[root@rocky8-153 ~]#ls /home/hu

#:表示指定用户家目录
[root@ubuntu-158 ~]#scp /root/hu/1012/a.sh hu@10.0.0.153:
Warning: Permanently added '10.0.0.153' (ED25519) to the list of known hosts.
hu@10.0.0.153's password: 
a.sh                                                 100%    0     0.0KB/s   00:00    

#远程主机查看
[root@rocky8-153 ~]#ls /home/hu
a.sh

将远程主机复制到本地

[root@rocky-154 huhao123]# pwd
/root/huhao123

[root@rocky-154 huhao123]# ls
test.txt

[root@ubuntu-158 ~]#scp root@10.0.0.154:/root/huhao123/test.txt .
root@10.0.0.154's password:
 
[root@ubuntu-158 ~]#ls       
test.txt

源和目标都不是本机

[root@ubuntu-158 ~]#scp 10.0.0.154:/etc/issue 10.0.0.153:/tmp/
root@10.0.0.153's password: 
root@10.0.0.154's password: 
issue                                                100%   23     5.5KB/s   00:00    

[root@rocky8-153 ~]#ls /tmp
issue                                                                

复制目录

[root@ubuntu-158 ~]#scp -r /var/log root@10.0.0.153:/tmp/
root@10.0.0.153's password: 
vmware-network.3.log                                 100%  193    68.9KB/s   00:00    
auth.log                                             100%  136KB   9.9MB/s   00:00    
subiquity-client-debug.log                           100%  590KB  33.8MB/s   00:00      
...

[root@rocky8-153 ~]#ls /tmp
issue  log    

#
scp -r dir dest/ #复制整个目录
scp -r dir/ dest/ #复制整个目录
scp -r dir/* dest/ #复制目录下所有文件

③ rsync命令

        scp 命令在复制文件时是全量复制,不管文件有没有改动,都是复制,速度慢,消耗资源。
        
        rsync工具可以基于ssh和rsync协议实现高效率的远程系统之间复制文件,使用安全的shell连接做为传输方式,比scp更快,基于增量数据同步,即只复制两方不同的文件,此工具来自于rsync包。

        

        注意:通信两端主机都需要安装 rsync 软件。

rsync [OPTION]... SRC [SRC]... DEST

#常用选项
-n|--dry-run       #只测试,不执行
-v|--verbose       #显示详细过程
-r|--recursive     #递归复制
-p|--perms         #保留权限属性
-t|--times         #保留修改时间戳
-g|--group         #保留组信息
-o|--owner         #保留所有者信息
-l|--links         #将软链接文件本身进行复制(默认)
-L|--copy-links    #将软链接文件指向的文件复制
-u|--update        #如果接收者的文件比发送者的文件较新,将忽略同步
-z|--compress      #压缩,节约网络带宽
-a|--archive       #保留所有属性,但不包括acl和selinux
--delete           #如果源数据中的文件被删除,则目标中的对应文件也要被删除,配合-r使用
--progress         #显示进度
--bwlimit=5120     #限速以KB为单位,5120表示5MB
#全量复制:完整复制源端的所有数据,而不考虑数据是否已存在或是否发生变化
[root@ubuntu-158 1012]#ll
total 148
-rw-r----- 1 root root 142938 Oct 12 18:49 auth.log
-rw-r--r-- 1 root root    657 Oct 12 18:49 fstab
-rw-r--r-- 1 root root     20 Oct 12 18:49 issue

[root@ubuntu-158 1012]#scp ./* 10.0.0.154:/tmp
root@10.0.0.154's password: 
auth.log                                             100%  140KB  15.1MB/s   00:00    
fstab                                                100%  657   726.3KB/s   00:00    
issue                                                100%   20    10.6KB/s   00:00    

root@rocky-154 tmp]#ll
total 148
-rw-r-----. 1 root root 142938 Oct 12 18:54 auth.log
-rw-r--r--. 1 root root    657 Oct 12 18:54 fstab
-rw-r--r--. 1 root root     20 Oct 12 18:54 issue

[root@ubuntu-158 1012]#echo "111111111">>issue

[root@ubuntu-158 1012]#scp ./* 10.0.0.154:/tmp
root@10.0.0.154's password: 
auth.log                                             100%  140KB  15.5MB/s   00:00    
fstab                                                100%  657   272.8KB/s   00:00    
issue                                                100%   30    13.1KB/s   00:00 

[root@rocky-154 tmp]#ll
total 148
-rw-r-----. 1 root root 142938 Oct 12 18:55 auth.log
-rw-r--r--. 1 root root    657 Oct 12 18:55 fstab
-rw-r--r--. 1 root root     30 Oct 12 18:55 issue
————————————————————————————————————————————————————————————————————————————————————————
#增量复制
[root@ubuntu-158 1012]#rsync -av ./* 10.0.0.154:/tmp
root@10.0.0.154's password: 
sending incremental file list
auth.log
fstab
issue

sent 1,049 bytes  received 1,315 bytes  945.60 bytes/sec
total size is 143,625  speedup is 60.76

#查看
[root@rocky-154 tmp]#ll
total 148
-rw-r-----. 1 root root 142938 Oct 12 18:49 auth.log
-rw-r--r--. 1 root root    657 Oct 12 18:49 fstab
-rw-r--r--. 1 root root     30 Oct 12 18:54 issue

[root@ubuntu-158 1012]#rsync -av ./* 10.0.0.154:/tmp
root@10.0.0.154's password: 
sending incremental file list
issue

sent 184 bytes  received 41 bytes  150.00 bytes/sec
total size is 143,633  speedup is 638.37

#再次查看
[root@rocky-154 tmp]#ll
total 148
-rw-r-----. 1 root root 142938 Oct 12 18:49 auth.log
-rw-r--r--. 1 root root    657 Oct 12 18:49 fstab
-rw-r--r--. 1 root root     38 Oct 12 19:05 issue

#
rsync -av dir dest/ #复制整个目录
rsync -av dir/ dest/ #复制目录下所有文件
rsync -av dir/* dest/ #复制目录下所有文件

④ 自动登录ssh工具sshpass

        由EPEL源提供,ssh登陆不能在命令行中指定密码。sshpass的出现,解决了这一问题。sshpass用于非交互SSH的密码验证,一般用在sh脚本中,无须再次输入密码(本机known_hosts文件中有的主机才能生效)。它允许用 -p 参数指定明文密码,然后直接登录远程服务器,它支持密码从命令行、文件、环境变量中读取。

[root@ubuntu-158 ~]#apt install sshpass
sshpass [option] command parameters

#常用选项
-p password      #指定明文密码
-f filename      #从文件中读取密码,文件的第一行为密码
-e               #将环境变量SSHPASS作为密码
[root@ubuntu-158 ~]#ssh 10.0.0.153 "hostname -I"
root@10.0.0.153's password: 
10.0.0.153 

root@ubuntu-158 ~]#sshpass -p 12345 ssh 10.0.0.153 "hostname -I"
10.0.0.153 
[root@ubuntu-158 ~]#cat pwd.txt 
12345
[root@ubuntu-158 ~]#sshpass -f pwd.txt ssh 10.0.0.153 "hostname -I"
10.0.0.153 
[root@ubuntu-158 ~]#export SSHPASS=12345
[root@ubuntu-158 ~]#sshpass -e ssh 10.0.0.153 "hostname -I"
10.0.0.153 

4、ssh登陆验证方式介绍

基于用户和口令登陆验证

1、客户端发起ssh请求,服务器会把自己的公钥发送给用户。
2、 用户会根据服务器发来的公钥对密码进行加密。
3.、加密后的信息回传给服务器,服务器用自己的私钥解密,如果密码正确,则用户登录成功。

基于密钥的登陆方式

1、首先在客户端生成一对密钥(ssh-keygen), 并将客户端的公钥ssh-copy-id 拷贝到服务端。
2、当客户端再次发送一个连接请求,包括ip、用户名,服务端得到客户端的请求后,会到authorized_keys中查找,如果有响应的IP和用户,就会随机生成一个字符串。
3、服务端将使用客户端拷贝过来的公钥进行加密,然后发送给客户端。
6. 得到服务端发来的消息后,客户端会使用私钥进行解密,然后将解密后的字符串发送给服务端。
7. 服务端接受到客户端发来的字符串后,跟之前的字符串进行对比,如果一致,就允许免密码登录。

 5、实现基于密钥的登陆方式

在客户端上生成密钥对

ssh-keygen -t rsa [-P 'password'] [-f “~/.ssh/id_rsa"]
root@ubuntu-157:~# 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 for "/root/.ssh/id_rsa" (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:qbuOKfuyZgP1w/UQioHtOd2/0LnFgkygHePYl8t9bLI root@ubuntu-157
The key's randomart image is:
+---[RSA 3072]----+
| o               |
|. o + .          |
| . @ * o         |
|  O * B  .       |
| . + * OS+       |
|.   + *.O *      |
| .   ... X       |
|  *  o .E        |
| ooB+.+.         |
+----[SHA256]-----+

root@ubuntu-157:~# ls .ssh/
id_rsa  id_rsa.pub

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

ssh-copy-id [-i [identity_file]] [user@]host
#将本机公钥传给远程主机
root@ubuntu-157:~# ssh-copy-id root@10.0.0.153
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '10.0.0.153 (10.0.0.153)' can't be established.
ED25519 key fingerprint is SHA256:k5pG1fthpE6freZ1KyyJIRxyH1+ReBMt/fElrzfQYd8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 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@10.0.0.153's password: 

Number of key(s) added: 1

Now try logging into the machine, with: "ssh 'root@10.0.0.153'"
and check to make sure that only the key(s) you wanted were added.

root@ubuntu-157:~# ls .ssh/
id_rsa           id_rsa.pub       known_hosts      known_hosts.old 

root@ubuntu-157:~# cat .ssh/id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC33PMgQ48xR6XDxKuScxiumpZpkrwWCUkpkPOI6KaflRjw9aDI7+Y2wjb5
...
uZLAb1eOUY2M4Gtf/hkcOzwws5luDYfs45xIpkRkisWbfVYqvwVKNLh4hTjm5p1Q1CqfYMY0foOI7TKWjmkRfgZNs2bjW+GKUTh1qoc= root@ubuntu-157

#查看目标机
[root@rocky8-153 ~]#ls .ssh/
authorized_keys

[root@rocky8-153 ~]#cat .ssh/authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC33PMgQ48xR6XDxKuScxiumpZpkrwWCUkpkPOI6KaflRjw9aDI7+Y2wjb5
...
uZLAb1eOUY2M4Gtf/hkcOzwws5luDYfs45xIpkRkisWbfVYqvwVKNLh4hTjm5p1Q1CqfYMY0foOI7TKWjmkRfgZNs2bjW+GKUTh1qoc= root@ubuntu-157

#测试免密登录
root@ubuntu-157:~# ssh root@10.0.0.153
Web console: https://rocky8-153:9090/ or https://10.0.0.153:9090/

Last login: Sun Oct 12 17:31:44 2025 from 10.0.0.158

注意:ssh-copy-id root@10.0.0.153时,要先确认指纹,10.0.0.153是否是要找的远程主机,并且会将该主机上的/etc/ssh/*pub 根据算法得到指纹来人为确认输入yes,会将该pub下载到客户端当前用户的.ssh/known_hosts中。

1、确认指纹,确认服务器。

2、客户端当前用户会话级别的pubkey和服务器上的pubkey交换完成。

3、客户端输密码,安全传输。

4、密码校验通过,部署客户端永久key到服务端对应加目录中。

多机打通

#先生成密钥对
root@ubuntu-157:~# 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 for "/root/.ssh/id_rsa" (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:/sOpyhPnvFXCmId6DDBzXwqT7sw5ei09nLsB2vuXAWE root@ubuntu-157
The key's randomart image is:
+---[RSA 3072]----+
|                 |
|       .E        |
|    + =. ..      |
|     * +.B       |
|      + S.+ .    |
|     *.B...o     |
|    . OO=o.+     |
|     o++O+*      |
|    ..+=*B..     |
+----[SHA256]-----+

root@ubuntu-157:~# ls .ssh
id_rsa  id_rsa.pub

#将公钥复制到本机
root@ubuntu-157:~# ssh-copy-id 127.1
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ED25519 key fingerprint is SHA256:NMjZpMYkMVJ2F+4SEexMgqnsJUEqj5uLmSeXYJfg3zA.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 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@127.0.0.1's password: 

Number of key(s) added: 1

Now try logging into the machine, with: "ssh '127.1'"
and check to make sure that only the key(s) you wanted were added.

root@ubuntu-157:~# ls .ssh/
authorized_keys  id_rsa  id_rsa.pub  known_hosts  known_hosts.old

#先将10.0.0.153打通
root@ubuntu-157:~# scp .ssh/authorized_keys 10.0.0.153:.ssh/
root@10.0.0.153's password: 
authorized_keys                                        100%  569   265.0KB/s   00:00    
root@ubuntu-157:~# ssh 10.0.0.153
Web console: https://rocky8-153:9090/ or https://10.0.0.153:9090/

Last login: Sun Oct 12 20:16:10 2025 from 10.0.0.157
[root@rocky8-153 ~]#exit

root@ubuntu-157:~# scp .ssh/id_rsa* 10.0.0.153:.ssh/
id_rsa                                                 100% 2602     1.3MB/s   00:00    
id_rsa.pub                                             100%  569   184.0KB/s   00:00    

[root@rocky8-153 ~]#ls .ssh/
authorized_keys  id_rsa  id_rsa.pub

[root@rocky8-153 ~]#ssh 10.0.0.157
...
root@ubuntu-157:~# exit

#总结:将 .ssh 目录整体复制到其它主机,这样表示多机共用密钥对
root@ubuntu-157:~# rsync -a .ssh 10.0.0.154:/root/
The authenticity of host '10.0.0.154 (10.0.0.154)' can't be established.
ED25519 key fingerprint is SHA256:MWItps0K3a6Ci0RAC/5t7i8OId+XSVn0uB4hdICH8O8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.154' (ED25519) to the list of known hosts.
root@10.0.0.154's password: 
root@ubuntu-157:~# rsync -a .ssh 10.0.0.158:/root/
The authenticity of host '10.0.0.158 (10.0.0.158)' can't be established.
ED25519 key fingerprint is SHA256:c9ShTOI4xrUo5HfkO2S5HJDPIfnQxOJ1h2nwrhacJgU.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.158' (ED25519) to the list of known hosts.
Ubuntu 25.04
root@10.0.0.158's password: 

windows客户端工具 xshell 也可以配置公钥远程连接。

6、ssh服务器配置

[root@ubuntu ~]# cat /etc/ssh/sshd_config
Port  22                     #远程端口,生产建议修改
ListenAddress ip             #指定 SSH 服务监听的 IP 地址
LoginGraceTime 2m            #设置登录超时时间
PermitRootLogin yes          #默认ubuntu不允许root远程ssh登录
StrictModes yes              #检查.ssh/文件的所有者,权限等
MaxAuthTries 6               #一次连接,最多可以输错6次密码
MaxSessions 10               #同一个连接最大会话,就是xshell上的复制ssh隧道,修改后对新连接生效
PubkeyAuthentication yes     #开启基于key验证
PermitEmptyPasswords no      #不允许空密码连接
PasswordAuthentication yes   #开启基于用户名和密码连接
MaxStartups 10:30:100        #未认证连接最大值,默认值10
PrintMotd no                 #是否输出motd信息,改成yes 则motd 会输出两次
PrintLastLog yes             #是否输出上次登录信息
UseDNS yes                   #是否需要解析主机名,no可加快连接速度
GSSAPIAuthentication yes     #是否开启客户端对IP反解析,提高速度可改为no
Banner /path/file            #远程连接时的登录前提示

#以下可以限制可登录用户的办法:
AllowUsers user1 user2 user3    #用户名白名单
DenyUsers user1 user2 user3     #用户名黑名单
AllowGroups g1 g2               #用户组白名单
DenyGroups g1 g2                #用户组黑名单
#设置ssh服务超时断开连接
#10s如果没有互动,则断开链接,永久生效可以写配置文件,例如可以写在 /etc/profile 里面
[root@ubuntu ~]# export TMOUT=10

#关闭dns解析选项,加快连接速度
[root@ubuntu ~]# vim /etc/ssh/sshd_config
UseDNS no
GSSAPIAuthentication no
[root@ubuntu ~]# systemctl restart sshd

#在ubuntu 上开启root远程登录
hu@ubuntu2204:~# vim /etc/ssh/sshd_config
#PermitRootLogin prohibit-password 
PermitRootLogin yes
hu@ubuntu2204:~# 
systemctl restart sshd

SSH服务安全加固:

        1、修改默认端口(如 2222)以减少暴力破解风险;

        2、禁用 SSHv1 协议(Protocol 2),仅使用更安全的 SSHv2;

        3、限制可登录用户(通过 AllowUsers 或 AllowGroups),避免未授权账户访问;

        4、设置空闲会话超时(ClientAliveInterval 300 + ClientAliveCountMax 0)自动断开闲置连接;

        4、结合防火墙规则(如 iptables/ufw)限制源 IP 或国家/地区访问;

        5、仅监听特定内网 IP(ListenAddress 192.168.1.100),避免暴露公网;

        6、强制强密码策略(如生成 12 位随机密码:tr -dc A-Za-z0-9_ < /dev/urandom | head -c 12),但优先启用密钥认证(PasswordAuthentication no)并禁用空密码(PermitEmptyPasswords no);

        8、禁止 root 直接登录(PermitRootLogin no),通过普通用户+sudo 提权;

        9、限制访问频度(如 MaxStartups 10:30:60)和并发连接数,防止 DDoS 攻击;

        10、定期分析日志(/var/log/auth.log 或 /var/log/secure),监控异常登录行为并及时调整策略。

二、利用sudo实现授权

        sudo(Superuser Do)是一款允许普通用户以特定权限(通常是root)执行特定命令的工具,其核心优势在于无需共享 root 密码,从而降低系统安全风险。

        传统 su 命令需用户知晓 root 密码且是用户环境完全切换,而 sudo 通过配置文件 /etc/sudoers 授权特定用户或用户组执行指定命令,授权后用户仅需输入自身密码即可临时获取 root 权限,执行后恢复原用户身份。

       

原理:

        sudo 的权限规则存储在 /etc/sudoers 文件中,该文件定义了谁、在什么主机、以什么身份、能执行什么命令。

        

特性:

        1. sudo能够授权指定用户在指定主机上运行某些命令。如果未授权用户尝试使用 sudo,会提示联系管理员。
        2. sudo提供了丰富的日志,详细地记录了每个用户干了什么。它能够将日志传到中心主机或者日志服务器。
        3. 默认情况下,授权后 5 分钟内重复使用 sudo 无需重新输入密码。
        4. sudo的配置文件是sudoers文件,它允许系统管理员集中的管理用户的使用权限和使用的主机。它所存放的位置默认是在/etc/sudoers,属性必须为0440。

#软件包
root@ubuntu-157:~# dpkg -l sudo
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version             Architecture Description
+++-==============-===================-============-=======================================================
ii  sudo           1.9.16p2-1ubuntu1.1 amd64        Provide limited super user privileges to specific users

#主配置文件
/etc/sudo.conf   
  
#授权规则配置文件
/etc/sudoers       
/etc/sudoers.d/*

#审计文件
/var/db/sudo
/var/log/auth.log

#安全编辑授权规则文件和语法检查工具
/usr/sbin/visudo

#授权编辑规则文件的工具
/usr/bin/sudoedit

#执行授权命令
/usr/bin/sudo

#语法检查
visudo -c
visudo -f /etc/sudoers.d/test
sudo [options...] [command]
sudo [options...] file...

#常用选项
-b|--background         #在后台执行         
-B|--bell               #响铃                    
-E|--preserve-env       #继承当前环境变量
-e|--edit filename...   #编辑文件     
-g|--group=group        #以指定组执行     
-H|--set-home           #指定切换用户的家目录
-h|--host=host          #在指定主机上执行               
-i|--login              #直接登录
-K|--remove-timestamp   #删除时间戳文件,则下次执行要重新输入密码
-k|--reset-timestamp    #清除时间戳,则下次执行要重新输入密码   
-l|--list               #列出指定用户己配置的sudo规则,不指定用户则是查看当前登录用户          
-p|--prompt=prompt      #改变密码询问时的提示语句        
-s|--shell              #以指定shell来执行                   
-U|--other-user=user    #配合-l使用,指定要查看的用户
-u|--user=user          #指定要代表的用户,默认root
-V|--version            #显示版本   
-h|--help               #显示帮助
-v|--validate           #再延长密码有效期5分钟

sudo授权规则配置

#授权user用户可以在host主机上以runas的身份执行command,TAG可为空
user host=(runas) [TAG:]command 

#可使用通配符
?             #任意单个字符 
*             #任意长度字符
[abc]         #匹配abc中的一个字符
[!abc]        #匹配任意一个除abc之外的字符
\x            #转义
[[alpha]]     #字母

#user 和 runnas
userName      #用户名
#uid          #用户ID
%groupName    #组名
%#gid         #组ID
User_Alias    #user别名
Runas_Alias   #runas别名

#host
ip              #ip地址
hostname        #主机名
network/netmask #网段/子网掩码
Host_Alias      #别名

#command
cmmand         #具体命令
directory/*    #某个目录下所有命令
sudoedit       #sudoedit命令,有此命令就可以编辑sudo规则
Cmnd_Alias     #命令别名

#别名

#类型
User_Alias|Runas_Alias|Host_Alias|Cmnd_Alias

#格式
Alias_Type NAME = item1, item2, ...

#别名名称由大写字母开始,后面接大写字母,数字,下划线
NAME = [A-Z]([A-Z][0-9]_)*
#指定IP或网段的写法,要求在对应主机上也有该配置
#该修改配置文件只是在当前主机对应用户下有

hu    10.0.0.158=(root) /usr/bin/ls /root/
hu    10.0.0.0/24=(root) /usr/bin/touch /root/from-hu
hu    10.0.0.157=(root) /usr/sbin/shutdown -h now

[hu@rocky8-153 ~]$ls /root
ls: cannot open directory '/root': Permission denied

[hu@rocky8-153 ~]$sudo ls /root
anaconda-ks.cfg    

[hu@rocky8-153 ~]$touch /root/from-hu
touch: cannot touch '/root/from-hu': Permission denied

[hu@rocky8-153 ~]$sudo touch /root/from-hu
[sudo] password for hu:

[hu@rocky8-153 ~]$sudo ls /root
anaconda-ks.cfg  from-hu  
#visudo实现语法检查

[root@rocky8-153 ~]#visudo
/etc/sudoers:9:10: syntax error
123123abc
         ^
What now? 
Options are:
  (e)dit sudoers file again                            #重新编辑文件
  e(x)it without saving changes to sudoers file        #放弃修改,不保存退出
  (Q)uit and save changes to sudoers file (DANGER!)    #强制保存修改(有风险,可能导致sudo失效)

What now?
#10.0.0.153主机查看配置
[root@rocky8-153 ~]#sudo -l
...
User root may run the following commands on rocky8-153:
    (ALL) ALL

#查看用户hu
[hu@rocky8-153 ~]$sudo -l
...
User hu may run the following commands on rocky8-153:
    (root) /usr/bin/ls /root
    (root) /usr/bin/touch /root/from-hu

#用户没有配置sudo规则
[xiaoq@rocky8-153 ~]$sudo -l

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for xiaoq: 
Sorry, user xiaoq may not run sudo on rocky8-153.

#不用切换,查看指定用户
[root@rocky8-153 ~]#sudo -l -U hu
...
User hu may run the following commands on rocky8-153:
    (root) /usr/bin/ls /root
    (root) /usr/bin/touch /root/from-hu

#初始用户,属于sudo组
hu@ubuntu-158:~$ sudo -l
[sudo] password for hu: 
Matching Defaults entries for hu on ubuntu-158:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin,
    use_pty

User hu may run the following commands on ubuntu-158:
    (root) /usr/bin/ls /root
    (ALL : ALL) ALL
#默认sudo到root身份执行
hu@ubuntu-158:~$ sudo ls /root
[sudo] password for hu: 
a.sh	 c.awk	 f.patch   		

#五分钟内再次执行,不需要输入密码
hu@ubuntu-158:~$ sudo touch /root/from-hu
hu@ubuntu-158:~$ sudo ls /root
a.sh	 c.awk	 f.patch	 from-hu	 		 
#多个身份要指定,否则默认切换root用户 
hu      10.0.0.153=(root) /usr/bin/ls /root
hu      10.0.0.153=(xiaoq,God) /usr/bin/touch /root/from-hu

#默认root身份,但是没有权限执行失败
[hu@rocky8-153 ~]$sudo touch /tmp/from-hu
Sorry, user hu is not allowed to execute '/bin/touch /tmp/from-hu' as root on rocky8-153.

#指定用户执行
[hu@rocky8-153 ~]$sudo -u xiaoq touch /tmp/from-hu

[hu@rocky8-153 ~]$ll /tmp
total 0
-rw-r--r--. 1 xiaoq xiaoq 0 Oct 13 11:27 from-hu

[root@rocky8-153 tmp]#rm -rf /tmp/from-hu 

[hu@rocky8-153 ~]$touch /tmp/from-hu

[hu@rocky8-153 ~]$ll /tmp
total 0
-rw-rw-r--. 1 hu hu 0 Oct 13 11:32 from-hu

[hu@rocky8-153 ~]$rm -rf /tmp/from-hu

#指定用户执行
[hu@rocky8-153 ~]$sudo -u hua touch /tmp/from-hu
[sudo] password for hu: 

[hu@rocky8-153 ~]$ll /tmp
total 4
-rw-r--r--. 1 hua  hua   0 Oct 13 11:34 from-hu
#id配置写法
[root@rocky8-153 tmp]#id root
uid=0(root) gid=0(root) groups=0(root)

[root@rocky8-153 tmp]#id hu
uid=1000(hu) gid=1000(hu) groups=1000(hu)

[root@rocky8-153 tmp]#id xiaoq
uid=1001(xiaoq) gid=1001(xiaoq) groups=1001(xiaoq)

[root@rocky8-153 tmp]#id hua
uid=1002(hua) gid=1002(hua) groups=1002(hua)

#修改配置文件 
#1000,%#1002,xiaoq      ALL=(#0)        /usr/bin/cat /etc/shadow               
#1000,%#1002,xiaoq      ALL=(%#0)       /usr/bin/cat /etc/shadow    

[hu@rocky8-153 ~]$sudo cat /etc/shadow
[sudo] password for hu: 
root:$6$v5mMTSV2.aqFUYXz$6Ou0LjeYWF1DBxi7T4oO90cvg6UFBv3WJ.Ux9ltw/QDAZnwGIQJEEm7FbT2AYTUiAtn9ck.UIAcz5weoLtfmM.::0:99999:7:::
bin:*:19767:0:99999:7:::
...

[xiaoq@rocky8-153 ~]$sudo cat /etc/shadow
[sudo] password for xiaoq: 
root:$6$v5mMTSV2.aqFUYXz$6Ou0LjeYWF1DBxi7T4oO90cvg6UFBv3WJ.Ux9ltw/QDAZnwGIQJEEm7FbT2AYTUiAtn9ck.UIAcz5weoLtfmM.::0:99999:7:::
bin:*:19767:0:99999:7:::
...

[hua@rocky8-153 ~]$sudo cat /etc/shadow 
[sudo] password for hua: 
root:$6$v5mMTSV2.aqFUYXz$6Ou0LjeYWF1DBxi7T4oO90cvg6UFBv3WJ.Ux9ltw/QDAZnwGIQJEEm7FbT2AYTUiAtn9ck.UIAcz5weoLtfmM.::0:99999:7:::
bin:*:19767:0:99999:7:::
...
————————————————————————————————————————————————————————————————————————————————————————
#别名写法
User_Alias PEOPLE=hu,#1001,%#1002 
Runas_Alias ROOT=root
Host_Alias LOCAL=10.0.0.153,rocky
Cmnd_Alias CMD=/usr/sbin/init *,/usr/bin/yum update
Cmnd_Alias SHUTDOWN=/usr/sbin/shutdown -h now

PEOPLE LOCAL=(ROOT) CMD,SHUTDOWN

[hu@rocky8-153 ~]$sudo -l
[sudo] password for hu: 
...
User hu may run the following commands on rocky8-153:
    (root) /usr/sbin/init *, /usr/bin/yum update, /usr/sbin/shutdown -h now

[hu@rocky8-153 ~]$init 5
Failed to open initctl fifo: Permission denied
Failed to talk to init daemon.

[hu@rocky8-153 ~]$sudo init 5

[hu@rocky8-153 ~]$runlevel
3 5

[hu@rocky8-153 ~]$yum update
Error: This command has to be run with superuser privileges (under the root user on most systems).
#配置不需要密码验证
#配置排除规则
hu      ALL=(root)      NOPASSWD:/usr/sbin,!/usr/sbin/useradd

#无需输入密码
[hu@rocky8-153 ~]$sudo -l
...
    (root) NOPASSWD: /usr/sbin, !/usr/sbin/useradd

#可执行userdel
[hu@rocky8-153 ~]$userdel abc
userdel: user 'abc' does not exist

[hu@rocky8-153 ~]$useradd xiaobai
useradd: Permission denied.
useradd: cannot lock /etc/passwd; try again later.

#无执行权限
[hu@rocky8-153 ~]$sudo useradd xiaobai
Sorry, user hu is not allowed to execute '/sbin/useradd xiaobai' as root on rocky8-153.
#指定默认切换账户
hu      ALL=(xiaoq,hua) ALL

[hu@rocky8-153 ~]$sudo -l
...
User hu may run the following commands on rocky8-153:
    (xiaoq, hua) ALL

#不指定默认以root身份执行
[hu@rocky8-153 ~]$sudo touch /tmp/hu1
Sorry, user hu is not allowed to execute '/bin/touch /tmp/hu1' as root on rocky8-153.

[hu@rocky8-153 ~]$sudo -u xiaoq touch /tmp/hu1
[hu@rocky8-153 ~]$ll /tmp
total 4
-rw-r--r--. 1 xiaoq xiaoq   0 Oct 13 13:59 hu1

Defaults:hu runas_default=hua
hu      ALL=(xiaoq,hua) ALL

[hu@rocky8-153 ~]$sudo touch /tmp/hu2

[hu@rocky8-153 ~]$ll /tmp
total 4
-rw-r--r--. 1 xiaoq xiaoq   0 Oct 13 13:59 hu1
-rw-r--r--. 1 hua   hua     0 Oct 13 14:02 hu2
#配置中转规则
xiaoq   ALL=(root)      /usr/bin/cat /etc/shadow
hu      ALL=(xiaoq)     /usr/bin/sudo /usr/bin/cat /etc/shadow

[xiaoq@rocky8-153 ~]$sudo cat /etc/shadow
[sudo] password for xiaoq: 
root:$6$v5mMTSV2.aqFUYXz$6Ou0LjeYWF1DBxi7T4oO90cvg6UFBv3WJ.Ux9ltw/QDAZnwGIQJEEm7FbT2AYTUiAtn9ck.UIAcz5weoLtfmM.::0:99999:7:::
bin:*:19767:0:99999:7:::
...

[hu@rocky8-153 ~]$sudo -u xiaoq sudo /usr/bin/cat /etc/shadow 
[sudo] password for hu: 
[sudo] password for xiaoq: 
root:$6$v5mMTSV2.aqFUYXz$6Ou0LjeYWF1DBxi7T4oO90cvg6UFBv3WJ.Ux9ltw/QDAZnwGIQJEEm7FbT2AYTUiAtn9ck.UIAcz5weoLtfmM.::0:99999:7:::
bin:*:19767:0:99999:7:::
...
#配置BUG
hu    ALL=(root)     NOPASSWD: /usr/bin/cat /var/log/message*

hu@ubuntu:~$ cat /var/log/messages
cat: /var/log/messages: Permission denied

hu@ubuntu:~$ sudo cat /var/log/messages 
...

#bug,能打开其他文件
#*匹配到了后面的文件
hu@ubuntu:~$ sudo cat /var/log/messages /etc/shadow 

#解决
hu   ALL=(root)     NOPASSWD: /usr/bin/cat /var/log/message*, !/usr/bin/cat /var/log/mesasge* *
#修改生命周期时长
[root@rocky8-153 ~]#sudo -V | grep time
Lecture user the first time they run sudo
Authentication timestamp timeout: 5.0 minutes    #默认一次密码有效时长 5min
Password prompt timeout: 5.0 minutes
Path to authentication timestamp dir: /run/sudo/ts    #sudo切换用户的认证时间记录文件
Type of authentication timestamp record: tty
Sudo log server timeout in seconds: 30

#修改配置文件,添加
[root@rocky8-153 ~]#vim /etc/sudoers
Defaults timestamp_timeout=1

#查看
[root@rocky8-153 ~]#sudo -V | grep time
Lecture user the first time they run sudo
Authentication timestamp timeout: 1.0 minutes
Password prompt timeout: 5.0 minutes
Path to authentication timestamp dir: /run/sudo/ts
Type of authentication timestamp record: tty
Sudo log server timeout in seconds: 30

#查看生命周期文件
[root@rocky8-153 ~]#ll -h /run/sudo/ts
total 0

[hu@rocky8-153 ~]$sudo -l
[sudo] password for hu: 

[root@rocky8-153 ~]#ll -h /run/sudo/ts/
total 4.0K
-rw-------. 1 root hu 112 Oct 13 15:22 hu

#到时间后需要再次输入
[hu@rocky8-153 ~]$sudo -l
[sudo] password for hu: 

#删除文件
[root@rocky8-153 ~]#rm -rf /run/sudo/ts/*

[root@rocky8-153 ~]#sudo -K    #重置生命周期
[root@rocky8-153 ~]#sudo -k

#sudo 生命周期采用的是续命机制,如果认证有效期是2分钟,则只要在2分钟内执行一次 sudo 命令,就
可以一直不用输入密码。

三、PAM

        PAM(Pluggable Authentication Modules,可插拔认证模块)是Linux和Unix系统中用于统一管理用户认证的核心框架。通过提供一些动态链接库和一套统一的API,将系统提供的服务和该服务的认证方式分开,使得系统管理员可以灵活的根据需要给不同的服务配置不同的认证方式,而无需更改服务程序的一种认证框架。 http://www.linux-pam.org/

        例如:无论用户使用密码、密钥等方式登录,应用程序只需调用PAM接口即可完成认证,无需关心底层实现细节。

        

PAM模块帮助

        http://www.linux-pam.org/Linux-PAM-html/ 在线文档
        http://www.linux-pam.org/documentation/   离线文档

       

man pam

#查询模块在哪一个man 章节
man -k 模块名 

[root@ubuntu ~]# man -k pam_nologin
pam_nologin (8)      - Prevent non-root users from login

#在指定章节查询模块
man N 模块名
[root@ubuntu ~]# man 8 pam_nologin

        PAM提供了对所有服务进行认证的中央机制,适用于本地登录,远程登录等程序。如:telnet,rlogin,fsh,ftp,点对点协议PPP,su等应用程序中。

        系统管理员通过PAM配置文件来制定不同应用程序的不同认证策略;应用程序开发者通过在服务程序中使用PAM API(pam_xxxx( ))来实现对认证方法的调用;而PAM服务模块的开发者则利用PAM SPI来编写模块(主要调用函数pam_sm_xxxx( )供PAM接口库调用,将不同的认证机制加入到系统中;PAM接口库(libpam)则读取配置文件,将应用程序和相应的PAM服务模块联系起来。

1、PAM相关文件

#rocky
#包名
[root@rocky8-153 ~]#rpm -q pam
pam-1.3.1-38.el8_10.x86_64

#模块文件
[root@rocky8-153 ~]#ls /lib64/security/*so

#特定模块相关的设置文件
[root@rocky8-153 ~]#ll /etc/security/

#应用程序调用PAM模块的配置文件
#主配置文件,默认不存在,一般不使用主配置
[root@rocky8-153 ~]#ll /etc/pam.conf/
ls: cannot access '/etc/pam.conf/': No such file or directory

#为每种应用模块提供一个专用的配置文件,如果该目录存在,pam.conf 无效
[root@rocky8-153 ~]#ll /etc/pam.d/

#ubuntu
#包名
root@ubuntu-158:~# dpkg -l libpam-runtime
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version          Architecture Description
+++-==============-================-============-===================================
ii  libpam-runtime 1.5.3-7ubuntu4.4 all          Runtime support for the PAM library

#模块文件
root@ubuntu-158:~# ls /usr/lib/x86_64-linux-gnu/security/

#特定模块相关的设置文件
root@ubuntu-158:~# ls /etc/security/

#应用程序调用PAM模块的配置文件
#主配置文件,默认不存在,一般不使用主配置
root@ubuntu-158:~# ls -l  /etc/pam.conf
-rw-r--r-- 1 root root 552 May  1  2024 /etc/pam.conf

#为每种应用模块提供一个专用的配置文件,如果该目录存在,pam.conf 无效
root@ubuntu-158:~# ls -l /etc/pam.d

查看程序是否支持PAM

root@ubuntu-158:~# ldd `which passwd` | grep libpam
	libpam.so.0 => /lib/x86_64-linux-gnu/libpam.so.0 (0x00007843905a0000)
	libpam_misc.so.0 => /lib/x86_64-linux-gnu/libpam_misc.so.0 (0x0000784390599000)

#不支持
root@ubuntu-158:~# ldd `which vim` | grep libpam

2、PAM工作原理

        PAM认证一般遵循这样的顺序:Service(服务)→PAM(配置文件)→pam_*.so。
        PAM认证首先要确定那一项服务,然后加载相应的PAM的配置文件(位于/etc/pam.d/下), 后调用认证文件(位于/lib64/security/下)进行安全认证。

        

PAM认证过程:

        1、使用者执行/usr/bin/passwd 程序,并输入密码。

        
        2、passwd开始调用PAM模块,PAM模块会搜寻passwd程序的PAM相关设置文件,这个设置文件一般是 在/etc/pam.d/里边的与程序同名的文件,即PAM会搜寻/etc/pam.d/passwd此设置文件。

        
        3.、经由/etc/pam.d/passwd设定文件的数据,取用PAM所提供的相关模块来进行验证。

        
        4.、将验证结果回传给passwd这个程序,而passwd这个程序会根据PAM回传的结果决定下一个动作(重新输入密码或者通过验证)。

3、PAM 配置文件格式说明

#主配置文件,一般不使用主配置
[root@ubuntu ~]# cat /etc/pam.conf

#查看主配置文件帮助
[root@ubuntu ~]# man pam.conf

#主配置文件格式
application    type    control    module-path    arguments

#为每种应用模块提供一个专用的配置文件
[root@ubuntu ~]# ll /etc/pam.d/

#专用配置文件格式
type    control    module-path    arguments

#配置字段说明
application  #指服务名,如 telnet、login、ftp等,OTHER代表所有没有在该文件中明确配置的其它服务
type         #指模块类型,即功能
control      #PAM库该如何处理与该服务相关的PAM模块的成功或失败情况,一个关健词实现
module-path  #用来指明本模块对应的程序文件的路径名
arguments    #用来传递给该模块的参数

type(模块类型)

说明
auth 帐号的认证和授权
account账户管理,用来设置某此功能和特性,如限制/允许用户对某个服务的访问时间等
password用户修改密码时密码复杂度检查机制等功能
session用户会话期间的控制,如最多打开的文件数,最多的进程数等
-type表示因为缺失而不能加载的模块将不记录到系统日志,对于那些不总是安装在系统上
的模块有用

control

说明

required一票否决,表示本模块必须返回成功才能通过认证,但是如果该模块返回失败,也不
会立即通知用户,而是要等到同一type中的所有模块全部执行完毕,再将失败结果返
回给应用程序,即为必要条件
requisite一票否决,该模块必须返回成功才能通过认证,但是一旦该模块返回失败,将不再执
行同一type内的任何模块,而是直接将控制权返回给应用程序,是一个必要条件
sufficient一票通过,表明本模块返回成功则通过身份认证的要求,不必再执行同一type内的其
它模块,但如果本模块返回失败可忽略,即为充分条件,优先于前面的required和requisite
optional表明本模块是可选的,它的成功与否不会对身份认证起关键作用,其返回值一般被忽略
 
include调用其他的配置文件中定义的配置信息
substack调用其他配置文件中的流程,并将整个运行结果作为该行的结果进行输出
在 control 列中,对于更复杂的语法,可以写成如下格式
[value1=action1 value2=action2 ...]

valueN对应于在为其定义行的模块中调用的函数的返回代码,取值如下
success, open_err, symbol_err, service_err, system_err, buf_err, perm_denied, 
auth_err, cred_insufficient, authinfo_unavail, user_unknown,maxtries, 
new_authtok_reqd, acct_expired, session_err, cred_unavail, cred_expired, 
cred_err, no_module_data, conv_err, authtok_err,authtok_recover_err, 
authtok_lock_busy, authtok_disable_aging, try_again, ignore, abort, 
authtok_expired, module_unknown, bad_item, conv_again,incomplete, and default

module-path

值示例说明
/path/XYZ.so模块文件所在绝对路径
pam_nologin.so模块文件所在相对路径,表示 so 文件在 /lib64/security/ 目录下
postlogin有些模块有自已的专有配置文件,这种写法表示直接使用另一个配置

arguments

                每个模块的参数都不相同,一般是由该模块的开发者自定义,下列是各模块都支持的通用参数。

值 说明
debug该模块应当用syslog( )将调试信息写入到系统日志文件中
no_warn表明该模块不应把警告信息发送给应用程序
use_first_pass该模块不能提示用户输入密码,只能从前一个模块得到输入密码
try_first_pass该模块首先用前一个模块从用户得到密码,如果该密码验证不通过,再提
示用户 输入新密码
use_mapped_pass该模块不能提示用户输入密码,而是使用映射过的密码
expose_account 允许该模块显示用户的帐号名等信息,一般只能在安全的环境下使用
#配置文件示例
root@ubuntu-158:~# cat /etc/pam.d/sshd | grep -v "^#"

@include common-auth

account    required     pam_nologin.so


@include common-account

session [success=ok ignore=ignore module_unknown=ignore default=bad]        pam_selinux.so close

session    required     pam_loginuid.so

session    optional     pam_keyinit.so force revoke

@include common-session

session    optional     pam_motd.so  motd=/run/motd.dynamic
session    optional     pam_motd.so noupdate

session    optional     pam_mail.so standard noenv # [1]

session    required     pam_limits.so

session    required     pam_env.so # [1]
session    required     pam_env.so envfile=/etc/default/locale

session [success=ok ignore=ignore module_unknown=ignore default=bad]        pam_selinux.so open

@include common-password

        修改PAM配置文件将马上生效,所以我们在编辑pam规则时,保持至少打开一个root会话,以防止root身份验证错误。

4、常用PAM模块

①pam_nologin.so 模块

        功能:如果 /etc/nologin 文件存在,将导致非root用户不能登录,当用户远程连接时,会显示/etc/nologin 中的内容,并拒绝之,前提是相应的服务使用了该模块,此规则才会生效。

        由于 su 服务没有使用该模块,所以使用 su 切换账号,不受影响。

#查看文档
man pam_nologin
#查询哪些服务使用了该模块
root@ubuntu-158:~# grep pam_nologin /etc/pam.d/*
/etc/pam.d/cockpit:account    required     pam_nologin.so
/etc/pam.d/login:auth       requisite  pam_nologin.so
/etc/pam.d/ppp:auth	required	pam_nologin.so
/etc/pam.d/sshd:account    required     pam_nologin.so
#sshd使用该模块,测试
#创建/etc/nologin文件,普通用户立即无法远程登录
root@ubuntu-158:~# touch /etc/nologin

root@ubuntu-158:~# stat /etc/nologin
  File: /etc/nologin
  Size: 0         	Blocks: 0          IO Block: 4096   regular empty file
Device: 252,0	Inode: 3015323     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2025-10-13 17:09:02.139232560 +0800
Modify: 2025-10-13 17:09:02.139232560 +0800
Change: 2025-10-13 17:09:02.139232560 +0800
 Birth: 2025-10-13 17:09:02.139232560 +0800

[C:\~]$ ssh hu@10.0.0.158
...
Ubuntu 25.04
Connection closing...Socket close.

Connection closed by foreign host.

Disconnected from remote host(10.0.0.158:22) at 17:10:21.

Type `help' to learn how to use Xshell prompt.

#普通用户远程登录的拒绝日志,可以在 /var/log/auth.log 文件中查询,明确说明是pam account 配置
拒绝登录
root@ubuntu-158:~# tail -f /var/log/auth.log
2025-10-13T17:10:21.195448+08:00 ubuntu-158 sshd-session[20061]: Failed password for hu from 10.0.0.1 port 55972 ssh2
2025-10-13T17:10:21.195998+08:00 ubuntu-158 sshd-session[20061]: fatal: Access denied for user hu by PAM account configuration [preauth]

#写入内容到文件
root@ubuntu-158:~# echo "pam deny user login" > /etc/nologin

#普通用户远程登录,被拒绝时能看到 "pam deny user login" 的提示
[C:\~]$ ssh hu@10.0.0.158
...
Ubuntu 25.04
pam deny user login

Connection closing...Socket close.

Connection closed by foreign host.

Disconnected from remote host(10.0.0.158:22) at 17:14:36.

Type `help' to learn how to use Xshell prompt.

#删除/etc/nologin文件
root@ubuntu-158:~# rm -rf /etc/nologin

[C:\~]$ ssh hu@10.0.0.158


Connecting to 10.0.0.158:22...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
Ubuntu 25.04
...
hu@ubuntu-158:~$ 

②pam_limits.so 模块

        功能:在用户级别实现对其可使用的资源的限制,例如:可打开的文件数量,可运行的进程数量,可用内存空间等。

#查看有哪些服务使用了该模块
root@ubuntu-158:~# grep pam_limits /etc/pam.d/*
/etc/pam.d/atd:session    required   pam_limits.so
/etc/pam.d/cron:session    required   pam_limits.so
/etc/pam.d/login:session    required   pam_limits.so
/etc/pam.d/runuser:session		required	pam_limits.so
/etc/pam.d/sshd:session    required     pam_limits.so
/etc/pam.d/su:session    required   pam_limits.so
/etc/pam.d/sudo:session    required   pam_limits.so
/etc/pam.d/sudo-i:session    required   pam_limits.so
#查看默认资源限制
root@ubuntu-158:~# ulimit -a
real-time non-blocking time  (microseconds, -R) unlimited
core file size              (blocks, -c) 0
data seg size               (kbytes, -d) unlimited
scheduling priority                 (-e) 0
file size                   (blocks, -f) unlimited
pending signals                     (-i) 6049
max locked memory           (kbytes, -l) 204580
max memory size             (kbytes, -m) unlimited
open files                          (-n) 1024
pipe size                (512 bytes, -p) 8
POSIX message queues         (bytes, -q) 819200
real-time priority                  (-r) 0
stack size                  (kbytes, -s) 8192
cpu time                   (seconds, -t) unlimited
max user processes                  (-u) 6049
virtual memory              (kbytes, -v) unlimited
file locks                          (-x) unlimited

ulimit命令

        ulimit是linux shell的内置命令,它具有一套参数集,用于对shell进程及其子进程进行资源限制。使用ulimit对参数进行修改,会立即生效,但其修改是临时性的,重新登录后无效。        

        ulimit 的修改,只影响当前的shell进程及其子进程,每个进程都有自己独有的limits 值。如果想永久生效,可以写在 profile 文件中。

ulimit [-SHabcdefiklmnpqrstuvxPT] [limit]

#选项
S         #设置软件层面的资源限制,超出时会告警
H         #设置硬件资源限制,无法超过阀值
a         #列出所有限制项的的值
b         #设置套接字缓冲区大小kb
c         #设置core文件的最大值,单位为block,每个block 默认512字节
d         #每个进程数据段的最大值,单位kb
e         #设置进程默认调度优先级(nice值)
f         #当前shell及子进程可创建的最大文件容量,单位block
i         #设置最大的等待信号
l         #可以锁定的物理内存的最大值,单位kb
m         #设置可以使用的常驻内存的最大值,单位kb
n         #设置内核可以同时打开的文件描述符的最大值
p         #设置管道缓冲区的最大值,单位kb
q         #消息队列最大字节数
r         #设置最大实时调度优先级
s         #设置堆栈的最大值,单位kb
t         #设置CPU使用时间的最大上限,单位seconds
u         #最大用户进程数
v         #虚拟内存最大值kb
x         #最多可以开多少个锁文件
P         #最大进程数
T         #最大线程数

#core 文件,当某些程序发生错误时,系统可能会将该程序在内存中的信息写成文件(除错用),这种文件就被称为核心文件(core file)
#查询时,若不加H或S参数,默认显示的是软限制
#修改时,若不加H或S参数,两个参数一起改变
#unlimited 是一个特殊值,用于表示不限制
#压力测试
[root@rocky8-153 ~]#systemctl start nginx.service

#限制了同时打开最大文件数
#-n 总请求数
#-c 并发客户端数
[root@rocky8-153 ~]#ab -c 1100 -n 10000 http://10.0.0.153/
This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 10.0.0.153 (be patient)
socket: Too many open files (24)

#修改同时打开最大文件数再测试
[root@rocky8-153 ~]#ulimit -n 10240

[root@rocky8-153 ~]#ulimit -n 10240
[root@rocky8-153 ~]#ab -c 1100 -n 10000 http://10.0.0.153/
This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 10.0.0.153 (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
^C
#使用 pam_limits 模块来配置相关参数
[root@rocky8-153 ~]#vim /etc/security/limits.conf 

#—配置文件格式
#<domain>      <type>  <item>         <value>
#

#*               soft    core            0
#*               hard    rss             10000
#@student        hard    nproc           20
#@faculty        soft    nproc           20
#@faculty        hard    nproc           50
#ftp             hard    nproc           0
#@student        -       maxlogins       4

#—格式说明
#<domain>     <type>    <item>       <value>
#应用对象     限制类型    限制的资源     指定具体值

#应用于哪些对象
username     #单个用户
@group       #组内所有用户
*            #所有用户
%            #仅用于限制 maxlogins limit,可以使用 %group 语法. 单%相当于*,表示对所有用户的maxsyslogins limit限制, %group 表示限制此组中的所有用户总的最大登录数

#限制的类型
soft         #软限制,普通用户自己可以修改
hard         #硬限制,由root用户设定,且通过kernel强制生效
-            #二者同时限定

#限制的资源
|core|data|fsize|memlock|nofile|rss|stack|cpu|nproc|as|maxlogins|maxsyslogins|priority|locks|sigpending|msgqueue|nice|rtprio
hu@ubuntu-158:~$ vim /etc/security/limits.conf 
hu - nproc 10    #表示限制用户 hu 最多开10个进程

root@ubuntu-158:~# ulimit -u
6049

root@ubuntu-158:~# su - hu

hu@ubuntu-158:~$ ulimit -u
10

#进程达到上限报错
hu@ubuntu-158:~$ bash
hu@ubuntu-158:~$ bash
hu@ubuntu-158:~$ bash
/usr/bin/lesspipe: 1: Cannot fork
hu@ubuntu-158:~$ bash
/usr/bin/lesspipe: 29: Cannot fork
hu@ubuntu-158:~$ bash
bash: fork: retry: Resource temporarily unavailable
bash: fork: retry: Resource temporarily unavailable
bash: fork: retry: Resource temporarily unavailable
bash: fork: retry: Resource temporarily unavailable
^Cbash: fork: Interrupted system call

注意:systemd 的service 资源设置需要单独配置

[root@rocky8-153 ~]#cat /etc/security/limits.conf 
# /etc/security/limits.conf
#
#This file sets the resource limits for the users logged in via PAM.
#It does not affect resource limits of the system services.
#
...

        在Centos7以上版本中,使用Systemd替代了之前的SysV。/etc/security/limits.conf文件的配置作用域缩小。

        
        /etc/security/limits.conf的配置,只适用于通过PAM认证登录用户的资源限制,它对systemd的service的资源限制不生效。因此登录用户的限制,通过/etc/security/limits.conf与/etc/security/limits.d下的文件设置即可。

        
        对于systemd service的资源设置,则需修改全局配置,全局配置文件放在/etc/systemd/system.conf和/etc/systemd/user.conf,同时也会加载两个对应目录中的所有.conf文件/etc/systemd/system.conf.d/*.conf 和 /etc/systemd/user.conf.d/*.conf。

        
        system.conf是系统实例使用的,user.conf是用户实例使用的。

[root@rocky8-153 ~]#vim /etc/systemd/system.conf
#DefaultLimitNOFILE=100000             #控制进程能打开的最大文件描述符数量
#DefaultLimitNPROC=65536               #限制用户可创建的进程数

[root@ubuntu ~]# cat /etc/systemd/system.conf 
#DefaultLimitNOFILE=1024:524288
#DefaultLimitNPROC=

#或者针对指定的service添加下面行
[root@ubuntu ~]## vim /usr/lib/systemd/system/nginx.service
[Service]
LimitNOFILE=100000
LimitNPROC=65535
#查看指定进程的资源限制
root@ubuntu-158:~# cat /proc/16338/limits
Limit                     Soft Limit           Hard Limit           Units     
Max cpu time              unlimited            unlimited            seconds   
Max file size             unlimited            unlimited            bytes     
Max data size             unlimited            unlimited            bytes     
Max stack size            8388608              unlimited            bytes     
Max core file size        0                    unlimited            bytes     
Max resident set          unlimited            unlimited            bytes     
Max processes             6049                 6049                 processes 
Max open files            1024                 1073741816           files     
Max locked memory         209489920            209489920            bytes     
Max address space         unlimited            unlimited            bytes     
Max file locks            unlimited            unlimited            locks     
Max pending signals       6049                 6049                 signals   
Max msgqueue size         819200               819200               bytes     
Max nice priority         0                    0                    
Max realtime priority     0                    0                    
Max realtime timeout      unlimited            unlimited            us 
#限制用户最多打开的文件数和运行进程数,并持久保存
[root@rocky8-153 ~]#cat /etc/pam.d/system-auth
session     required      pam_limits.so
...

[root@rocky8-153 ~]#vim /etc/security/limits.conf 
 
#用户apache可打开10240个文件
apache  - nofile 10240

#用户hu不能运行超过10个进程
hu hard nproc 10

#限制hu用户最大的同时登录次数
[root@rocky8-153 ~]#vim /etc/security/limits.conf
hu - maxlogins 2

#用户hu创建会话并登录

[C:\~]$ 
...

Too many logins for 'hu'.
Last login: Mon Oct 13 18:16:30 2025 from 10.0.0.1

Connection closed.

Disconnected from remote host(10.0.0.153:22) at 18:16:35.

Type `help' to learn how to use Xshell prompt.

③pam_google_authenticator 模块

        MFA:Multi-Factor Authentication ( 多因子验证)是一种简单有效的最佳安全实践方法,它能够在用户名和密码之外再额外增加一层安全保护。
        pam_google_authenticator 功能:实现SSH登录的两次身份验证,先验证APP的数字码,再验证root用户的密码,都通过才可以登录。

#服务器上安装包
#安装epel源
[root@rocky86 ~]# yum install epel-release

#安装软件包
[root@rocky86 ~]# yum install -y google-authenticator

#ubuntu中安装
[root@ubuntu ~]# apt install libpam-google-authenticator

#修改配置文件,在最上面新增一行
vim /etc/pam.d/sshd
auth   required     pam_google_authenticator.so

#修改配置文件
vim /etc/ssh/sshd_config
KbdInteractiveAuthentication yes

#重启服务
systemctl restart sshd

root@ubuntu-158:~# google-authenticator 

Do you want authentication tokens to be time-based (y/n) y        #回答y
Warning: pasting the following URL into your browser exposes the OTP secret to Google:
  https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/root@ubuntu-158%3Fsecret%3D3QYKRK7D4S7NDYL467YO3C5LTE%26issuer%3Dubuntu-158    #复制该链接,浏览器中打开,会显示一个二维码,然后用手机上的验证器扫描,得到一组验证码
...                              
Your new secret key is: 3QYKRK7D4S7NDYL467YO3C5LTE
Enter code from app (-1 to skip): 554425    #将手机上的验证码输入此处
Code confirmed
Your emergency scratch codes are:
  39369168
  25501401
  92815134
  89687936
  37157083

Do you want me to update your "/root/.google_authenticator" file? (y/n) y      #后续一直回答y

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y

By default, a new token is generated every 30 seconds by the mobile app.
In order to compensate for possible time-skew between the client and the server,
we allow an extra token before and after the current time. This allows for a
time skew of up to 30 seconds between authentication server and client. If you
experience problems with poor time synchronization, you can increase the window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the current
code, and the 8 next codes). This will permit for a time skew of up to 4 minutes
between client and server.
Do you want to do so? (y/n) y

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting? (y/n) y

#测试远程连接
C:\Users\HhAosocool>ssh root@10.0.0.158
(root@10.0.0.158) Verification code:     #先输入手机上的验证码
(root@10.0.0.158) Password:              #再输入远程连接密码

#先输入验证码还是先输入 ssh 远程密码
#取决于 /etc/pam.d/sshd 文件中的配置位置

#如果手机无法使用,可以使用初始化时生成的5个密码
#但是上述5个密码,每个都只能使用一次
#实际上,这5个密码,可以人为手动修改,保证一直够
root@ubuntu-158:~# ls -l .google_authenticator 
-r-------- 1 root root 136 Oct 13 18:48 .google_authenticator

root@ubuntu-158:~# cat .google_authenticator 
3QYKRK7D4S7NDYL467YO3C5LTE
" RATE_LIMIT 3 30
" WINDOW_SIZE 17
" DISALLOW_REUSE
" TOTP_AUTH
39369168
25501401
92815134
89687936
37157083

#为什么知道手机上的码是正确的呢?
#app扫描二维码,得到主机信息,于是手机app和linux主机中的程序
#使用相同算法生成随机码,包含两个变量主机信息和时间,因此可以匹配
#如果双方时间不同,那么验证码则永远不会匹配。

四、时间同步服务

        互联网中的很多服务都要依赖时间的同步,如果时间不同步,则有很多网络服务都不能用。

1、ntp

        将系统时钟和世界协调时UTC同步,精度在局域网内可达0.1ms,在互联网上绝大多数的地方精度可以达到1-50ms。利用NTP(Network Time Protocol) 协议使网络中的各个计算机时间达到同步。(早期项目,Centos8以后不再使用)

        ntp 是使用渐进性同步机制,如果本地时间与标准时间相差较大,则需要一定的时间才能同步完成。

root@rocky8-153 ~]#yum list ntp
Last metadata expiration check: 2:28:17 ago on Mon 13 Oct 2025 05:43:12 PM CST.
Error: No matching Packages to list

[root@rocky8-153 ~]#yum search ntp
...
chrony.x86_64 : An NTP client/server
...

root@ubuntu-158:~# apt list ntp
ntp/plucky 1:4.2.8p15+dfsg-2~1.2.3+dfsg1-3 all

2、chrony

        实现NTP协议的的自由软件。可使系统时钟与NTP服务器,参考时钟(例如GPS接收器)以及使用手表和键盘的手动输入进行同步。还可以作为NTPv4(RFC 5905)服务器和对等体运行,为网络中的计算机提供时间服务。
        设计用于在各种条件下良好运行,包括间歇性和高度拥挤的网络连接,温度变化(计算机时钟对温度敏感),以及不能连续运行或在虚拟机上运行的系统。

        

优势:(首次立即同步,后续渐进同步)

        1、更快的同步只需要数分钟而非数小时时间,从而最大程度减少了时间和频率误差,对于并非全天 24 小时运行的虚拟计算机而言非常有用。
        2、能够更好地响应时钟频率的快速变化,对于具备不稳定时钟的虚拟机或导致时钟频率发生变化的节能技术而言非常有用。
        3、在初始同步后,它不会停止时钟,以防对需要系统时间保持单调的应用程序造成影响。
        4、在应对临时非对称延迟时(例如,在大规模下载造成链接饱和时)提供了更好的稳定性。
        5、无需对服务器进行定期轮询,因此具备间歇性网络连接的系统仍然可以快速同步时钟。

        

文档:https://chrony.tuxfamily.org/ 官方网站

           https://chrony.tuxfamily.org/documentation.html 官方文档 

[root@rocky8-153 ~]#yum list chrony
Last metadata expiration check: 2:31:19 ago on Mon 13 Oct 2025 05:43:12 PM CST.
Installed Packages
chrony.x86_64                                        4.5-2.el8_10                                        @baseos

[root@rocky8-153 ~]#rpm -q chrony
chrony-4.5-2.el8_10.x86_64

root@ubuntu-158:~# dpkg -l chrony
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
un  chrony         <none>       <none>       (no description available)

root@ubuntu-158:~# apt install chrony

①chrony文件组成

#可执行程序

#命令行用户工具,用于监控性能并进行多样化的配置。它可以在chronyd实例控制的计算机上工作,也可在一台不同的远程计算机上工作
[root@ubuntu ~]# ll /usr/bin/chronyc 
-rwxr-xr-x 1 root root 89256 Feb  8  2022 /usr/bin/chronyc*

#后台运行的守护进程,用于调整内核中运行的系统时钟和时钟服务器同步。它确定计算机增减时间的比率,并对此进行补偿
[root@ubuntu ~]# ll /usr/sbin/chronyd 
-rwxr-xr-x 1 root root 285712 Feb  8  2022 /usr/sbin/chronyd*

#服务unit文件
root@ubuntu-158:~# systemctl status chronyd.service

#配置文件
root@ubuntu-158:~# tree /etc/chrony
/etc/chrony
├── chrony.conf        #主配置文件
├── chrony.keys
├── conf.d
│   ├── README
│   └── ubuntu-nts.conf
├── nts-bootstrap-staging-ubuntu.crt
├── nts-bootstrap-ubuntu.crt
└── sources.d
    ├── README
    └── ubuntu-ntp-pools.sources

3 directories, 8 files

#监听端口
服务端: 123/udp         #其它机器通过此端口连接本机,将本机当作ntp服务器
客户端: 323/udp         #本机通过此端口同步时间

②配置文件说明

https://chrony.tuxfamily.org/doc/3.5/chrony.conf.html     #官方文档

[root@ubuntu ~]# man chrony.conf     #帮助手册
常用字段说明
server时钟服务器地址,加iburst 选项表示服务可用时,一次发送八个数据包,包间隔通常为2秒,可加快初始同步速度
pool语法和指令与server 字段相似,不同之处在于其指定的NTP服务可以解析多个IP地址
driftfile根据实际时间计算出计算机增减时间的比率,将它记录到一个文件中,会在重启后为系统时钟作出补偿
rtcsync启用内核模式,系统时间每11分钟会拷贝到实时时钟(RTC)
allow指定可以使用本机服务的设备,格式可以是IP,子网,网段
deny指定不可以使用本机服务的设备,格式可以是IP,子网,网段
cmdallow指定设备可以通过chronyd使用控制指令
cmddeny指定设备不可以通过chronyd使用控制指令
bindcmdaddress允许chronyd监听哪个接口来接收由chronyc执行的命令
makestep通常chronyd将根据需求通过减慢或加速时钟,使得系统逐步纠正所有时间偏差。在某些特定情况下,系统时钟可能会漂移过快,导致该调整过程消耗很长的时间来纠正系统时钟。该指令强制chronyd在调整期大于某个阀值时调整系统时钟
local stratum 10即使server指令中时间服务器不可用,也允许将本地时间作为标准时间授时给其它客户端

③NTP客户端工具

chrony可以运行在交互和非交互式两种方式

#交互式客户端下常用字命令

help             #显示帮助信息
accheck          #检查是否对特定主机可访问当前服务器
activity         #显示有多少NTP源在线/离线
sources [-v]     #显示当前时间源的同步信息
sourcestats [-v] #显示当前时间源的同步统计信息
add server       #手动添加一台新的NTP服务器
clients          #报告已访问本服务器的客户端列表
delete           #手动移除NTP服务器或对等服务器
settime          #手动设置守护进程时间
tracking         #显示系统时间信息
#启动服务
[root@rocky86 ~]# systemctl is-active chronyd.service
inactive

[root@rocky86 ~]# systemctl start chronyd.service

[root@rocky86 ~]# systemctl is-active chronyd.service
active

[root@ubuntu-158 ~]#chronyc
chrony version 4.6.1
Copyright (C) 1997-2003, 2007, 2009-2024 Richard P. Curnow and others
chrony comes with ABSOLUTELY NO WARRANTY.  This is free software, and
you are welcome to redistribute it under certain conditions.  See the
GNU General Public License version 2 for details.

chronyc> tracking
Reference ID   : CA701FC5 (dns2.synet.edu.cn) #当前同步的NTP服务器ID和IP地址
Stratum        : 2                            #层次,跳数
Ref time (UTC) : Tue May 30 01:00:39 2023     #源最后一次获取到的UTC时间
System time    : 0.000000001 seconds fast of NTP time #当前系统时间与NTP服务时间的偏移量
Last offset    : +0.000733123 seconds         #最后偏移上次时钟更新时本地偏移量
RMS offset     : 0.000733123 seconds          #偏移量平均值
Frequency      : 12.340 ppm fast              #系统时钟偏差值的速率,单位为百万分之一
Residual freq  : +588.341 ppm                 #当前源的剩余频率
Skew           : 9.803 ppm                    #估计误差范围,单位为百万分之一
Root delay     : 0.022467736 seconds          #到根设备的网络延迟总和
Root dispersion: 0.003619912 seconds          #到根设备的网络延迟平均值 
Update interval: 0.0 seconds                  #最近两次时钟更新之间的间隔
Leap status    : Normal                       #跳跃状态
#列出配置中可用的ntp服务
chronyc> activity
200 OK
5 sources online
0 sources offline
0 sources doing burst (return to online)
0 sources doing burst (return to offline)
0 sources with unknown address
chronyc> 

#列出配置中所有ntp服务源的状态
chronyc> sourcestats
Name/IP Address            NP  NR  Span  Frequency  Freq Skew  Offset  Std Dev
==============================================================================
ntp-nts-2.ps5.canonical.>  26  14   35m     +1.924     27.147  +5044us    21ms
ntp-nts-3.ps5.canonical.>  26  14   35m     +3.377     24.186  +5145us    18ms
ntp-nts-2.ps6.canonical.>   7   5   34m     +6.446     80.441  -6849us    24ms
ntp-nts-3.ps6.canonical.>  10   5   35m    +16.165     33.969    +12ms    11ms
ntp-nts-1.ps5.canonical.>  26  15   35m     +6.489     28.953  +9866us    23ms

#字段说明
Name/IP Address #NTP服务器IP地址或主机名,或者参考时钟的refid值
NP              #当前服务器可用的采样点,用这些点执行线性回归方法来估算偏移值
NR              #最后一次回归计算后具有相同符号的偏差值的运行次数
Span            #最旧样本和最新样本之间的间隔,默认单位秒
Frequency       #NTP服务器的估算偏差值的速率,单位为百万分之一
Freq Skew       #Freq的估计误差范围,单位为百万分之一
Offset          #NTP源服务器的偏移量
Std Dev         #估算的样本标准偏差
#查看上次同步
chronyc> sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^+ ntp-nts-2.ps5.canonical.>     2   8   377   159  -5549us[-5549us] +/-  148ms
^* ntp-nts-3.ps5.canonical.>     2   8   377   160    -35ms[  -33ms] +/-  174ms
^- ntp-nts-2.ps6.canonical.>     2   8   107   472  -4685us[+2010us] +/-  136ms
^- ntp-nts-3.ps6.canonical.>     2   8   301   411    +17ms[  +19ms] +/-  162ms
^- ntp-nts-1.ps5.canonical.>     2   8   377   146    -18ms[  -18ms] +/-  179ms

#字段说明
M               #NTP源 ^表示服务器, = 表示二级时钟, # 表示本地时钟
S               #NTP源状态,*此源己同步, +可接收的源, -合并算法排除的可接受源, ?没连上的源, x认为该源有错, ~不确定的源
Name/IP address #NTP服务器主机名或IP地址或refid值
Stratum         #层次,跳数,1 表示本地时钟,2 表示通过第一层级的服务器实现同步,以此类推
Poll            #NTP源的轮询频率,以秒为单位,值为基数2的对数,6表示64秒进行一次同步,chronyd会自动调整此值    
Reach           #8进制数,表示源的可达性,每次对钟收发8个数据包,337表示最后一次同步8个数据包都收到,377二进制就是8个1
LastRx          #多久前从源收到最后一次数据,默认单位是秒
Last sample     #上次同步时NTP服务器与本地时间的偏移值 调整后偏移量[实际偏移量]实际测量中的误差范围,+表示正偏移,本地快
root@ubuntu-158:~# vim /etc/chrony/sources.d/ubuntu-ntp-pools.sources
#注释pool行

#添加
root@ubuntu-158:~# vim /etc/chrony/chrony.conf 
server ntp.aliyun.com iburst

#重启服务
root@ubuntu-158:~# systemctl restart chrony

#查看
chronyc> sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^? 203.107.6.88                  2   6     3     0    +12ms[  +12ms] +/-   17ms
chronyc> sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 203.107.6.88                  2   6    37    15  -3665us[  -16ms] +/-  116ms

#修改时间,查看同步过程
#先重启一下服务,才可以很快的观察到过程,不然要等很久,因为其实质是渐进性同步
root@ubuntu-158:~# date
Mon Oct 13 09:19:50 PM CST 2025

root@ubuntu-158:~# systemctl restart chrony.service;date -s "+10 day"
Thu Oct 23 09:19:59 PM CST 2025

root@ubuntu-158:~# date
Thu Oct 23 09:20:00 PM CST 2025

#查看同步过程
root@ubuntu-158:~# while(true)do chronyc sources;date +%F-%T;sleep 2 ;done
...
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^? 203.107.6.88                  2   6     3     1  +14400m[+14400m] +/-   87ms
2025-10-23-21:20:02
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 203.107.6.88                  2   6     7     1    -37ms[+14400m] +/-   86ms
2025-10-13-21:20:04
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 203.107.6.88                  2   6    17     1  -6687us[  -38ms] +/-   56ms
2025-10-13-21:20:06
^C

root@ubuntu-158:~# date
Mon Oct 13 09:20:51 PM CST 2025
#chrony 是渐进式同步,如果差距过大,想立即同步完成,则可以重启服务
root@ubuntu-158:~# date -s "+10 day"
Thu Oct 23 09:22:03 PM CST 2025

root@ubuntu-158:~# systemctl restart chrony.service

root@ubuntu-158:~# date
Thu Oct 23 09:22:17 PM CST 2025

root@ubuntu-158:~# date
Mon Oct 13 09:22:35 PM CST 2025

④时间工具timedatctl

timedatectl [OPTIONS...] COMMAND ...

#常用选项
-h|--help         #显示帮助信息
--version         #显示版本信息
-a|--all          #显示所有属性
--value           #查询时仅显示值,不显示字段标题

#常用子命令
status             #显示当前时间设置,默认项
show               #以友好格式显示,具体同容同 status 
set-time TIME      #修改时间
set-timezone ZONE  #修改时区
list-timezones     #列出当前可用时区
set-local-rtc BOOL #RPC时间是否关联本地时区
set-ntp BOOL       #是否开启ntp 服务

[root@rocky8-153 ~]#timedatectl
               Local time: Mon 2025-10-13 22:05:14 CST    #本机时间, CST
表示北京时间
           Universal time: Mon 2025-10-13 14:05:14 UTC    #世界标准时间,
UTC表示世界标准时间
                 RTC time: Mon 2025-10-13 14:05:14        #RTC时间,硬件
时间
                Time zone: Asia/Shanghai (CST, +0800)     #本机时区
System clock synchronized: yes        #系统时间是否己同步完成
              NTP service: active     #NTP时间同步服务是否启用
          RTC in local TZ: no         #RTC时间是否关联本机时区

          
          
#RTC Real-Time Clock 硬件时间,来自于时钟芯片
#UTC Coordinated Universal Time 世界协调时间,又称世界标准时间
#GMT Greenwich Mean Time 格林尼治(天文台)标准时间
#开启RTC时间与本地时区绑定
root@ubuntu-157:~# timedatectl set-local-rtc 1

root@ubuntu-157:~# timedatectl
               Local time: Mon 2025-10-13 22:11:09 CST
           Universal time: Mon 2025-10-13 14:11:09 UTC
                 RTC time: Mon 2025-10-13 22:11:09        #与本地时间一致
                Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: yes
 
Warning: The system is configured to read the RTC time in the local time zone.
         This mode cannot be fully supported. It will create various problems
         with time zone changes and daylight saving time adjustments. The RTC
         time is never updated, it relies on external facilities to maintain it.
         If at all possible, use RTC in UTC by calling
         'timedatectl set-local-rtc 0'.
#修改时间
[root@ubuntu ~]# timedatectl set-time "2042-10-15 00:00:00"
[root@ubuntu ~]# date +"%F %T"
2042-10-15 00:00:16

#查看
[root@ubuntu ~]# timedatectl show -a
Timezone=Asia/Shanghai
LocalRTC=no
CanNTP=yes
NTP=yes
NTPSynchronized=no
TimeUSec=Wed 2042-10-15 00:00:18 CST
RTCTimeUSec=Wed 2042-10-15 00:00:18 CST

#修改后某些服务不可用
[root@ubuntu ~]# curl https://www.baidu.com
curl: (60) SSL certificate problem: certificate has expired
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

[root@ubuntu ~]# echo $?
60
#开启ntp时间同步服务
root@ubuntu-158:~# systemctl is-active chronyd.service
inactive

root@ubuntu-158:~# timedatectl set-ntp 1

root@ubuntu-158:~# systemctl is-active chronyd.service
active

#NTP服务开启,时间被同步回来
root@ubuntu-158:~# timedatectl
               Local time: Mon 2025-10-13 22:15:12 CST
           Universal time: Mon 2025-10-13 14:15:12 UTC
                 RTC time: Mon 2025-10-13 14:15:12
                Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no
root@ubuntu-158:~# 

⑤实现私有时间服务

        在同一个网络内,如果有多个需要进行时间同步的服务器,则我们可以在内网自建NTP Server,这样可以节约访问外网的网络资源;另一方面,如果外网不可用,则至少可以保证,内网的NTP服务还是可用的。

#服务端配置
root@ubuntu-158:~# vim /etc/chrony/chrony.conf 
allow 10.0.0.0/24     #允许10.0.0 网段的主机将本机作为时间同步服务器
local stratum 10      #允许本机在不能与外网同步的情况下,还能提供服务

#root@ubuntu-158:~# vim /etc/chrony/sources.d/ubuntu-ntp-pools.sources

#重启服务
root@ubuntu-158:~# systemctl restart chrony.service 

root@ubuntu-158:~# ss -unlp
State     Recv-Q    Send-Q         Local Address:Port       Peer Address:Port   Process                                       
...  
UNCONN    0         0                    0.0.0.0:123             0.0.0.0:*       users:(("chronyd",pid=43636,fd=7))           
UNCONN    0         0                  127.0.0.1:323             0.0.0.0:*       users:(("chronyd",pid=43636,fd=5))           
UNCONN    0         0                      [::1]:323                [::]:*       users:(("chronyd",pid=43636,fd=6)) 
#rocky客户端配置
#添加 server,生产环境下至少两台,保证高可用
[root@rocky8-153 ~]#vim /etc/chrony.conf 
server 10.0.0.158 iburst

#重启服务
[root@rocky8-153 ~]#systemctl restart chronyd.service

#关闭防火墙
[root@rocky8-153 ~]#systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.

[root@rocky8-153 ~]#chronyc  -n sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 10.0.0.158                    3   6   377    23  -1913us[-4736us] +/-   42ms
———————————————————————————————————————————————————————————————————————————————————————————
[root@rocky8-153 ~]#date -s "+10 day"
Thu Oct 23 21:39:42 CST 2025

[root@rocky8-153 ~]#timedatectl
               Local time: Thu 2025-10-23 21:43:53 CST
           Universal time: Thu 2025-10-23 13:43:53 UTC
                 RTC time: Mon 2025-10-13 13:43:59
                Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: no
              NTP service: active
          RTC in local TZ: no

#等待同步成功
[root@rocky8-153 ~]#date
Mon Oct 13 21:58:49 CST 2025
#ubuntu客户端
root@ubuntu-157:~# vim /etc/chrony/sources.d/ubuntu-ntp-pools.sources
#注释pool行

#添加 server,生产环境下至少两台,保证高可用
root@ubuntu-157:~# vim /etc/chrony/chrony.conf
server 10.0.0.158 iburst

#重启服务
root@ubuntu-157:~# systemctl restart chrony.service

root@ubuntu-157:~# chronyc -n sources
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 10.0.0.158                    3   6    17     7   +219us[ +234us] +/-   24ms
#服务器查看
root@ubuntu-158:~# chronyc -n clients 
Hostname                      NTP   Drop Int IntL Last     Cmd   Drop Int  Last
===============================================================================
10.0.0.153                      8      0   6   -    25       0      0   -     -
10.0.0.157                      4      0   1   -    48       0      0   -     -
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值