bash 如何终止使用 sudo 运行的进程?Ctrl+C 执行,但不杀死
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7269947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to terminate a process which is run with sudo? Ctrl+C do it, but not kill
提问by blaketang
At my company, some commands are allowed to run with sudo, such as tcpdump. Others not.
在我公司,一些命令是允许使用 sudo 运行的,例如 tcpdump。其他人没有。
I expect run tcpdump for a while, and then stop it. When I run tcpdump, and I could abort that with Ctrl+C
我希望运行 tcpdump 一段时间,然后停止它。当我运行 tcpdump 时,我可以使用 Ctrl+C 中止它
I wrote a shell script like this -
我写了一个这样的shell脚本 -
#!/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.
它真的不起作用。tcpdump的进程是以root身份运行的,当前用户是一个普通账户。
My question is: is there any way to do the equivalent of ctrl c in bash script?.
我的问题是:有没有什么办法可以在 bash 脚本中做相当于 ctrl c 的事情?
EDIT:
编辑:
ps:As my company's security policy, I cannot run kill as root.
ps:作为我公司的安全政策,我不能以root身份运行kill。
采纳答案by jon
Try the -Zoption to tcpdump. It instructs tcpdump to drop root privileges and run as the user specified in the argument.
尝试-Z选择tcpdump. 它指示 tcpdump 放弃 root 权限并以参数中指定的用户身份运行。
sudo tcpdump -Z $USER -ieth1 -w ~/dump.bin
Now try killing that process.
现在尝试杀死该进程。
回答by Blagovest Buyukliev
Simply run killthrough sudoas well:
只需运行kill通过sudo,以及:
sudo kill -2 $!
This way the killprocess will have the privilege to send signals to a process that runs as root.
这样,kill进程将有权向以 root 身份运行的进程发送信号。
回答by Robert Wohlfarth
回答by david.perez
For programs that don't have special switches like -Zand in case you can alter sudoers file, this is a solution:
对于没有特殊开关的程序,-Z如果您可以更改 sudoers 文件,这是一个解决方案:
sudo myprogram &
sleep 5
sudo pkill myprogram
All I have to do is to allow to run pkill myprogrampasswordless by using visudoand adding this line:
我所要做的就是pkill myprogram通过使用visudo和添加以下行来允许无密码运行:
myuser ALL=(ALL) NOPASSWD:/bin/pkill myprogram
This is less dangerous that lo let sudo kill any program.
这比让 sudo 杀死任何程序更不危险。
回答by Patrick B.
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 Blagovestshould do it.
回答by Vijay Anand Pandian
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)
G - 超时秒数(超时后命令会自动被杀死) Z - 删除 root 并以用户权限运行 W - 要保存的文件数(作为拆分文件)

