如何只输出 运行 进程的用户

How to output just the user of a running process

当我执行 ps aux | grep mongod 时,我得到

mongod    53830  0.1  0.3 247276 27168 ?        Sl   Apr04 128:21 /var/lib/mongodb-mms-automation/mongodb-mms-monitoring-agent-5.4.4.366-1.rhel7_x86_64/mongodb-mms-monitoring-agent
mongod   104378  0.6  0.8 469384 71920 ?        Ssl  Mar22 571:03 /opt/mongodb-mms-automation/bin/mongodb-mms-automation-agent -f /etc/mongodb-mms/automation-agent.config -pidfilepath /var/run/mongodb-mms-automation/mongodb-mms-automation-agent.pid >> /var/log/mongodb-mms-automation/automation-agent-fatal.log 2>&1
mongod   104471  0.6  5.4 1993296 433624 ?      Sl   Mar22 578:03 /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.4.13/bin/mongod -f /data/mdiag/data/automation-mongod.conf

但是,我只对输出第三个条目的 user 感兴趣,它运行实际的 mongod 进程。我希望输出只是

mongod

我该如何调整 psgrepawk 来做到这一点?

也许过滤掉代理商?

$ ps aux | awk '/mongod/ && !/agent/{print }'

将其通过管道传输到 awk 并搜索:

 ps aux | grep mongod | awk '/bin\/mongod /{print }'

有了它,您可能可以放弃 grep,让 awk 进行搜索:

 ps aux |  awk '/bin\/mongod /{print }'

这是在记录中的任意位置搜索字符串 "bin/mongod ",然后返回该记录第 8 个位置的任何内容。

尝试使用 shell 命令获取该用户很可能会崩溃。您可以使用 PID 选项启动 mongod 吗?

/var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.4.13/bin/mongod -f /data/mdiag/data/automation-mongod.conf --pidfilepath /run/mongodb-pid.txt

然后您可以简单地 运行 ps $(cat /run/mongodb-pid.txt) 只得到您想要的特定进程。

以下 awk 可能对您有所帮助。

ps aux | awk '/mongod/ && /automation-mongod.conf/{print }' 

ps aux | awk '/mongod/ && /\/data\/mdiag\/data\/automation-mongod.conf/{print }'

最好指定模式以匹配我们感兴趣的 COMMAND 字段的第一部分的末尾。此外,使用括号表达式代替 \/ 至少让我的眼睛更快乐查看匹配文件路径的模式。

ps aux | awk -v command=11 -v user=1 '$command ~ /[/]bin[/]mongod$/ { print $user }'