问题描述
我正在尝试从剧本中获取 ansible 剧本的 PID.我找到了一种粗略的方法,我试图让它更加精致和强大.如果我运行以下 find
+ awk
命令,它会为我提供用户 ansible-playbook
的所有 PID.虽然它也给了我一些虚假的 PID,但我需要删除它们.
I am trying to get the ansible playbook's PID from within the playbook. I found one crude approach, I am trying to make it more refined and robust. If I run following find
+ awk
command, it gives me all the PID of ansible-playbook
by the user. Although it give me few bogus PIDs as well and I need to remove them.
例如:4229 是一个有效的 PID,我需要它,而 19425 是一个陈旧的 PID(不存在于 ps -eaf 输出中),我需要将它从我的列表中删除.
For example: 4229 is a valid PID and I need it whereas 19425 is a stale PID(not present in ps -eaf output) and I need to remove it from my list.
要直观地查看其中包含 PID 名称的文件:
To visually see the files with PID names in them:
meta@monk:~/.ansible/tmp>ls -lrt
total 8
drwx------ 2 monk admin4096 Oct 16 13:09 ansible-local-19425A_62FT
drwx------ 3 monk admin4096 Oct 17 10:38 ansible-local-4229U_pXdg
meta@monk:~/.ansible/tmp>
提取PID名称:
meta@monk:~/.ansible/tmp>find . -type d |awk 'NR>1{pid=gensub(/.\/ansible-local-([0-9]+)._.*$/,"\\1","g",$NF);print pid}'
4229
4229
19425
要验证 PID 是否存在:
To validate if a PID is alive or not:
meta@monk:~>ps -eaf |grep -iE '4229|4229|19425'
monk 4229 2179 5 10:33 pts/26 00:00:49 /usr/local/bin/python /usr/local/bin/ansible-playbook pid.yml -vv
monk 5303 4229 0 10:38 pts/26 00:00:00 /usr/local/bin/python /usr/local/bin/ansible-playbook pid.yml -vv
monk 5744 5569 0 10:49 pts/3 00:00:00 grep -iE 4229|4229|19425
meta@monk:~>
只需要得出 4229,因为 19425 从 ps -eaf
输出中消失了.
Concluding only 4229 is desired, as 19425 is gone from ps -eaf
output.
问题:
如何有效地组合 find
、 awk
和 ps -eaf
命令以产生输出 4229
?
How to combine find
, awk
, and ps -eaf
command efficiently to produce the output 4229
?
顺便说一下,我尝试了 获取正在运行的 playbook 的 pid 以在 playbook 中使用,甚至增加了赏金,但还没有快乐.所以请不要将其标记为重复,因为这是该问题的扩展.
By the way, I tried simpler solutions provided in Get the pid of a running playbook for use within the playbook ,even added bounty but no joy yet. So please do not mark it as duplicate as this is an extension to that question.
推荐答案
试试这个:
#!/bin/bash
cd ~/.ansible/tmp
while read pid; do
[ -d /proc/${pid} ] || ls -lad ansible-local-${pid}*;
done < <(find . -type d | sed -n 's/^ansible-local-\([0-9]*\).*$/\1/p' )
如果正确列出过时的目录,则在第 6 行将 ls -lad
更改为 'rm -r`.
If correctly lists the stale directories, then change ls -lad
to 'rm -r` in line 6.
这篇关于从同一剧本中获取 ansible 剧本的 PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!