gpt4 book ai didi

bash - 如何查看哪些用户正在执行命令(Shell 脚本)

转载 作者:行者123 更新时间:2023-11-29 09:14:34 35 4
gpt4 key购买 nike

我想知道你是否可以帮我解决这个问题。我需要编写一个 shell 脚本来查看其他用户是否在执行 x 命令的同一台计算机上执行 watch 命令。你能帮帮我吗?非常感谢。

最佳答案

要解决这个问题,可以使用 ps -aux | grep <prgname>作为根用户。

例如:ps -aux | grep firefox执行此命令(作为 root),它返回以下输出:

sergio    3252 24.1  6.7 1840936 540264 ?      Sl   09:48 123:36 /usr/lib/firefox/firefox
root 23059 0.0 0.0 15944 948 pts/7 S+ 18:20 0:00 grep --color=auto firefox

最后一行是我执行的命令!

使用 ps 解决问题的一种方法可能是使用如下脚本。我认为可以创建更好的解决方案,但这似乎在我的 Ubuntu 14 上运行良好。

#!/bin/bash

i=0
search="watch"

tmp=`mktemp`
ps -aux | tr -s ' ' | grep "$search" > $tmp

while read fileline
do
user=`echo $fileline | cut -f1 -d\ `
prg=`echo $fileline | cut -f11 -d\ `
prg=`basename $prg`
if [ $prg == $search ]; then
echo "$user - $prg"
i=`expr $i + 1`
fi
done < $tmp

if [ $i == 0 ]; then
echo User not found
fi

rm $tmp

关于bash - 如何查看哪些用户正在执行命令(Shell 脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401408/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com