4

I'm trying to have a ps aux command listing only real ssh-agent process. I've noticed that on some distros, I have unwanted process showing up, like command colors and such. I need to do this because I need to ensure the real ssh-agent process is running in a script (don't bother, I already have a loop for it...).

So I figured out I need to use something like that in my test routine:

#!/bin/bash
ps aux | grep ssh-agent | grep -v grep | awk '{print $12}'

My question is: Would the awk $12 work on any unix/linux env using bash with any bash versions?

Also, if I remove "grep -v grep" and do this:

ps aux | grep ssh-agent | awk '{print $12}'

output is:

ssh-agent
ssh-agent

Now:

ps aux | grep ssh-agent

output is:

foo 18153478  0.0  0.0  536  844      - A      Apr 25  0:00 ssh-agent
foo 31260886  0.0  0.0  252  264  pts/0 A    22:38:41  0:00 grep ssh-agent

That means, the space between "grep ssh-agent" is interpreted as a delimiter by the awk command. Aynthing possible to overcome that? I already tried using tab delimiter but that's not it. It seems the delimiter of the command are simple "space" characters. Is it possible to enforce tab delimiters for "ps" command output?

Any idea?

4

3 回答 3

3

好的,我想我找到了,非常简单明了:

ps -e -o pid,comm | grep ssh-agent

工作得很好。

在这里找到答案:https ://unix.stackexchange.com/questions/22892/how-do-use-awk-along-with-a-command-to-show-the-process-id-with-the-ps-命令/22895#22895

并改编成 | grep ssh 代理

马丁也建议。谢谢大家分享你的经验!

于 2013-05-09T23:40:07.377 回答
2

第一个 $12 与 ps 输出的字段数有关。它与 bash 无关。

grep -v grep是删除 grep 进程的好方法,因此请保留它;

现在你不确定最后一个字段是字段 12 还是什么,我不太确定

ps aux | grep ssh-agent | grep -v grep | awk '{ print $NF }' 

假设您只想查看 ssh-agent (并且它没有命令行参数)

这是一些快速而肮脏的东西,会吐出 pid 和完整的命令行

ps aux | grep ssh-agent | grep -v grep | awk '{ print $1 " "; for (k = 12; k < NF; k++ ) { printf "%s", k; } printf "\n"; }' 

NF 是 awk 中的字段数,因此 $NF 是最后一个字段。

看看这是否适合你。虽然有更清洁的方法可以做到这一点

于 2013-05-09T23:06:53.510 回答
1

我提议grep为某事喜欢'[s]sh-agent'。这样你就可以防止得到它grep本身。

我还建议不使用awk(打印第 12 列),而是使用cut打印行的特定字符范围,例如:

ps aux | grep '[s]sh-agent' | cut -c 66-

这当然取决于输出格式ps

您可以/proc/改为查看文件系统:

(
  cd /proc
  for p in [0-9]*
  do
    [ "$(readlink $p/exe)" = "/bin/bash" ] &&
      echo "$p $(cat $p/cmdline | tr '\0' ' ')"
  done
)

(用更合适的东西代替/bin/bash当然。)

另一方面,这将取决于/proc/文件系统的存在。自己决定哪个对你更好。

于 2013-05-09T23:10:02.840 回答