ulimit

本文最后更新于:2023年12月5日 晚上

控制 shell 程序的资源

ulimit [-SHacdefilmnpqrstuvx] [limit]

配置文件

ulimit 命令,立即生效,但无法保存,永久保存需要修改配置文件:

/etc/security/limits.conf
/etc/security/limits.d/*.conf

# 配置文件格式:每行一个定义
<domain> <type> <item> <value>

*          soft    nproc     4096
root       soft    nproc     unlimited

配置文件详细信息:man 5 limits.conf

domain

domain description
username 一个用户
@group 组内所有用户
* 所有用户
% 限制最多有多少用户登录,%对*生效,限制组使用%group
:
@:
%:

type

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

item

item default description
core
data
fsize
memlock 最大锁定内存地址空间
nofile 1024 所能够同时打开的最大文件数量
rss
stack
cpu
nproc 1024 所能够同时运行的进程的最大数量
as
maxlogins
maxsyslogins
priority
locks
sigpending
msgqueue POSIX 消息队列所使用的最大内存
nice
rtprio

范例:

*               soft    core            0
*               hard    nofile          512
@student        hard    nproc           20
@faculty        soft    nproc           20
@faculty        hard    nproc           50
ftp             hard    nproc           0
@student        -       maxlogins       4
:123            hard    cpu             5000
@500:           soft    cpu             10000
600:700         hard    locks           10

生产案例:

* - core unlimited
* - nproc 1000000
* - nofile 1000000
* - memlock 32000
* - msgqueue 8192000

案例:ulimit 命令修改用户打开的文件个数

[root@centos8 ~]#ulimit -n
1024
[root@centos8 ~]#ulimit -n 1048577
-bash: ulimit: open files: cannot modify limit: Operation not permitted
[root@centos8 ~]#ulimit -n 1048576
[root@centos8 ~]#ulimit -a
core file size (blocks, -c) unlimited
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 7111
max locked memory (kbytes, -l) 16384
max memory size (kbytes, -m) unlimited
open files (-n) 1048576
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) 7111
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
[root@centos8 ~]#echo 2^20|bc
1048576

案例:限制用户最多打开的文件数和运行进程数,并持久保存

cat /etc/pam.d/system-auth
session required pam_limits.so

vim /etc/security/limits.conf
#用户apache可打开10240个文件
apache - nofile 10240
#用户student不能运行超过20个进程
student hard nproc 10

#用student登录多次运行bash,观察结果

[root@centos8 ~]#vim /etc/security/limits.conf
wang - nofile 66666
wang - nproc 5
mage - nofile 88888

[root@centos8 ~]#su - wang
Last login: Mon May 25 14:40:38 CST 2020 on pts/0
[wang@centos8 ~]$ulimit -n
66666

案例:限制 mage 用户最大的同时登录次数

[root@centos8 ~]#tail -n1 /etc/security/limits.conf
mage - maxlogins 2

[root@centos8 ~]#who
mage tty1 2020-05-25 14:35
root pts/0 2020-05-25 14:35 (10.0.0.1)
root pts/3 2020-05-25 14:06 (10.0.0.1)
mage tty3 2020-05-25 14:35


ulimit
http://blog.lujinkai.cn/运维/基础/加密和安全/ulimit/
作者
像方便面一样的男子
发布于
2020年12月9日
更新于
2023年12月5日
许可协议