ps 即process state,可以进程当前状态的快照,默认显示当前终端中的进程,Linux系统各进程的相关信息均保存在/proc/PID目录下的各文件中。
ps格式
ps [OPTION]...
支持三种选项:
常用选项:
a #选项包括所有终端中的进程 x #选项包括不链接终端的进程 u #选项显示进程所有者的信息 f #选项显示进程树,相当于 --forest k|--sort 属性 #对属性排序,属性前加 - 表示倒序 o #属性… 选项显示定制的信息pid、cmd、%cpu、%mem L #显示支持的属性列表 -C cmdlist #指定命令,多个命令用,分隔 -L #显示线程 -e #显示所有进程,相当于-A -f #显示完整格式程序信息 -F #显示更完整格式的进程信息 -H #以进程层级格式显示进程相关信息 -u userlist #指定有效的用户ID或名称 -U userlist #指定真正的用户ID或名称 -g gid或groupname #指定有效的gid或组名称 -G gid或groupname #指定真正的gid或组名称 -p pid #显示指pid的进程 --ppid pid #显示属于pid的子进程 -t ttylist #指定tty,相当于 t -M 显示SELinux信息,相当于Z
ps输出属性
C : ps -ef 显示列 C 表示cpu利用率 VSZ: Virtual memory SiZe,虚拟内存集,线性内存,申请的内存 RSS: ReSident Size, 常驻内存集,进程实际使用的内存 STAT:进程状态 R:running S: interruptable sleeping D: uninterruptable sleeping T: stopped Z: zombie +: 前台进程 l: 多线程进程 L:内存分页并带锁 N:低优先级进程 <: 高优先级进程 s: session leader,会话(子进程)发起者 I:Idle kernel thread,CentOS 8 新特性 ni: nice值 pri: priority 优先级 rtprio: 实时优先级 psr: processor CPU编号
示例:
ps axo pid,cmd,psr,ni,pri,rtprio
常用组合:
aux -ef -eFH -eo pid,tid,class,rtprio,ni,pri,psr,pcpu,stat,comm axo stat,euid,ruid,tty,tpgid,sess,pgrp,ppid,pid,pcpu,comm
范例:-ef或aux查看进程详细信息
#列 C 表示 CPU利用率 [root@centos7 ~]#ps -ef UID PID PPID C STIME TTY TIME CMD root 1 0 0 07:17 ? 00:00:05 /usr/lib/systemd/systemd --switched-root --system --deserialize 22 root 2 0 0 07:17 ? 00:00:00 [kthreadd] root 4 2 0 07:17 ? 00:00:00 [kworker/0:0H] root 6 2 0 07:17 ? 00:00:01 [ksoftirqd/0] [root@centos7 ~]#ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.3 125340 3860 ? Ss 07:17 0:05 /usr/lib/systemd/systemd --switched-root --system --deserialize 22 root 2 0.0 0.0 0 0 ? S 07:17 0:00 [kthreadd] root 4 0.0 0.0 0 0 ? S< 07:17 0:00 [kworker/0:0H] root 6 0.0 0.0 0 0 ? S 07:17 0:01 [ksoftirqd/0]
范例:f查看进程的父子关系
[root@centos7 ~]#ps auxf USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 2 0.0 0.0 0 0 ? S 07:17 0:00 [kthreadd] root 4 0.0 0.0 0 0 ? S< 07:17 0:00 \_ [kworker/0:0H] root 6 0.0 0.0 0 0 ? S 07:17 0:01 \_ [ksoftirqd/0] root 7 0.0 0.0 0 0 ? S 07:17 0:00 \_ [migration/0] root 723 0.0 0.4 112936 4364 ? Ss 07:17 0:00 /usr/sbin/sshd -D root 991 0.0 0.6 162052 6920 ? Ss 07:17 0:01 \_ sshd: root@pts/0 root 995 0.0 0.3 116340 3008 pts/0 Ss+ 07:17 0:00 | \_ -bash
范例:o查看进程的特定属性
[root@centos7 ~]#ps axo pid,cmd,%mem,%cpu PID CMD %MEM %CPU 1 /usr/lib/systemd/systemd -- 0.3 0.0 2 [kthreadd] 0.0 0.0 4 [kworker/0:0H] 0.0 0.0 6 [ksoftirqd/0] 0.0 0.0
范例:k或--sort,针对属性排序(-为倒叙),CentOS6 以下版本不支持
#按cpu利用率从小到大排序 [root@centos7 ~]#ps axo pid,cmd,%mem,%cpu k %cpu PID CMD %MEM %CPU 1 /usr/lib/systemd/systemd -- 0.3 0.0 2561 ps axo pid,cmd,%mem,%cpu k 0.1 0.0 308 [xfsaild/sda3] 0.0 0.2 1621 [kworker/0:2] 0.0 0.2 573 /usr/bin/vmtoolsd 0.4 0.4 #按内存使用率从大到小倒叙排列 [root@centos7 ~]#ps axo pid,cmd,%mem,%cpu --sort -%mem PID CMD %MEM %CPU 727 /usr/bin/python2 -Es /usr/s 1.7 0.0 579 /usr/lib/polkit-1/polkitd - 1.2 0.0 595 /usr/sbin/NetworkManager -- 0.8 0.0 725 /usr/sbin/rsyslogd -n 0.7 0.0 991 sshd: root@pts/0 0.6 0.0 1100 sshd: root@pts/1 0.6 0.0 2442 sshd: root@pts/2 0.6 0.0 1102 sshd: root@notty 0.6 0.0 2444 sshd: root@notty 0.6 0.0 993 sshd: root@notty 0.6 0.0 726 /usr/sbin/httpd -DFOREGROUN 0.5 0.0
范例:有效用户和实际用户
#euser:有效用户; #ruser:实际(真正的)用户 #passwd有效执行的用户是root,而实际执行的用户是wang [root@centos7 ~]#su - wang [wang@centos7 ~]$passwd Changing password for user wang. Changing password for wang. (current) UNIX password: [root@centos7 ~]#ps axo pid,cmd,%mem,%cpu,euser,ruser|grep passwd 2687 passwd 0.2 0.0 root wang 2695 grep --color=auto passwd 0.0 0.0 root root #查询实际用户(ruser)或用户ID的进程 [root@centos7 ~]#ps -fU wang UID PID PPID C STIME TTY TIME CMD wang 2658 2657 0 10:32 pts/3 00:00:00 -bash root 2731 2658 0 10:37 pts/3 00:00:00 passwd #查询指定用户(euser)或用户ID的进程 [root@centos7 ~]#ps -fu wang UID PID PPID C STIME TTY TIME CMD wang 2658 2657 0 10:32 pts/3 00:00:00 -bash
按条件搜索进程
pgrep 命令格式
pgrep [options] pattern
常用选项
-u #uid: effective user,生效者 -U #uid: real user,真正发起运行命令者 -t #terminal: 与指定终端相关的进程 -l #显示进程名 -a #显示完整格式的进程名 -P pid #显示指定进程的子进程
范例:
#查找有效用户发起的进程ID号 [root@centos7 ~]#pgrep -u wang 2658 4415 4418 4460 #显示出进程的名称 [root@centos7 ~]#pgrep -ul wang pgrep: invalid user name: l [root@centos7 ~]#pgrep -lu wang 2658 bash 4415 ping 4418 bash 4460 dd #显示详细信息 [root@centos7 ~]#pgrep -au wang 2658 -bash 4415 ping 127.0.0.1 4418 -bash 4460 dd if=/dev/zero of=/dev/null #显示指定进程的子进程 [root@centos7 ~]#pgrep -P 2658 4415 [root@centos7 ~]#pgrep -aP 2658 4415 ping 127.0.0.1 [root@centos7 ~]#pgrep -aP 4418 4460 dd if=/dev/zero of=/dev/null #显示终端上运行的进程 [root@centos7 ~]#pgrep -at pts/3 2624 -bash 2657 su - wang 2658 -bash 4415 ping 127.0.0.1 [root@centos7 ~]#ps aux |grep wang #显示的更详细 root 2657 0.0 0.0 191884 124 pts/3 S 10:32 0:00 su - wang wang 2658 0.0 0.1 116208 1004 pts/3 S 10:32 0:00 -bash wang 4415 0.0 0.1 128556 1272 pts/3 S+ 14:10 0:00 ping 127.0.0.1 root 4417 0.0 0.2 191884 2340 pts/0 S 14:10 0:00 su - wang wang 4418 0.0 0.2 116208 2660 pts/0 S 14:10 0:00 -bash wang 4460 99.9 0.0 108100 612 pts/0 R+ 14:11 3:43 dd if=/dev/zero of=/dev/null root 4504 0.0 0.0 112812 968 pts/2 R+ 14:15 0:00 grep --color=auto wang
pidof 格式
pidof [options] [program [...]]
常用选项:
-x #按脚本名称查找pid
范例:
[wang@centos7 scripts]$./guess_number.sh 请输入0-9之间的正整数: [root@centos7 ~]#ps aux|grep guess_number|grep -v grep wang 4572 0.0 0.1 113288 1180 pts/3 S+ 14:20 0:00 /bin/bash ./guess_number.sh [root@centos7 ~]#pidof -x guess_number.sh 4572
实例:找到未知进程的执行程序文件路径
#比如有个进程占用内存或cpu太多,使用dd来模拟,cpu利用率达到99.7% [wang@centos7 ~]$dd if=/dev/zero of=/dev/null #按cpu利用率排序,查看哪个进程占用的多 [root@centos7 ~]#ps axo pid,%mem,%cpu,cmd k -%cpu PID %MEM %CPU CMD 3111 0.0 99.7 dd if=/dev/zero of=/dev/null #查到进程ID号后,进入/proc查看进程的命令 [root@centos7 ~]#ls -l /proc/3111/exe lrwxrwxrwx 1 wang wang 0 Apr 10 11:26 /proc/3111/exe -> /usr/bin/dd #如果进程只有一个ID号,也可以使用pidof查询 [root@centos7 ~]#ll /proc/`pidof dd`/exe lrwxrwxrwx 1 wang wang 0 Apr 10 11:55 /proc/3111/exe -> /usr/bin/dd
实例:显示统计占用系统内存最多的进程,并排序。
[root@centos7 scripts]#ps axo pid,%cpu,%mem,cmd --sort -%mem|head -10 PID %CPU %MEM CMD 727 0.0 1.7 /usr/bin/python2 -Es /usr/sbin/tuned -l -P 579 0.0 1.2 /usr/lib/polkit-1/polkitd --no-debug 595 0.0 0.8 /usr/sbin/NetworkManager --no-daemon 725 0.0 0.7 /usr/sbin/rsyslogd -n 991 0.0 0.6 sshd: root@pts/0 1100 0.0 0.6 sshd: root@pts/1 1102 0.0 0.6 sshd: root@notty 993 0.0 0.6 sshd: root@notty 726 0.0 0.5 /usr/sbin/httpd -DFOREGROUND
lsof:list open files,查看当前系统文件的工具。
在linux环境下,一切皆文件,用户通过文件不仅可以访问常规数据,还可以访问网络连接和硬件如传输控制协议 (TCP) 和用户数据报协议 (UDP)套接字等,系统在后台都为该应用程序分配了一个文件描述符。
命令选项:
-a #列出打开文件存在的进程 -c 进程名 #列出指定进程所打开的文件 -g #列出GID号进程详情 -d 文件号 #列出占用该文件号的进程 +d 目录 #列出目录下被打开的文件 +D 目录 #递归列出目录下被打开的文件 -n 目录 #列出使用NFS的文件 -i 条件 #列出符合条件的进程(4、6、协议、:端口、 @ip ) -p 进程号 #列出指定进程号所打开的文件 -u #列出UID号进程详情 -h #显示帮助信息 -v #显示版本信息。 -n #不反向解析网络名字
范例:
#查看由登陆用户启动而非系统启动的进程 [root@centos7 scripts]#lsof /dev/pts/ 0 2 3 ptmx [root@centos7 scripts]#lsof /dev/pts/0 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME bash 3619 root 0u CHR 136,0 0t0 3 /dev/pts/0 bash 3619 root 1u CHR 136,0 0t0 3 /dev/pts/0 bash 3619 root 2u CHR 136,0 0t0 3 /dev/pts/0 bash 3619 root 255u CHR 136,0 0t0 3 /dev/pts/0 su 4417 root 0u CHR 136,0 0t0 3 /dev/pts/0 su 4417 root 1u CHR 136,0 0t0 3 /dev/pts/0 su 4417 root 2u CHR 136,0 0t0 3 /dev/pts/0 bash 4418 wang 0u CHR 136,0 0t0 3 /dev/pts/0 bash 4418 wang 1u CHR 136,0 0t0 3 /dev/pts/0 bash 4418 wang 2u CHR 136,0 0t0 3 /dev/pts/0 bash 4418 wang 255u CHR 136,0 0t0 3 /dev/pts/0 dd 4612 wang 2u CHR 136,0 0t0 3 /dev/pts/0 #指定进程号,查看该进程打开的文件 [root@centos7 scripts]#lsof -p 4612 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME dd 4612 wang cwd DIR 8,3 99 16777612 /home/wang dd 4612 wang rtd DIR 8,3 4096 64 / dd 4612 wang txt REG 8,3 74896 50354474 /usr/bin/dd dd 4612 wang mem REG 8,3 106176928 279846 /usr/lib/locale/locale-archive dd 4612 wang mem REG 8,3 2156272 279233 /usr/lib64/libc-2.17.so dd 4612 wang mem REG 8,3 163312 279845 /usr/lib64/ld-2.17.so dd 4612 wang 0r CHR 1,5 0t0 1040 /dev/zero dd 4612 wang 1w CHR 1,3 0t0 1038 /dev/null dd 4612 wang 2u CHR 136,0 0t0 3 /dev/pts/0 [root@centos7 scripts]#lsof -p `pidof dd` #同上 [root@centos7 scripts]#lsof -c dd #同上 #查看指定用户打开的文件 [root@centos7 scripts]#lsof -u wang COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME bash 2658 wang cwd DIR 8,3 4096 33575026 /scripts bash 2658 wang rtd DIR 8,3 4096 64 / bash 2658 wang txt REG 8,3 964536 50332758 /usr/bin/bash bash 2658 wang mem REG 8,3 106176928 279846 /usr/lib/locale/locale-archive bash 2658 wang mem REG 8,3 61560 279543 /usr/lib64/libnss_files-2.17.so bash 2658 wang mem REG 8,3 2156272 279233 /usr/lib64/libc-2.17.so bash 2658 wang mem REG 8,3 19248 279526 /usr/lib64/libdl-2.17.so bash 2658 wang mem REG 8,3 174576 289245 /usr/lib64/libtinfo.so.5.9 bash 2658 wang mem REG 8,3 163312 279845 /usr/lib64/ld-2.17.so bash 2658 wang mem REG 8,3 26970 286881 /usr/lib64/gconv/gconv-modules.cache bash 2658 wang 0u CHR 136,3 0t0 6 /dev/pts/3 bash 2658 wang 1u CHR 136,3 0t0 6 /dev/pts/3 bash 2658 wang 2u CHR 136,3 0t0 6 /dev/pts/3 bash 2658 wang 255u CHR 136,3 0t0 6 /dev/pts/3 bash 4418 wang cwd DIR 8,3 99 16777612 /home/wang bash 4418 wang rtd DIR 8,3 4096 64 / bash 4418 wang txt REG 8,3 964536 50332758 /usr/bin/bash bash 4418 wang mem REG 8,3 106176928 279846 /usr/lib/locale/locale-archive bash 4418 wang mem REG 8,3 61560 279543 /usr/lib64/libnss_files-2.17.so bash 4418 wang mem REG 8,3 2156272 279233 /usr/lib64/libc-2.17.so bash 4418 wang mem REG 8,3 19248 279526 /usr/lib64/libdl-2.17.so bash 4418 wang mem REG 8,3 174576 289245 /usr/lib64/libtinfo.so.5.9 bash 4418 wang mem REG 8,3 163312 279845 /usr/lib64/ld-2.17.so bash 4418 wang mem REG 8,3 26970 286881 /usr/lib64/gconv/gconv-modules.cache bash 4418 wang 0u CHR 136,0 0t0 3 /dev/pts/0 bash 4418 wang 1u CHR 136,0 0t0 3 /dev/pts/0 bash 4418 wang 2u CHR 136,0 0t0 3 /dev/pts/0 bash 4418 wang 255u CHR 136,0 0t0 3 /dev/pts/0 dd 4612 wang cwd DIR 8,3 99 16777612 /home/wang dd 4612 wang rtd DIR 8,3 4096 64 / dd 4612 wang txt REG 8,3 74896 50354474 /usr/bin/dd dd 4612 wang mem REG 8,3 106176928 279846 /usr/lib/locale/locale-archive dd 4612 wang mem REG 8,3 2156272 279233 /usr/lib64/libc-2.17.so dd 4612 wang mem REG 8,3 163312 279845 /usr/lib64/ld-2.17.so dd 4612 wang 0r CHR 1,5 0t0 1040 /dev/zero dd 4612 wang 1w CHR 1,3 0t0 1038 /dev/null dd 4612 wang 2u CHR 136,0 0t0 3 /dev/pts/0 #查看指定目录下被打开的文件,参数+d为列出目录下被打开的文件,参数+D为递归列出目录下被打开的文件 [root@centos7 scripts]#lsof +d /var/log COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME VGAuthSer 572 root 2w REG 8,3 66662 16777603 /var/log/vmware-vgauthsvc.log.0 VGAuthSer 572 root 4w REG 8,3 66662 16777603 /var/log/vmware-vgauthsvc.log.0 vmtoolsd 573 root 3w REG 8,3 1461085 17059558 /var/log/vmware-vmsvc-root.log rsyslogd 725 root 6w REG 8,3 485008 16826021 /var/log/messages rsyslogd 725 root 7w REG 8,3 21853 16826025 /var/log/secure rsyslogd 725 root 8w REG 8,3 57478 16781844 /var/log/cron rsyslogd 725 root 9w REG 8,3 53784 16781845 /var/log/maillog [root@centos7 scripts]#lsof +D /var/log COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME auditd 548 root 5w REG 8,3 4437878 33938837 /var/log/audit/audit.log VGAuthSer 572 root 2w REG 8,3 66662 16777603 /var/log/vmware-vgauthsvc.log.0 VGAuthSer 572 root 4w REG 8,3 66662 16777603 /var/log/vmware-vgauthsvc.log.0 vmtoolsd 573 root 3w REG 8,3 1461559 17059558 /var/log/vmware-vmsvc-root.log rsyslogd 725 root 6w REG 8,3 485008 16826021 /var/log/messages rsyslogd 725 root 7w REG 8,3 21853 16826025 /var/log/secure rsyslogd 725 root 8w REG 8,3 57478 16781844 /var/log/cron rsyslogd 725 root 9w REG 8,3 53784 16781845 /var/log/maillog httpd 726 root 2w REG 8,3 2460 51028372 /var/log/httpd/error_log httpd 726 root 7w REG 8,3 0 53818614 /var/log/httpd/access_log tuned 727 root 3w REG 8,3 69892 33574986 /var/log/tuned/tuned.log httpd 775 apache 2w REG 8,3 2460 51028372 /var/log/httpd/error_log httpd 775 apache 7w REG 8,3 0 53818614 /var/log/httpd/access_log httpd 776 apache 2w REG 8,3 2460 51028372 /var/log/httpd/error_log httpd 776 apache 7w REG 8,3 0 53818614 /var/log/httpd/access_log httpd 778 apache 2w REG 8,3 2460 51028372 /var/log/httpd/error_log httpd 778 apache 7w REG 8,3 0 53818614 /var/log/httpd/access_log httpd 779 apache 2w REG 8,3 2460 51028372 /var/log/httpd/error_log httpd 779 apache 7w REG 8,3 0 53818614 /var/log/httpd/access_log httpd 780 apache 2w REG 8,3 2460 51028372 /var/log/httpd/error_log httpd 780 apache 7w REG 8,3 0 53818614 /var/log/httpd/access_log #查看所有网络连接,通过参数-i查看网络连接的情况,包括连接的ip、端口等以及一些服务的连接情况,例如:sshd等。也可以通过指定ip查看该ip的网络连接情况 lsof -i –n lsof -i@127.0.0.1 [root@centos7 scripts]#lsof -i -n COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME chronyd 585 chrony 5u IPv4 17116 0t0 UDP 127.0.0.1:323 chronyd 585 chrony 6u IPv6 17117 0t0 UDP [::1]:323 sshd 723 root 3u IPv4 20404 0t0 TCP *:ssh (LISTEN) sshd 723 root 4u IPv6 20406 0t0 TCP *:ssh (LISTEN) httpd 726 root 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 775 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 776 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 778 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 779 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 780 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) master 836 root 13u IPv4 21698 0t0 TCP 127.0.0.1:smtp (LISTEN) master 836 root 14u IPv6 21699 0t0 TCP [::1]:smtp (LISTEN) sshd 2442 root 3u IPv4 45303 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57752 (ESTABLISHED) sshd 2444 root 3u IPv4 44519 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57753 (ESTABLISHED) sshd 2620 root 3u IPv4 46914 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57839 (ESTABLISHED) sshd 2622 root 3u IPv4 47818 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57840 (ESTABLISHED) sshd 3615 root 3u IPv4 63437 0t0 TCP 192.168.100.12:ssh->192.168.100.1:62423 (ESTABLISHED) sshd 3617 root 3u IPv4 63761 0t0 TCP 192.168.100.12:ssh->192.168.100.1:62424 (ESTABLISHED) [root@centos7 scripts]#lsof -i@127.0.0.1 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME chronyd 585 chrony 5u IPv4 17116 0t0 UDP localhost:323 master 836 root 13u IPv4 21698 0t0 TCP localhost:smtp (LISTEN) #查看端口连接情况,通过参数-i:端口可以查看端口的占用情况,-i参数还有查看协议,ip的连接情况等 lsof -i :80 -n [root@centos7 scripts]#lsof -i:80 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME httpd 726 root 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 775 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 776 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 778 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 779 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) httpd 780 apache 4u IPv6 20568 0t0 TCP *:http (LISTEN) #查看指定进程打开的网络连接,参数-i、-a、-p等,-i查看网络连接情况,-a查看存在的进程,-c指定进程名称,-p指定进程ID [root@centos7 scripts]#lsof -i -n -a -c sshd COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 723 root 3u IPv4 20404 0t0 TCP *:ssh (LISTEN) sshd 723 root 4u IPv6 20406 0t0 TCP *:ssh (LISTEN) sshd 2442 root 3u IPv4 45303 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57752 (ESTABLISHED) sshd 2444 root 3u IPv4 44519 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57753 (ESTABLISHED) sshd 2620 root 3u IPv4 46914 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57839 (ESTABLISHED) sshd 2622 root 3u IPv4 47818 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57840 (ESTABLISHED) sshd 3615 root 3u IPv4 63437 0t0 TCP 192.168.100.12:ssh->192.168.100.1:62423 (ESTABLISHED) sshd 3617 root 3u IPv4 63761 0t0 TCP 192.168.100.12:ssh->192.168.100.1:62424 (ESTABLISHED) [root@centos7 scripts]#lsof -i -n -a -p 2442 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 2442 root 3u IPv4 45303 0t0 TCP 192.168.100.12:ssh->192.168.100.1:57752 (ESTABLISHED) #查看指定状态的网络连接,-n:no host names, -P:no port names,-i TCP指定协议,-s指定协议状态通过多个参数可以清晰的查看网络连接情况、协议连接情况等 [root@centos7 scripts]#lsof -n -P -i TCP -s TCP:ESTABLISHED COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 2442 root 3u IPv4 45303 0t0 TCP 192.168.100.12:22->192.168.100.1:57752 (ESTABLISHED) sshd 2444 root 3u IPv4 44519 0t0 TCP 192.168.100.12:22->192.168.100.1:57753 (ESTABLISHED) sshd 2620 root 3u IPv4 46914 0t0 TCP 192.168.100.12:22->192.168.100.1:57839 (ESTABLISHED) sshd 2622 root 3u IPv4 47818 0t0 TCP 192.168.100.12:22->192.168.100.1:57840 (ESTABLISHED) sshd 3615 root 3u IPv4 63437 0t0 TCP 192.168.100.12:22->192.168.100.1:62423 (ESTABLISHED) sshd 3617 root 3u IPv4 63761 0t0 TCP 192.168.100.12:22->192.168.100.1:62424 (ESTABLISHED)
范例:利用 lsof 恢复正在使用中的误删除的文件
#查看guess_number.sh文件 [root@centos7 scripts]#ll guess_number.sh -rwxr-xr-x 1 root root 386 Apr 10 15:38 guess_number.sh [root@centos7 scripts]#cat guess_number.sh #!/bin/bash NUM=$[RANDOM%10] RED='echo -e \033[1;31m' GREEN='echo -e \033[1;32m' YELLOW='echo -e \033[1;33m' END="\033[0m" while read -p "请输入0-9之间的正整数:" INPUT;do if [ $INPUT -eq $NUM ];then $RED "恭喜你猜对了!!!"$END break elif [ $INPUT -gt $NUM ];then $GREEN "数字大了,重新猜!"$END else $YELLOW "数字小了,重新猜!"$END fi done [root@centos7 scripts]#lsof |grep guess_number guess_num 6926 root 255r REG 8,3 386 43472707 /scripts/guess_number.sh #误删除该文件 [root@centos7 scripts]#rm -rf guess_number.sh #查看该文件的进程号 [root@centos7 scripts]#lsof|grep guess_number.sh guess_num 6926 root 255r REG 8,3 386 43472707 /scripts/guess_number.sh (deleted) #进入proc进程号中的fd目录,查看guess_number文件状态 [root@centos7 scripts]#ll /proc/6926/fd total 0 lrwx------ 1 root root 64 Apr 10 15:38 0 -> /dev/pts/0 lrwx------ 1 root root 64 Apr 10 15:38 1 -> /dev/pts/0 lrwx------ 1 root root 64 Apr 10 15:38 2 -> /dev/pts/0 lr-x------ 1 root root 64 Apr 10 15:38 255 -> /scripts/guess_number.sh (deleted) #复制内容到guess_number.sh文件 [root@centos7 scripts]#cat /proc/6926/fd/255 >/scripts/guess_number.sh #查看文件内容大小,已恢复 [root@centos7 scripts]#cat guess_number.sh #!/bin/bash NUM=$[RANDOM%10] RED='echo -e \033[1;31m' GREEN='echo -e \033[1;32m' YELLOW='echo -e \033[1;33m' END="\033[0m" while read -p "请输入0-9之间的正整数:" INPUT;do if [ $INPUT -eq $NUM ];then $RED "恭喜你猜对了!!!"$END break elif [ $INPUT -gt $NUM ];then $GREEN "数字大了,重新猜!"$END else $YELLOW "数字小了,重新猜!"$END fi done [root@centos7 scripts]#ll guess_number.sh -rw-r--r-- 1 root root 386 Apr 10 15:43 guess_number.sh
Linux的作业控制
让作业运行于后台
后台作业虽然被送往后台运行,但其依然与终端相关;退出终端,将关闭后台作业。如果希望送往后台后,剥离与终端的关系
查看当前终端所有作业:
jobs
作业控制:
fg [[%]JOB_NUM] #把指定的后台作业调回前台 bg [[%]JOB_NUM] #让送往后台的作业在后台继续运行 kill [%JOB_NUM] #终止指定的作业
利用后台执行,实现并行功能,即同时运行多个进程,提高效率
方法1
cat all.sh f1.sh& f2.sh& f3.sh&
方法2
(f1.sh&);(f2.sh&);(f3.sh&)
方法3
f1.sh&f2.sh&f3.sh&
范例:多组命令实现并行
#先并行ping127.1和127.3地址3次;再并行ping127.2和127.4地址2次 [root@centos7 scripts]#{ ping -c3 127.1; ping -c2 127.2; }& { ping -c3 127.3 ;ping -c2 127.4;}& [1] 7380 [2] 7381 [root@centos7 scripts]#PING 127.3 (127.0.0.3) 56(84) bytes of data. PING 127.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.021 ms 64 bytes from 127.0.0.3: icmp_seq=1 ttl=64 time=0.021 ms 64 bytes from 127.0.0.3: icmp_seq=2 ttl=64 time=0.060 ms 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.058 ms 64 bytes from 127.0.0.3: icmp_seq=3 ttl=64 time=0.076 ms 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.200 ms --- 127.3 ping statistics --- --- 127.1 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 1999ms 3 packets transmitted, 3 received, 0% packet loss, time 1999ms rtt min/avg/max/mdev = 0.021/0.093/0.200/0.077 ms rtt min/avg/max/mdev = 0.021/0.052/0.076/0.023 ms PING 127.2 (127.0.0.2) 56(84) bytes of data. 64 bytes from 127.0.0.2: icmp_seq=1 ttl=64 time=0.137 ms PING 127.4 (127.0.0.4) 56(84) bytes of data. 64 bytes from 127.0.0.4: icmp_seq=1 ttl=64 time=0.159 ms 64 bytes from 127.0.0.2: icmp_seq=2 ttl=64 time=0.033 ms 64 bytes from 127.0.0.4: icmp_seq=2 ttl=64 time=0.033 ms --- 127.2 ping statistics --- --- 127.4 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1002ms 2 packets transmitted, 2 received, 0% packet loss, time 1001ms rtt min/avg/max/mdev = 0.033/0.085/0.137/0.052 ms rtt min/avg/max/mdev = 0.033/0.096/0.159/0.063 ms ^C #还有按ctrl+c退出 [1]- Done { ping -c3 127.1; ping -c2 127.2; } [2]+ Done { ping -c3 127.3; ping -c2 127.4; } [root@centos7 scripts]#{ ping -c3 127.1; ping -c2 127.2; }& { ping -c3 127.3 ;ping -c2 127.4;}&wait #ping结束会自动退出
实例:编写脚本,使用for和while分别实现192.168.0.0/24网段内,地址是否能够ping通,若ping通则输出"success!",若ping不通则输出"fail!"
1、for循环 [root@centos7 scripts]#cat ping_for.sh #!/bin/bash #根据实际情况,修改ip地址为192.168.100.0/24网段 IP=192.168.100 for i in {1..255};do { ping -c 1 -w 1 $IP.$i &>/dev/null if [ $? -eq 0 ] ;then echo $IP.$i is 'success!' else echo $IP.$i is 'fail!' fi }& done wait [root@centos7 scripts]#./ping_for.sh 192.168.100.1 is success! 192.168.100.2 is success! 192.168.100.12 is success! 192.168.100.255 is fail! 192.168.100.3 is fail! 192.168.100.5 is fail! 192.168.100.7 is fail! 192.168.100.9 is fail! 192.168.100.11 is fail! ...省略... 2、while循环 [root@centos7 scripts]#cat ping_while.sh #!/bin/bash IP=192.168.100 i=1 while (($i<255)) do { ping -c 1 -w 1 $IP.$i &>/dev/null if [ $? -eq 0 ] ;then echo $IP.$i is 'success!' else echo $IP.$i is 'fail!' fi }& i=$(($i+1)) done wait [root@centos7 scripts]#./ping_while.sh 192.168.100.1 is success! 192.168.100.2 is success! 192.168.100.12 is success! 192.168.100.11 is fail! 192.168.100.5 is fail! 192.168.100.15 is fail! 192.168.100.3 is fail! 192.168.100.7 is fail! ...省略...
通过任务计划,可以让系统自动的按时间或周期性任务执行任务
1、未来的某时间点执行一次任务
2、周期性运行某任务
at 命令:
at [option] TIME
常用选项:
-V #显示版本信息 -t time #时间格式 [[CC]YY]MMDDhhmm[.ss] -l #列出指定队列中等待运行的作业;相当于atq -d #删除指定的作业;相当于atrm -c #查看具体作业任务 -f /path/file #指定的文件中读取任务 -m #当任务被完成之后,将给用户发送邮件,即使没有标准输出
范例:创建、查看、删除任务
[root@centos7 ~]# date Mon Apr 5 16:57:23 CST 2021 [root@centos7 ~]# at -l [root@centos7 ~]# at 18:00 at> mkdir /data/data -p at> echo $HOSTNAME at> <EOT> job 4 at Mon Apr 5 18:00:00 2021 [root@centos7 ~]# su - wang Last login: Mon Apr 5 16:33:46 CST 2021 on pts/3 [wang@centos7 ~]$ at 16:00 at> echo $USER at> <EOT> job 5 at Tue Apr 6 16:00:00 2021 [wang@centos7 ~]$ at -l 5 Tue Apr 6 16:00:00 2021 a wang [wang@centos7 ~]$ exit logout [root@centos7 ~]# at -l 4 Mon Apr 5 18:00:00 2021 a root 5 Tue Apr 6 16:00:00 2021 a wang [root@centos7 ~]# ll /var/spool/at total 8 -rwx------ 1 root root 2672 Apr 5 16:56 a00004019b6198 -rwx------ 1 wang wang 2474 Apr 5 16:56 a00005019b66c0 drwx------ 2 root root 6 Apr 5 16:35 spool [root@centos7 ~]# at -c 4 ...省略... mkdir /data/data -p echo $HOSTNAME [root@centos7 ~]# at -d 4 [root@centos7 ~]# at -l 5 Tue Apr 6 16:00:00 2021 a wang
查看atd是否启动
rpm -ql at #查看包文件 [root@centos7 ~]# rpm -ql at /usr/bin/at /usr/lib/systemd/system/atd.service ...省略... #查看atd是否启动,否则到时间后无法执行任务 [root@centos7 ~]# systemctl status atd.service ● atd.service - Job spooling tools Loaded: loaded (/usr/lib/systemd/system/atd.service; enabled; vendor preset: enabled) Active: inactive (dead) [root@centos7 ~]# systemctl start atd.service [root@centos7 ~]# systemctl status atd.service ● atd.service - Job spooling tools Loaded: loaded (/usr/lib/systemd/system/atd.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2021-04-05 16:12:58 CST; 2s ago Main PID: 5768 (atd) CGroup: /system.slice/atd.service └─5768 /usr/sbin/atd -f
注意:
范例:
[root@centos8 ~]#dnf install postfix -y [root@centos8 ~]#systemctl enable --now postfix
TIME:定义什么时候进行 at 这项任务的时间
HH:MM [YYYY-mm-dd] #时分秒年月日 noon, midnight, teatime(4pm) #表示时间的词组 tomorrow now+{minutes,hours,days, OR weeks} #从现在开始的多少分钟小时等以后,如now+30minutes
范例:at 时间格式
HH:MM #在今日的 HH:MM 进行,若该时刻已过,则明天此时执行任务 02:00 HH:MM YYYY-MM-DD #规定在某年某月的某一天的特殊时刻进行该项任务 00:00 2021-05-20 HH:MM[am|pm] [Month] [Date] 06pm Apr 18 17:20 tomorrow #在某个时间点再加几个时间后才进行该项任务 HH:MM[am|pm] + number [minutes|hours|days|weeks] now + 5 min 02pm + 3 days #范例: [root@centos7 ~]# at -f /data/data.log 11:30 2021-04-18 job 12 at Sun Apr 18 11:30:00 2021 [root@centos7 ~]# at -f /data/data.log tomorrow job 13 at Tue Apr 6 17:37:00 2021 [root@centos7 ~]# at -f /data/data.log now+30minutes job 14 at Mon Apr 5 18:07:00 2021 [root@centos7 ~]# at -f /data/data.log 03pm tomorrow job 15 at Tue Apr 6 15:00:00 2021 [root@centos7 ~]# at -f /data/data.log 00am Apr 18 job 16 at Sun Apr 18 00:00:00 2021
范例1:创建一次性任务
#创建一次性任务 [root@centos7 ~]# date Mon Apr 5 16:10:10 CST 2021 [root@centos7 ~]# at 16:12 at> echo $PATH at> touch /data/data.log at> <EOT> job 1 at Mon Apr 5 16:12:00 2021 Can't open /var/run/atd.pid to signal atd. No atd running? #查看atd服务状态,并启动 [root@centos7 ~]# systemctl status atd.service ● atd.service - Job spooling tools Loaded: loaded (/usr/lib/systemd/system/atd.service; enabled; vendor preset: enabled) Active: inactive (dead) [root@centos7 ~]# systemctl start atd.service [root@centos7 ~]# systemctl status atd.service ● atd.service - Job spooling tools Loaded: loaded (/usr/lib/systemd/system/atd.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2021-04-05 16:12:58 CST; 2s ago Main PID: 5768 (atd) CGroup: /system.slice/atd.service └─5768 /usr/sbin/atd -f #重新设置一次性任务 [root@centos7 ~]# date Mon Apr 5 16:13:18 CST 2021 [root@centos7 ~]# at 16:15 at> echo $PATH at> touch /data/data.log at> <EOT> job 2 at Mon Apr 5 16:15:00 2021 You have mail in /var/spool/mail/root #查看mail邮件信息 [root@centos7 ~]# mail Heirloom Mail version 12.5 7/5/10. Type ? for help. "/var/spool/mail/root": 1 messages 1 new >N 1 root Mon Apr 5 16:15 14/573 "Output from your job 1" & 1 Message 1: From root@centos7.localdomain Mon Apr 5 16:15:00 2021 Return-Path: <root@centos7.localdomain> X-Original-To: root Delivered-To: root@centos7.localdomain Subject: Output from your job 1 To: root@centos7.localdomain Date: Mon, 5 Apr 2021 16:15:00 +0800 (CST) From: root@centos7.localdomain (root) Status: R /app/tree/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin:/root/bin #查看创建的文件 [root@centos7 ~]# ll /data/data.log -rw-r--r-- 1 root root 0 Apr 5 16:15 /data/data.log
普通用户也能创建一次性任务,并且将任务暂时保存在/var/spool/at目录中,因为at命令是suid权限。
#虽然at目录是root所有者所有组权限,但at命令是suid权限,所以普通用户wang执行at命令做一次性任务时,使用的是root权限。 [root@centos7 ~]# ll /var/spool/at -d drwx------ 3 root root 31 Apr 5 16:35 /var/spool/at [root@centos7 ~]# ll `which at` -rwsr-xr-x 1 root root 53048 Oct 31 2018 /usr/bin/at You have mail in /var/spool/mail/root
范例2:普通用户创建一次性任务
[root@centos7 ~]# su - wang Last login: Mon Jan 11 20:51:23 CST 2021 on pts/0 [wang@centos7 ~]$ date Mon Apr 5 16:33:52 CST 2021 [wang@centos7 ~]$ at 16:35 at> echo $PATH at> touch /data/wang.log at> <EOT> job 3 at Mon Apr 5 16:35:00 2021 [wang@centos7 ~]$ mail No mail for wang [wang@centos7 ~]$ exit logout You have new mail in /var/spool/mail/root [root@centos7 ~]# mail Heirloom Mail version 12.5 7/5/10. Type ? for help. "/var/spool/mail/root": 2 messages 1 new 1 root Mon Apr 5 16:15 15/584 "Output from your job 1" >N 2 wang@centos7.localdo Mon Apr 5 16:35 15/656 "Output from your job 2" & 2 Message 2: /app/tree/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin:/home/wang/.local/bin:/home/wang/bin touch: cannot touch ‘/data/wang.log’: Permission denied #提示没有权限创建/data/wang.log文件 & q [root@centos7 ~]# ll /data -d drwxr-xr-x 3 root root 169 Apr 5 16:12 /data
范例3:广播发送一次性任务
[root@centos7 ~]# echo wall at jobs |at 17:05 job 6 at Mon Apr 5 17:05:00 2021 [root@centos7 ~]# at -l 5 Tue Apr 6 16:00:00 2021 a wang 6 Mon Apr 5 17:05:00 2021 a root [root@centos7 ~]# Broadcast message from root@centos7 (Mon Apr 5 17:05:00 2021): at jobs [root@centos7 ~]#
范例4:使用文件做为定时任务的输入
#有标准输出或错误时,会发送邮件 [root@centos7 ~]# cat /data/data.log mkdir /data/tmp -p cp /etc/yum.repos.d/* /data/tmp [root@centos7 ~]# date Mon Apr 5 17:13:58 CST 2021 [root@centos7 ~]# at 17:15 < /data/data.log job 7 at Mon Apr 5 17:15:00 2021 [root@centos7 ~]# mail Heirloom Mail version 12.5 7/5/10. Type ? for help. "/var/spool/mail/root": 4 messages 1 new 1 root Mon Apr 5 16:12 15/584 "Output from your job 1" 2 root Mon Apr 5 16:15 15/584 "Output from your job 2" 3 wang@centos7.localdo Mon Apr 5 16:35 16/667 "Output from your job 3" >N 4 root Mon Apr 5 17:15 14/532 "Output from your job 7" & 4 Message 4: cp: omitting directory ‘/etc/yum.repos.d/backup’ ##文件命令有错误,所以会发邮件提醒 #执行无错误,并且没有标准输出,不会发送邮件 [root@centos7 ~]# rm /data/tmp -rf [root@centos7 ~]# cat /data/data.log mkdir /data/tmp -p cp -a /etc/yum.repos.d/* /data/tmp [root@centos7 ~]# at 17:20 < /data/data.log job 9 at Mon Apr 5 17:20:00 2021 [root@centos7 ~]# ll /data/tmp/ #执行成功 total 12 drwxr-xr-x. 3 root root 4096 Mar 28 10:12 backup -rw-r--r-- 1 root root 481 Mar 28 10:12 base.repo -rw-r--r-- 1 root root 49 Mar 25 21:19 ssh.exp [root@centos7 ~]# mail #邮件中无该任务 Heirloom Mail version 12.5 7/5/10. Type ? for help. "/var/spool/mail/root": 4 messages > 1 root Mon Apr 5 16:12 15/584 "Output from your job 1" 2 root Mon Apr 5 16:15 15/584 "Output from your job 2" 3 wang@centos7.localdo Mon Apr 5 16:35 16/667 "Output from your job 3" 4 root Mon Apr 5 17:15 15/543 "Output from your job 7" #同样,at -f file 命令同上 [root@centos7 ~]# at -f /data/data.log 17:22 job 10 at Mon Apr 5 17:22:00 2021 #-m是强制发送邮件,无标准输出也发送 [root@centos7 ~]# rm /data/tmp -rf [root@centos7 ~]# at -f /data/data.log 17:30 -m job 11 at Mon Apr 5 17:30:00 2021 [root@centos7 ~]# mail Heirloom Mail version 12.5 7/5/10. Type ? for help. "/var/spool/mail/root": 5 messages 1 new 1 root Mon Apr 5 16:12 15/584 "Output from your job 1" 2 root Mon Apr 5 16:15 15/584 "Output from your job 2" 3 wang@centos7.localdo Mon Apr 5 16:35 16/667 "Output from your job 3" 4 root Mon Apr 5 17:15 15/543 "Output from your job 7" >N 5 root Mon Apr 5 17:30 13/479 "Output from your job 11" & 5 Message 5: From root@centos7.localdomain Mon Apr 5 17:30:00 2021 Return-Path: <root@centos7.localdomain> X-Original-To: root Delivered-To: root@centos7.localdomain Subject: Output from your job 11 To: root@centos7.localdomain Date: Mon, 5 Apr 2021 17:30:00 +0800 (CST) From: root@centos7.localdomain (root) Status: R & q [root@centos7 ~]# ll /data/tmp/ total 12 drwxr-xr-x. 3 root root 4096 Mar 28 10:12 backup -rw-r--r-- 1 root root 481 Mar 28 10:12 base.repo -rw-r--r-- 1 root root 49 Mar 25 21:19 ssh.exp
/etc/at.{allow,deny} 控制用户是否能执行at任务
#默认没有allow,只有deny [root@centos7 ~]# ll /etc/at.deny -rw-r--r-- 1 root root 1 Oct 31 2018 /etc/at.deny [root@centos7 ~]# ll /etc/at.allow ls: cannot access /etc/at.allow: No such file or directory #测试1:把wang用户加到deny中,wang用户就不能创建新的定时任务了,但之前创建的计划任务还可以执行 [root@centos7 ~]# echo wang >> /etc/at.deny [root@centos7 ~]# cat /etc/at.deny wang [root@centos7 ~]# su - wang Last login: Mon Apr 5 16:56:05 CST 2021 on pts/3 [wang@centos7 ~]$ at 18:00 You do not have permission to use at. #不能创建定时任务 [wang@centos7 ~]$ #测试2:mage用户在allow中,wang用户在deny中,那么mage可以创建,而wang不能创建 [root@centos7 ~]# cat /etc/at.allow mage [root@centos7 ~]# cat /etc/at.deny wang [root@centos7 ~]# su - mage Last login: Mon Apr 5 17:52:34 CST 2021 on pts/3 [mage@centos7 ~]$ at -l [mage@centos7 ~]$ su - wang [wang@centos7 ~]$ at -l You do not have permission to use at. #测试3:mage即在allow中,又在deny中,那么mage可以创建,因为allow的优先级比deny高 [root@centos7 ~]# cat /etc/at.allow mage [root@centos7 ~]# cat /etc/at.deny wang [root@centos7 ~]# su - mage Last login: Mon Apr 5 17:54:56 CST 2021 on pts/3 [mage@centos7 ~]$ at -l [mage@centos7 ~]$ at 18:00 at> echo success!!! at> <EOT> job 17 at Mon Apr 5 18:00:00 2021 [root@centos7 ~]# mail >N 6 mage@centos7.localdo Mon Apr 5 18:00 14/486 "Output from your job 17" & 6 Message 6: success!!! #测试4:删除at.allow和at.deny文件,只有root才能创建任务 [root@centos7 ~]# rm -f /etc/at.allow You have mail in /var/spool/mail/root [root@centos7 ~]# rm -f /etc/at.deny [root@centos7 ~]# su - wang Last login: Mon Apr 5 17:55:35 CST 2021 on pts/3 [wang@centos7 ~]$ at -l You do not have permission to use at. [wang@centos7 ~]$ su - mage Password: [mage@centos7 ~]$ at -l You do not have permission to use at.
周期性任务计划cron相关的程序包:
cron 依赖于crond服务,确保crond守护处于运行状态:
#CentOS 7 以后版本: systemctl status crond #CentOS 6: service crond status
范例:
#查看cronie和crontabs包文件 [root@centos7 ~]# rpm -ql cronie /etc/cron.d /etc/cron.d/0hourly /etc/cron.deny /etc/pam.d/crond /etc/sysconfig/crond /usr/bin/crontab /usr/lib/systemd/system/crond.service /usr/sbin/crond [root@centos7 ~]# rpm -ql crontabs /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly /etc/crontab /etc/sysconfig/run-parts /usr/bin/run-parts /usr/share/man/man4/crontabs.4.gz /usr/share/man/man4/run-parts.4.gz #查看crond.service运行状态 [root@centos7 ~]# systemctl status crond ● crond.service - Command Scheduler Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2021-04-03 10:42:57 CST; 2 days ago Main PID: 592 (crond) CGroup: /system.slice/crond.service └─592 /usr/sbin/crond -n #run-parts可以跟dir目录,执行里面的脚本或可执行文件 [root@centos7 ~]# /usr/bin/run-parts Usage: run-parts [--list | --test] <dir> #测试run-parts [root@centos7 data]# echo "echo f1.sh" >f1.sh [root@centos7 data]# echo "echo f2" >f2 [root@centos7 data]# cat f1.sh echo f1.sh [root@centos7 data]# cat f2 echo f2 [root@centos7 data]# run-parts /data #data下的文件没有执行权限,不能执行 [root@centos7 data]# chmod +x f* #添加执行权限后,可以执行 [root@centos7 data]# run-parts /data /data/f1.sh: f1.sh /data/f2: f2
cron任务分为:
计划任务日志:/var/log/cron
/etc/crontab 格式说明,详情参见 man 5 crontab
注释行以 # 开头
#crontab文件只有root才有修改权限 [root@centos7 data]# ll /etc/crontab -rw-r--r--. 1 root root 451 Jun 10 2014 /etc/crontab #crontab文件格式 [root@centos7 data]# cat /etc/crontab SHELL=/bin/bash #默认的SHELL类型 PATH=/sbin:/bin:/usr/sbin:/usr/bin #默认的PATH变量值,可修改为其它路径 MAILTO=root #默认标准输出和错误发邮件给root,可以指向其它用户 # For details see man 4 crontabs # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed [root@centos7 data]# #注:由于/etc/crontab只有root才能修改,一般不这么使用。
计划任务时间表示法:
(1) 特定值 给定时间点有效取值范围内的值 (2) * 给定时间点上有效取值范围内的所有值 表示“每...” (3) 离散取值 #,#,# (4) 连续取值 #-# (5) 在指定时间范围上,定义步长 /#: #即为步长 (6) 特定关健字 @yearly 0 0 1 1 * @annually 0 0 1 1 * @monthly 0 0 1 * * @weekly 0 0 * * 0 @daily 0 0 * * * @hourly 0 * * * * @reboot Run once after reboot
范例:
#晚上9点10分运行echo命令 10 21 * * * wang /bin/echo "Howdy!" #每3小时echo和wall命令 0 */3 * * * wang /bin/echo “howdy”; wall “welcome to Magedu!” #minute (0 - 59)hour (0 - 23)day of month (1 - 31)month (1 - 12)day of week (0 - 6) #都可以使用离散或连续取值,如1,3,5,15-20,25-28等这样的表示方法
范例:
[root@centos7 data]# cat /etc/crontab 23 21 * * * wang echo $PATH [root@centos7 data]# mail >N 7 (Cron Daemon) Mon Apr 5 21:23 26/944 "Cron <wang@centos7> echo $PATH mkdir /data/tmp -p" & 7 Message 7: From wang@centos7.localdomain Mon Apr 5 21:23:01 2021 /sbin:/bin:/usr/sbin:/usr/bin #默认的PATH变量值,比系统自带的要少很多,可以修改添加 [root@centos7 data]# echo $PATH /app/tree/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin:/root/bin
crond任务相关文件:
/etc/crontab #计划任务的总配置文件,存放统一配置的计划任务 /etc/cron.d/ #各用户,或各计划任务的子配置文件 /etc/cron.hourly/ #脚本 /etc/cron.daily/ #脚本 /etc/cron.weekly/ #脚本 /etc/cron.monthly/ #脚本
范例:
[root@centos7 cron.d]# cat 0hourly # Run the hourly jobs SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root 01 * * * * root run-parts /etc/cron.hourly #每个小时的第1分钟执行
运行计算机关机时cron不运行的任务,CentOS6以后版本取消anacron服务,由crond服务管理,对笔记本电脑、台式机、工作站、偶尔要关机的服务器及其它不一直开机的系统很重要对很有用。
由/etc/cron.hourly/0anacron执行,当执行任务时,更新/var/spool/anacron/cron.daily 文件的时间戳配置文件:/etc/anacrontab,负责执行/etc/ cron.daily /etc/cron.weekly /etc/cron.monthly中系统任务。
/etc/anacrontab格式说明
字段1:如果在这些日子里没有运行这些任务……
字段2:在重新引导后等待这么多分钟后运行它
字段3:任务识别器,在日志文件中标识
字段4:要执行的任务
[root@centos7 ~]# cat /etc/anacrontab # /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # the maximal random delay added to the base delay of the jobs RANDOM_DELAY=45 # the jobs will be started during the following hours only START_HOURS_RANGE=3-22 #开机后5分钟、25分钟分别执行计划任务 #period in days delay in minutes job-identifier command 1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
CentOS 7 使用 systemd-tmpfiles-setup服务实现
CentOS 6 使用/etc/cron.daily/tmpwatch定时清除临时文件
配置文件:
/etc/tmpfiles.d/*.conf /run/tmpfiles.d/*.conf /usr/lib/tmpfiles.d/*.conf [root@centos7 lib]#cat /usr/lib/tmpfiles.d/tmp.conf v /tmp 1777 root root 10d v /var/tmp 1777 root root 30d # Exclude namespace mountpoints created with PrivateTmp=yes x /tmp/systemd-private-%b-* X /tmp/systemd-private-%b-*/tmp x /var/tmp/systemd-private-%b-* X /var/tmp/systemd-private-%b-*/tmp
命令:
systemd-tmpfiles --clean|--remove|--create
crontab命令:
crontab命令格式:
crontab [-u user] [-l | -r | -e] [-i]
常用选项:
-l #列出所有任务 -e #编辑任务 -r #移除所有任务 -i #同-r一同使用,以交互式模式移除指定任务 -u user #仅root可运行,指定用户管理cron任务
控制用户执行计划任务:
/etc/cron.{allow,deny} #同一次性任务的allow和deny
范例:选项范例
#不使用-u,默认以当前用户来创建计划任务 #-u user,是以指定的用户来创建计划任务 [root@centos7 ~]#crontab -e -u wang #查看默认用户的计划任务 [root@centos7 ~]#crontab -l PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin * * * * * useradd hehe;echo $PATH #查看指定用户的计划任务 [root@centos7 ~]#crontab -l -u wang * * * * * echo wang.test [root@centos7 ~]#cat /var/spool/ anacron/ at/ cron/ lpd/ mail/ plymouth/ postfix/ samba/ [root@centos7 ~]#cat /var/spool/cron/wang * * * * * echo wang.test #直接删除当前用户的计划任务 [root@centos7 ~]#crontab -r [root@centos7 ~]#crontab -l no crontab for root #交互式删除指定用户的计划任务 [root@centos7 ~]#crontab -ri -u wang crontab: really delete wang's crontab? y [root@centos7 ~]#crontab -l -u wang no crontab for wang [root@centos7 ~]#ll /var/spool/cron/wang ls: cannot access /var/spool/cron/wang: No such file or directory [root@centos7 ~]#
范例:每个月日期和星期几字段的关系
[root@centos8 ~]#man 5 crontab Note: The day of a command's execution can be specified in the following two fields — 'day of month', and 'day of week'. If both fields are restricted (i.e., do not contain the "*" character), the command will be run when either field matches the current time. For example, "30 4 1,15 * 5" would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday. 30 2 1-10,20 * 1-5 #每月1-10号和20号,以及每周1-5执行;会怎么执行呢? #月和周是或的关系,满足其中之一都会执行
范例:修改默认的cron的文本编辑工具
[root@centos7 ~]# cat /etc/profile.d/env.sh export EDITOR=vim #编辑计划任务时,默认是调用vi,没有颜色;加上export EDITOR=vim会调用vim,有颜色显示 [root@centos7 ~]# . /etc/profile.d/env.sh #生效 root@ubuntu1804:~# crontab -e no crontab for root - using an empty one Select an editor. To change later, run 'select-editor'. 1. /bin/nano <---- easiest 2. /usr/bin/vim.basic 3. /usr/bin/vim.tiny 4. /bin/ed Choose 1-4 [1]: root@ubuntu1804:~# cat /etc/profile.d/env.sh export EDITOR=vim
范例:PATH变量
#crontab -e创建的计划任务,PATH变量很少,只有/usr/bin:/bin #测试 [root@centos7 ~]#crontab -l */2 * * * * echo $PATH [root@centos7 ~]#mail N 11 (Cron Daemon) Tue Apr 6 21:10 25/835 "Cron <root@centos7> echo $PATH" & 11 Message 11: /usr/bin:/bin #测试创建用户 #useradd命令在/usr/sbin中,没有在crontab的path变量里 [root@centos7 ~]# which useradd /usr/sbin/useradd [root@centos7 ~]# crontab -l * * * * * useradd haha #验证时,没有haha用户 [root@centos7 ~]# getent passwd|grep haha [root@centos7 ~]#mail /bin/sh: useradd: command not found #解决方法,由于默认PATH变量太少,需要添加PATH变量即可,或者写命令的绝对路径 [root@centos7 ~]# crontab -l PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin * * * * * useradd hehe;echo $PATH [root@centos7 ~]#tail -f /var/log/cron Apr 6 21:27:01 centos7 CROND[1704]: (root) CMD (useradd hehe;echo $PATH) [root@centos7 ~]#mail 2 (Cron Daemon) Tue Apr 6 21:27 26/951 "Cron <root@centos7> useradd hehe;echo $PATH" & 2 Message 2: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin [root@centos7 ~]#getent passwd |grep hehe hehe:x:1007:1007::/home/hehe:/bin/bash
范例:crontab -e创建的计划任务存放在/var/spool/cron目录下,如果是root创建的就是root,其他用户创建的,就显示该用户名
#root用户创建的计划任务 [root@centos7 ~]#cat /var/spool/cron/root PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin * * * * * useradd hehe;echo $PATH #wang用户创建计划任务 [wang@centos7 ~]$crontab -l * * * * * echo $PATH [wang@centos7 ~]$cat /var/spool/cron/wang #不能查看,因为cron目录只有root有权限 cat: /var/spool/cron/wang: Permission denied [wang@centos7 ~]$exit logout [root@centos7 ~]#ll /var/spool/cron/ total 8 -rw------- 1 root root 100 Apr 6 21:29 root -rw------- 1 wang wang 21 Apr 6 21:41 wang [root@centos7 ~]#cat /var/spool/cron/wang * * * * * echo $PATH [root@centos7 ~]#ll /var/spool/cron/ -d #cron目录只有root有权限 drwx------. 2 root root 30 Apr 6 21:41 /var/spool/cron/
范例:sed命令实现磁盘报警
[root@centos7 ~]#cat /usr/bin/disk_check.sh #!/bin/bash WARNING=10 df | sed -En '/^\/dev\/sd/s#^([^ ]+).* ([0-9]+)%.*#\1 \2#p'| while read DEVICE USE;do [ $USE -gt $WARNING ] && echo "$DEVICE will be full,USE:$USE" | mail -s diskfull root done [root@centos7 ~]#chmod +x /usr/bin/disk_check.sh [root@centos7 ~]#crontab -l */10 * * * * check_disk.sh
面试题:11月每天的6-12点之间每隔2小时执行/app/bin/test.sh
[root@centos8 ~]#crontab -l 0 6-12/2 * 11 * /app/bin/test.sh
注意:运行结果的标准输出和错误以邮件通知给相关用户,会有大量的垃圾邮件,所以计划任务中的脚本执行结果扔到垃圾箱中比较好。
cron任务中不建议使用%,它有特殊用途,它表示换行的特殊意义,且第一个%后的所有字符串会被将成当作命令的标准输入,如果在命令中要使用%,则需要用 \ 转义,不如把比较长的命令写在脚本中,再调用即可。
注意:将%放置于单引号中是不支持的
范例:
30 2 * * * /bin/cp -a /etc/ /data/etc`date +\%F_\%T` 30 2 * * * /bin/cp -a /etc/ /data/etc`date +'%F_%T'` #直接用%会有问题
1、每周的工作日1:30,将/etc备份至/backup目录中,保存的文件名称格式为“etcbak-yyyy-mm-dd-
HH.tar.xz”,其中日期是前一天的时间
#先新建一个备份的脚本,并添加执行权限 [root@centos7 ~]# cat /scripts/backup_etc.sh #!/bin/bash mkdir /backup -p tar Jcf /backup/etcbak-`date -d '-1 day' +%F-%H`.tar.xz /etc/* &>/dev/null [root@centos7 ~]# chmod +x /scripts/backup_etc.sh #增加定时任务,由于测试时间是20:40分左右,所以将定时任务时间改成20:45分 [root@centos7 ~]#date Wed Apr 7 20:40:17 CST 2021 [root@centos7 ~]# crontab -e PATH=/usr/bin:/bin:/sbin 45 20 * * 1-5 /scripts/backup_etc.sh #查看定时任务的执行情况 [root@centos7 ~]#tail -f /var/log/cron Apr 7 20:45:01 centos7 crond[607]: (root) RELOAD (/var/spool/cron/root) Apr 7 20:45:01 centos7 CROND[1382]: (root) CMD (/scripts/backup_etc.sh) #测试成功,生成了备份文件,日期是前一天的 [root@centos7 ~]#ll /backup/ -h -rw-r--r-- 1 root root 7.2M Apr 7 20:45 etcbak-2021-04-06-20.tar.xz [root@centos7 ~]#
2、每两小时取出当前系统/proc/meminfo文件中以S或M开头的信息追加至/tmp/meminfo.txt文件中
#先新建一个查看内存文件的脚本,并添加执行权限 [root@centos7 scripts]# cat /scripts/meminfo.sh #!/bin/bash echo Now it is `date +%F_%H_%M_%S` >>/tmp/meminfo.txt sed -nr '/^(S|M)/p' /proc/meminfo >> /tmp/meminfo.txt [root@centos7 scripts]# chmod +x meminfo.sh [root@centos7 scripts]# crontab -e * */2 * * * /scripts/meminfo.sh #测试,采用每分钟执行一次的方式测试,结果如下 [root@centos7 ~]#tail -f /var/log/cron Apr 9 19:43:01 centos7 CROND[1277]: (root) CMD (/scripts/meminfo.sh) Apr 9 19:44:01 centos7 CROND[1284]: (root) CMD (/scripts/meminfo.sh) [root@centos7 scripts]#cat /tmp/meminfo.txt Now it is 2021-04-09_19_43_01 MemTotal: 995680 kB MemFree: 721444 kB MemAvailable: 702296 kB SwapCached: 0 kB Mlocked: 0 kB SwapTotal: 2097148 kB SwapFree: 2097148 kB Mapped: 26052 kB Shmem: 8016 kB Slab: 46420 kB SReclaimable: 18388 kB SUnreclaim: 28032 kB Now it is 2021-04-09_19_44_01 MemTotal: 995680 kB MemFree: 721544 kB MemAvailable: 702396 kB SwapCached: 0 kB Mlocked: 0 kB SwapTotal: 2097148 kB SwapFree: 2097148 kB Mapped: 26060 kB Shmem: 8016 kB Slab: 46380 kB SReclaimable: 18388 kB SUnreclaim: 27992 kB
3、工作日时间,每10分钟执行一次磁盘空间检查,一旦发现任何分区利用率高于80%,就执行wall警报
#先新建一个磁盘检查的脚本,并添加执行权限 [root@centos7 scripts]# cat disk_check.sh #!/bin/bash #先按60% WARNING=60 df|sed -nr '/^\/dev\/sd/s#(^[^ ]+) .* ([0-9]+)%.*#\1 \2#p' |while read DEVICE USED;do [ $USED -gt $WARNING ] && wall The $DEVICE will be full,and $USED used! done [root@centos7 ~]# chmod +x /scripts/disk_check.sh #增加定时任务 [root@centos7 ~]# crontab -l */10 * * * 1-5 /scripts/disk_check.sh #测试,查看当前的磁盘利用率,sda3已经超过了60%,会触发警报 [root@centos7 ~]#df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 476M 0 476M 0% /dev tmpfs 487M 0 487M 0% /dev/shm tmpfs 487M 7.9M 479M 2% /run tmpfs 487M 0 487M 0% /sys/fs/cgroup /dev/sda3 20G 13G 7.3G 64% / /dev/sdb1 477M 2.3M 445M 1% /mnt/sdb1 /dev/sda1 497M 181M 317M 37% /boot tmpfs 98M 0 98M 0% /run/user/0 #测试结果,各个终端都收到了广播 [root@centos7 ~]#tail -f /var/log/cron Apr 7 22:06:01 centos7 CROND[1951]: (root) CMD (/scripts/disk_check.sh) Broadcast message from root@centos7 (Wed Apr 7 22:06:02 2021): The /dev/sda3 will be full,and 64 used! [root@centos7 scripts]# Broadcast message from root@centos7 (Wed Apr 7 22:06:02 2021): The /dev/sda3 will be full,and 64 used!
4、工作日时间,每10分钟执行一次磁盘空间检查,一旦发现任何分区利用率高 于80%,就发送邮件报警
#先新建一个磁盘检查的脚本,并添加执行权限 [root@centos7 scripts]# cat disk_check1.sh #!/bin/bash #先按60% WARNING=60 df|sed -nr '/^\/dev\/sd/s#(^[^ ]+) .* ([0-9]+)%.*#\1 \2#p' |while read DEVICE USED;do [ $USED -gt $WARNING ] && echo "The $DEVICE will be full,and $USED used" |mail -s disk_warning root done [root@centos7 ~]# chmod +x /scripts/disk_check1.sh #增加定时任务 [root@centos7 ~]# crontab -l */10 * * * 1-5 /scripts/disk_check1.sh #测试,查看当前的磁盘利用率,sda3已经超过了60%,会触发警报 [root@centos7 ~]#df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 476M 0 476M 0% /dev tmpfs 487M 0 487M 0% /dev/shm tmpfs 487M 7.9M 479M 2% /run tmpfs 487M 0 487M 0% /sys/fs/cgroup /dev/sda3 20G 13G 7.3G 64% / /dev/sdb1 477M 2.3M 445M 1% /mnt/sdb1 /dev/sda1 497M 181M 317M 37% /boot tmpfs 98M 0 98M 0% /run/user/0 #测试结果 [root@centos7 ~]#tail -f /var/log/cron Apr 7 22:21:01 centos7 CROND[2073]: (root) CMD (/scripts/disk_check1.sh) [root@centos7 scripts]#mail N 27 root Wed Apr 7 22:21 18/627 "disk_warning" & 27 Message 27: The /dev/sda3 will be full,and 64 used