系統:redHat 5.5
背景:開發人員通過遠程桌面軟件NX連接linux服務器完成他們的設計工作,但是NX有些時候會出現些BUG,開發人員非正常關其PC機、或者其它特殊情況導致其不能恢復以前的連接的NX session. 然而以前的NX session卻在服務器端保留,包括在這個session中運行的程序,這樣導致服務器資源浪費和產生殭屍進程。
解決方法:運行命令 w -h,分析後發現,每個正常運行的NX session都會記錄下用戶名、端口號和遠程連接IP,而每個正常運行的NX session裏開的每個terminal都會關聯NX session的端口號。 這樣便可以抓出每個用戶所有terminal對應的端口號和當前正常的端口號做對比,不同的就判斷爲有死NX session留下的,將其kill掉。(不好意思,不方便貼圖)
使用方法:cron定期運行NXclean.sh將所有用戶的死NX session留下腳本全殺掉,只保留當前活動狀態的NX session.
具體腳本:NXclean.sh
- #!/bin/bash
- #
- #author:root123.blog.51cto.com
- #description: kill all the processes left by dead NX session.
- #
- logFile=./nxclean.log
- #get the users' names who had logined system.
- users=$(w -h | awk '{print $1}' | sort -u)
- for i in $users
- do
- #get current NX port number of each user
- NXport=$(w -h | grep "^$i" | awk '{print $2}' | grep "^:[0-9]")
- NXport=${NXport#":"}
- #get all exist NX port number of each user
- existPorts=$(w -h | grep "^$i" | awk '{print $3}' | grep "^:[0-9]" | sort -u)
- for j in $existPorts
- do
- if [ X$j =X ]
- then :
- else
- existPort=${j%".0"}
- existPort=${j#":"}
- #kill all processes which related the existsPort; NX port is greater than or equal 1000
- if [ X${existPort != X${NXport} } && [ ${existPort} -ge 1000 ]
- then
- echo "$(date) $(hostname) user is $i, current NX port is $NXport, dead NX port is $existPort" >> $logFile
- echo "kill all the processes which related the dead NX prot $existPort" >> $logFile
- #get the PID related $existPort
- TTYs=$(w -h | grep $i | grep $existPort | awk '{print $2}')
- for k in $TTYs
- do
- PIDs=$(ps axu | grep "^$i" grep "$k" | awk '{print $2}')
- for l in $PIDs
- do
- if [ X$l != "X" ]
- then
- echo "kill process $l" >> $logFile
- kill -9 $l
- fi
- done
- done
- fi
- fi
- done
- done
注:腳本爲手動輸入,如有錯,請通知我更正。