清理远程桌面软件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 

注:脚本为手动输入,如有错,请通知我更正。

你可能感兴趣的:(linux,进程,远程桌面,NX)