trina24
trina24

Reputation: 11

Kill all processes on specific port via Jenkins

I'd like to have a Jenkins job which kills all processes on port 5000 (bash). The easy solution

fuser -k 5000/tcp

works fine when I execute this command in the terminal, but on Jenkins ("execute shell") marks build as failure.

I have tried also

kill $(lsof -i -t:5000)

but again, as it works on regular terminal, on Jenkins I get

kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
Build step 'Execute shell' marked build as failure

Any ideas how to fix this?

Upvotes: 1

Views: 6780

Answers (5)

SK -
SK -

Reputation: 469

I was facing the same issue and in many cases standard input/output is disabled (specially when you have ssh to the target machine). What you can do is create a executable shell file in the target server and execute that file.

So, the step would look something like below :

Step 1 . -> create the shell file

 cat > kill_process.sh << EOF
 target_port_num=\`lsof -i:\${1} -t\`;
 echo "Kill process at port is :: \${target_port_num}"
 kill -9 \${target_port_num}
 EOF

Step 2 . -> make it executable chmod +x process_killer.sh

Step 3 . -> execute the shell and pass the port number ./process_killer.sh 3005

Hope this help.

Upvotes: 0

elodingens
elodingens

Reputation: 61

I hadd the same problem. It did not work when the process was not running. bash just did it, but jenkins failed.

You can add an || true to your jenkins job to indicate jenkins to proceed with the job if the bash command fails.

So its:

fuser -k 5000/tcp || true

see also don't fail jenkins build if execute shell fails

Upvotes: 6

Carlos Augusto Pega
Carlos Augusto Pega

Reputation: 1

The problem is that $ is a special char in jenkins commands. It means you are referring to an ENV VAR.

You should try writing the command wrapped with single quotes.

Upvotes: 0

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

maybe jenkins user can't see the processes because of privileges so the expansion of $(lsof ..) is empty.

the error output may not be complete because if lsof call fails there will be a message on stderr.

Upvotes: 0

Joao  Vitorino
Joao Vitorino

Reputation: 3256

Try put the command with the path

/usr/bin/kill $(/usr/sbin/lsof -i -t:5000)

If the user running the jenkins service is not the same as the user with the process on port 5000 you won't be able to kill the process. Maybe you will need to run this with sudo.

Try this

su -s jenkins #Or the user who run jenkins
/usr/bin/kill $(/usr/sbin/lsof -i -t:5000)

Upvotes: 2

Related Questions