Jenkins如何使用Groovy删除Linux进程

    host = "[email protected]"
    //进程名称
    process ="/usr/local/tomcat"
   +++++++ 方法一 +++++++
    //进程个数
    result = sh returnStdout: true ,script: "ssh $host \"ps -ef | grep \'$process\' | grep -v grep| wc -l\""
    result = result.trim()
    echo result
    if (result!=null && result.toInteger() > 0){
        echo "kill 进程 "+result+"个!"
        try { 
            sh "ssh $host \'ps -ef | grep \"$process \" | grep -v grep | awk \"{print \$2}\" | xargs kill -9\'"
        } catch(Exception ex) {
            resultTemp = sh returnStdout: true ,script: "ssh $host \"ps -ef | grep \'$process \' | grep -v grep| wc -l\""
            echo "进程kill成功"
            if (resultTemp!=null && resultTemp.toInteger() > 0){
                echo "进程kill失败"
                ex.printStackTrace()
            }
        }
    }else{
        echo "kill 进程 0个!"
    }
    +++++++方法二+++++++
    killSh = "ps -ef|grep \'$process\' |grep -v grep|awk \'{print \\\$1\\\",\\\"\\\$2}\'|awk -F\',\' \'{print \\\$2}\'|xargs kill -9"
    try { 
        sh "ssh $host \"$killSh\""
        echo "KILL SUCCESS"
    } catch(Exception e1) {
        def msg = e1.getMessage();
        if(msg=="script returned exit code 123"){
            echo "This process does not exist!"
        }else{
            echo "KILL FAILURE!"
        }
    } 

其中需要注意两个点

  1. ssh远程操作的时候,ssh userName@local “需要执行的命令,这里就是普通的字符串”
    例如

    killSh = "ps -ef|grep \'$process\' |grep -v grep|awk \'{print \\\$1\\\",\\\"\\\$2}\'|awk -F\',\' \'{print \\\$2}\'|xargs kill -9"
    

    将字符串拼接好,放入ssh后的双引号之内就可以了。

  2. Groovy异常的捕获

    try { 
       //Protected code 
    } catch(ExceptionType1 e1) { 
       e1.getMessage()//异常信息
    } catch(ExceptionType2 e2)  {
      e2.printStackTrace()//抛出异常
    }
    

注:
在linux中请慎重使用标点符号,双引号中的语句可以直接使用$test这种方式赋值

ssh host “$test...”

当有反斜杠存在的时候,使用${test}这种形式,大括号可以用来区分

ssh host “${path}/test.log”

猜你喜欢

转载自blog.csdn.net/qq_35275077/article/details/89351688