为什么用 sudo 生成的文件不归 root 所有?

use*_*739 0 permissions command-line root

我在终端中运行以下命令。

sudo tcpdump -c 2 -w /tmp/z.pcap icmp
Run Code Online (Sandbox Code Playgroud)

然后在终端中运行以下命令。

ping 8.8.8.8
Run Code Online (Sandbox Code Playgroud)

生成的文件属于用户 tcpdump 而不是 root。

$ stat /tmp/z.pcap 
  File: /tmp/z.pcap
  Size: 158             Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d      Inode: 4068722     Links: 1
Access: (0644/-rw-r--r--)  Uid: (  115/ tcpdump)   Gid: (  120/ tcpdump)
Access: 2021-02-25 10:05:52.910772287 -0500
Modify: 2021-02-25 10:06:00.102859691 -0500
Change: 2021-02-25 10:06:00.102859691 -0500
 Birth: 2021-02-25 10:05:52.910772287 -0500
Run Code Online (Sandbox Code Playgroud)

命令 tcpdump 属于根。为什么生成的文件不属于root?

$ ls -l $(which tcpdump)
-rwxr-xr-x 1 root root 1261512 2021/01/15-17:41:47 /usr/bin/tcpdump
Run Code Online (Sandbox Code Playgroud)

use*_*733 6

man tcpdump。如果没有必要,最好不要以 root 身份运行,因此开发人员补充说:

  -Z user
  --relinquish-privileges=user
         If  tcpdump is running as root, after opening the capture device
         or input savefile, change the user ID to user and the  group  ID
         to the primary group of user.

         This  behavior  is  enabled  by default (-Z tcpdump), and can be
         disabled by -Z root.
Run Code Online (Sandbox Code Playgroud)

换句话说:tcpdump 一旦产生,就不需要保留 root 权限,所以它会删除它们。