如果我发现我现在有两个用户登录系统(UserA和UserB),我如何找到这两个用户运行的进程。但是,这里的技巧是脚本将在无人值守的批处理中运行,而无需键盘的任何输入。除了被调用之外。
我知道脚本的第一部分是 谁| awk'{print $ 1}' 这个的输出就是 用户A 用户B
我想知道的是,如何使用此输出并自动将其与某些ps命令一起推送并获得所需的结果。
答案 0 :(得分:2)
获取用户列表(使用who),保存到文件,然后列出所有进程,然后grep(使用刚创建的文件),
tempfile=/tmp/wholist.$$
who | cut -f1 -d' '|sort -u > $tempfile
ps -ef |grep -f $tempfile
rm $tempfile
答案 1 :(得分:2)
LOGGED_IN=$( who | awk '{print $1}' | sort -u | xargs echo )
[ "$LOGGED_IN" ] && ps -fU "$LOGGED_IN"
standard switch -U
将输出仅限于那些真实用户ID与任何给定对应的进程的参数。 (例如,ps -f -U“UserA UserB”。)
答案 2 :(得分:2)
我终于在其他答案的帮助下找到了我正在寻找的单线程(已更新,以防没有用户登录 - 请参阅评论)。
ps -fU "`who | cut -d' ' -f1 | uniq | xargs echo`" 2> /dev/null
反引号内的东西被执行并“在现场插入”。它的工作原理如下:
who : you know what that does
cut -d' ' : split strings into fields, using ' ' as separator
-f1 : and return only field 1
uniq : return only unique entries
xargs echo : take each of the values piped in, and send them through echo: this strips the \n
2> /dev/null : if there are any error messages (sent to 2: stderr)
: redirect those to /dev/null - i.e. "dump them, never to be seen again"
所有的输出
user1 user2 user3
......但是有很多。然后,您使用ps
标记调用-fU
,以完整格式请求这些用户的所有进程(您当然可以更改这些标记以获取所需的格式,只需保留-U
就在“``
ps -fU user1 user2 user3
答案 3 :(得分:0)
不确定我是否正确理解了您的问题,但您可以通过grep管理ps的输出以获取特定用户运行的进程,如下所示:
ps -ef | grep '^xxxxx '
其中xxxxx是用户。