今天在写脚本的时候遇到一个问题,需求是通过本机远程连接到其他服务器,杀掉之前提起的nmon进程,然后再返回本机
于是命令如下(以本机localhost为例):
ssh localhost "ps -ef | grep "nmon" | grep -v grep | awk -F ' ' '{print $2}'|tail -1| xargs kill -9;exit"(ssh已经做了无密码登录,提起nmon进程的脚本没问题,问题只出现在kill进程)
执行以上命令后,这时问题出现了
返回信息:
[root@svt112 nmon]# ssh localhost "ps -ef | grep "nmon" | grep -v grep | awk -F ' ' '{print $2}'|tail -1| xargs kill -9;exit"Usage:
 kill [options] <pid|name> [...]Options:
 -a, --all              do not restrict the name-to-pid conversion to processes
                        with the same uid as the present process
 -s, --signal <sig>     send specified signal
 -q, --queue <sig>      use sigqueue(2) rather than kill(2)
 -p, --pid              print pids without signaling them
 -l, --list [=<signal>] list signal names, or convert one to a name
 -L, --table            list signal names and numbers -h, --help     display this help and exit
 -V, --version  output version information and exitFor more details see kill(1).
单独执行 ps -ef | grep "nmon" | grep -v grep | awk -F ' ' '{print $2}'|tail -1| xargs kill -9 是没有问题的,但是不知道为什么加上ssh去执行就失败了

解决方案 »

  1.   

    先检查一下xargs之前命令是否真的按预期输出了进程Pid
      

  2.   


    ps -ef | grep "nmon" | grep -v grep | awk -F ' ' '{print $2}'|tail -1
      

  3.   


    嗯,时能够正常输出pid的,如果单独执行 ps -ef | grep "nmon" | grep -v grep | awk -F ' ' '{print $2}'|tail -1| xargs kill -9,是能够杀死指定nmon进程的,但是加到ssh远程命令里,就不行了,感觉像是ssh $IP "   " 里获取不到pid变量
      

  4.   

    其实是想表达,在ssh里执行这条命令是否正常输出了pid
      

  5.   

    $ echo  "ps -ef | grep "nmon" | grep -v grep | awk -F ' ' '{print $2}'|tail -1| xargs kill -9;exit"
    ps -ef | grep nmon | grep -v grep | awk -F ' ' '{print }'|tail -1| xargs kill -9;exitawk命令的$2没有了
      

  6.   

    $ echo "a='$var_a'"  "b='\$var_b'"
    a='' b='$var_b'
      

  7.   

    awk '{prinf \$2}'  在$前加转义字符
      

  8.   

     grep "nmon"应该用单引号或者转义吧,不然与前面的双引号不好区分
      

  9.   

    在jenkins中直接使用这个命令获取进程号进行kill -9的话,会存在问题,如果PID没有获取到则为空,那么直接执行 kill -9 命令是错误的,因此应该对PID进行判断,如下:
    #判断tomcat是不是假死
     PID=$(ps -ef |grep tomcat |grep /u01/web/tomcat1 |grep -v 'grep'|awk '{print $2}' | xargs)
     if [ "$PID" ]
     then 
      echo "正在kill进程"
      kill -9 $PID
     else 
      echo "没有进程需要kill"
     fi