清理遠程桌面軟件NX死session留下的進程

系統: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

 

  1. #!/bin/bash  
  2.  
  3. #  
  4. #author:root123.blog.51cto.com  
  5. #description: kill all the processes left by dead NX session.  
  6. #  
  7.  
  8. logFile=./nxclean.log  
  9.  
  10. #get the users' names who had logined system.  
  11. users=$(w -h | awk '{print $1}' | sort -u)  
  12.  
  13. for i in $users  
  14. do  
  15.   #get current NX port number of each user 
  16.   NXport=$(w -h | grep "^$i" | awk '{print $2}' | grep "^:[0-9]")  
  17.   NXport=${NXport#":"}  
  18.   #get all exist NX port number of each user 
  19.   existPorts=$(w -h | grep "^$i" | awk '{print $3}' | grep "^:[0-9]" | sort -u)  
  20.   for j in $existPorts  
  21.   do  
  22.     if [ X$j =X ]  
  23.     then :  
  24.     else 
  25.       existPort=${j%".0"}  
  26.       existPort=${j#":"}  
  27.       #kill all processes which related the existsPort; NX port is greater than or equal 1000   
  28.       if [ X${existPort != X${NXport} } && [ ${existPort} -ge 1000 ]  
  29.       then 
  30.       echo "$(date) $(hostname) user is $i, current NX port is $NXport, dead NX port is $existPort" >> $logFile  
  31.       echo "kill all the processes which related the dead NX prot $existPort" >> $logFile  
  32.       #get the PID related $existPort  
  33.       TTYs=$(w -h | grep  $i | grep $existPort | awk '{print $2}')  
  34.       for k in $TTYs  
  35.       do  
  36.         PIDs=$(ps axu | grep "^$i" grep "$k" | awk '{print $2}')  
  37.         for l in $PIDs  
  38.         do  
  39.           if [ X$l != "X" ]  
  40.           then 
  41.             echo "kill process $l" >> $logFile  
  42.             kill -9 $l  
  43.           fi  
  44.         done  
  45.       done  
  46.     fi  
  47.    fi  
  48.   done  
  49. done 

注:腳本爲手動輸入,如有錯,請通知我更正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章