blaketang
blaketang

Reputation: 113

how to terminate a process which is run with sudo? Ctrl+C do it, but not kill

At my company, some commands are allowed to run with sudo, such as tcpdump. Others not.

I expect run tcpdump for a while, and then stop it. When I run tcpdump, and I could abort that with Ctrl+C

I wrote a shell script like this -

#!/bin/sh
sudo tcpdump -ieth1 -w ~/dump.bin
sleep 5
kill -2 $!

it doesn't really work. The process of tcpdump is run as root, and current user is a normal account.

My question is: is there any way to do the equivalent of ctrl c in bash script?.

EDIT:

ps:As my company's security policy, I cannot run kill as root.

Upvotes: 11

Views: 14904

Answers (6)

david.perez
david.perez

Reputation: 7012

For programs that don't have special switches like -Z and in case you can alter sudoers file, this is a solution:

sudo myprogram &
sleep 5
sudo pkill myprogram

All I have to do is to allow to run pkill myprogram passwordless by using visudo and adding this line:

myuser ALL=(ALL) NOPASSWD:/bin/pkill myprogram

This is less dangerous that lo let sudo kill any program.

Upvotes: 2

Patrick B.
Patrick B.

Reputation: 12333

sudo tcpdump -ieth1 -w ~/dump.bin 

will block your script, you need to put it into the background:

sudo tcpdump -ieth1 -w ~/dump.bin &

.

This and the answer from Blagovest should do it.

Upvotes: 0

Vijay Anand Pandian
Vijay Anand Pandian

Reputation: 1165

sudo tcpdump -Z root -w ~/dump.bin -n -i eth0 -G 300 -W 1

G - Timeout Seconds (After timeout period the comman gets killed automatically) Z - drop root and runs as user privilege W - Number files to be saved (as a splitted file)

Upvotes: 0

jon
jon

Reputation: 96

Try the -Z option to tcpdump. It instructs tcpdump to drop root privileges and run as the user specified in the argument.

sudo tcpdump -Z $USER -ieth1 -w ~/dump.bin

Now try killing that process.

Upvotes: 8

Robert Wohlfarth
Robert Wohlfarth

Reputation: 1771

The timeout command also terminates a program after so long. sudo timeout 5 tcpdump -ieth1 -w ~/dump.bin should accomplish the same thing as the script.

Upvotes: 1

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

Simply run kill through sudo as well:

sudo kill -2 $!

This way the kill process will have the privilege to send signals to a process that runs as root.

Upvotes: 5

Related Questions