实用脚本:检查高 CPU / 内存消耗进程

1 检查高 CPU 消耗进程在 Linux 上运行了多长时间的 Bash 脚本

该脚本将帮助你确定高 CPU 消耗进程在 Linux 上运行了多长时间。

# vi /opt/scripts/long-running-cpu-proc.sh
#!/bin/bash
ps -eo pid,user,ppid,%mem,%cpu,cmd --sort=-%cpu | head | tail -n +2 | awk '{print $1}' > /tmp/long-running-processes.txt
echo "--------------------------------------------------"
echo "UName     PID  CMD            Process_Running_Time"
echo "--------------------------------------------------"
for userid in `cat /tmp/long-running-processes.txt`
do
username=$(ps -u -p $userid | tail -1 | awk '{print $1}')
pruntime=$(ps -p $userid -o etime | tail -1)
ocmd=$(ps -p $userid | tail -1 | awk '{print $4}')
echo "$username $userid $ocmd $pruntime"
done | column -t
echo "--------------------------------------------------"

给 long-running-cpu-proc.sh 设置可执行的 Linux 文件权限。

# chmod +x /opt/scripts/long-running-cpu-proc.sh

运行此脚本时,你将获得类似以下的输出:

# sh /opt/scripts/long-running-cpu-proc.sh
----------------------------------------------------
UName     PID  CMD       Process_Running_Time
----------------------------------------------------
daygeek  5214  Web       01:18:48
daygeek  5748  Web       01:08:20
daygeek  8043  inkscape  22:11
daygeek  5269  Web       01:18:31
daygeek  1712  Web       10:44:50
daygeek  5335  RDD       01:17:54
daygeek  1639  firefox   10:44:51
daygeek  7793  nautilus  24:14
daygeek  6301  Web       57:40
----------------------------------------------------

2.检查高内存消耗进程在 Linux 上运行了多长时间的 Bash 脚本

该脚本将帮助你确定最大的内存消耗进程在 Linux 上运行了多长时间。

# sh /opt/scripts/long-running-memory-proc.sh
#!/bin/bash
ps -eo pid,user,ppid,%mem,%cpu,cmd --sort=-%mem | head | tail -n +2 | awk '{print $1}' > /tmp/long-running-processes-1.txt
echo "--------------------------------------------------"
echo "UName     PID  CMD          Process_Running_Time"
echo "--------------------------------------------------"
for userid in `cat /tmp/long-running-processes-1.txt`
do
username=$(ps -u -p $userid | tail -1 | awk '{print $1}')
pruntime=$(ps -p $userid -o etime | tail -1)
ocmd=$(ps -p $userid | tail -1 | awk '{print $4}')
echo "$username $userid $ocmd $pruntime"
done | column -t
echo "--------------------------------------------------"

给 long-running-memory-proc.sh 设置可执行的 Linux 文件权限。

# chmod +x /opt/scripts/long-running-memory-proc.sh

运行此脚本时,你将获得类似以下的输出:

# sh /opt/scripts/long-running-memory-proc.sh
----------------------------------------------------
UName    PID   CMD       Process_Running_Time
----------------------------------------------------
daygeek  1639  firefox   10:44:56
daygeek  2997  Web       10:39:54
daygeek  5269  Web       01:18:37
daygeek  1712  Web       10:44:55
daygeek  8043  inkscape  22:17
daygeek  5214  Web       01:18:54
daygeek  1898  Web       10:44:48
daygeek  1129  Xorg      10:45:07
daygeek  6301  Web       57:45
----------------------------------------------------
posted @ 2020-09-21 11:08  哈喽哈喽111111  阅读(241)  评论(0编辑  收藏  举报