[英]Kill a Long Running User Process in Linux using shell script
我需要一個Shell腳本來殺死一個長時間運行的用戶進程(超過一定的時間)。
這些是我對此的觀察:
這是我嘗試過的:
user = " " " "
for i in user
users="user1 user2 user3"
for u in $users ; do
ps -o etime,pid,comm -u $u | grep "here what i need to grep?" | while read in ; do
ET=`echo $in | cut -f1 -d":"`
[[ $ET -ge 10 ]]&&{ PID=`echo $in | cut -f2 -d" "` ; kill -HUP $PID ; }
done
done
幫我
這將kill -HUP
(a)屬於指定列表上的用戶,(b)未連接到終端並且(c)超過10分鍾的任何進程:
#!/bin/sh
users=("user1" "user2")
for user in "${users[@]}"
do
ps -o etime,euid,pid,tty,comm -u "$user" | while read etime euid pid tty comm
do
[ "$etime" = ELAPSED ] && continue
[ "$tty" = '?' ] && continue
do_kill=$(echo "$etime" | awk -F'[-:]' 'NF==3{sub(/^/,"0-")} $1>0 || $2>0 ||$3>=10 {print "Kill"}')
[ "$do_kill" ] || continue
kill -HUP "$pid"
done
done
ps
提供了經過的時間,格式為天HH:mm:ss的就業超過一日齡或hh:mm:ss
就業不到一天的時間了。 awk
用於解釋這一點,並確定作業是十分鍾或更長時間。 這是通過以下命令完成的:
echo "$etime" | awk -F'[-:]' 'NF==3{sub(/^/,"0-")} $1>0 || $2>0 ||$3>=10 {print "Kill"}'
如果作業的時間是10分鍾或10分鍾以上,則awk
打印Kill
。 否則,它什么也不打印。
依次執行awk
命令的每個部分:
-F'[-:]'
這告訴awk
打破破折號或冒號上的字段。
NF==3{sub(/^/,"0-")}
如果只有三個字段,那么我們將缺少日期字段添加到該行的開頭。 這樣可以確保下一個命令的格式統一。
$1>0 || $2>0 ||$3>=10 {print "Kill"}
如果(a)天數$1
大於零,或(b)小時數$2
大於零,或(c)分鍾數大於或等於10,則打印Kill
。 否則,不打印任何內容。
以下提示用戶確定將kill -HUP
應用於該進程
#!/bin/bash
users=("user1" "user2")
exec 3<&0
for user in "${users[@]}"
do
ps -o etime,euid,pid,tty,comm -u "$user" | while read etime euid pid tty comm
do
[ "$etime" = ELAPSED ] && continue
[ "$tty" = '?' ] && continue
do_kill=$(echo "$etime" | awk -F'[-:]' 'NF==3{sub(/^/,"0-")} $1>0 || $2>0 ||$3>=10 {print "Kill"}')
[ "$do_kill" ] || continue
echo "$user $etime $euid $pid $tty $comm"
read -p "OK to kill this process (y/N)? " -u 3 ok
[[ "${ok,,}" =~ y ]] || continue
echo "Killing $pid"
kill -HUP "$pid"
done
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.