在不需要 sudo 的情况下在 root 拥有的 shell 脚本中创建文件

Mat*_*att 2 bash shell ubuntu

乍一看,这似乎是一个有点奇怪的问题,但我在这里。

我正在编写一个 shell 脚本,该脚本构成一个文件系统,该文件系统将被压缩回存档,并且其中需要一些文件由 root 用户拥有。整个事情很快就会自动化,但现在有点问题,因为如果我使用 sudo 我需要输入密码。

看到这些文件是在我自己的主目录下创建的,我对其拥有完全访问权限,我想也许我可以将它们的所有权更改为 root 用户。那可能吗?

如果我正常尝试,我会得到“不允许操作”。也许还有其他选择?

Ren*_*non 5

您可以使用fakeroot做您想做的事。它是一个库,使程序认为它们以 root 身份运行,而实际上并非如此。IIRC,它用于dpkg允许非 root 用户构建.deb包含 root 拥有的文件的包。

看看这个shell脚本:

#!/bin/bash

mkdir image
touch image/user-owned
touch image/root-owned

chown renato.renato image/user-owned
chown root.root     image/root-owned

tar cf image.tar image
Run Code Online (Sandbox Code Playgroud)

通常,我只能以 root 身份创建这个 tar 存档。但是,如果我使用 fakeroot:

$ fakeroot ./create-image.sh
$ tar tvf image.tar

drwxr-xr-x root/root         0 2014-04-09 01:09 image/
-rw-r--r-- root/root         0 2014-04-09 01:09 image/root-owned
-rw-r--r-- renato/renato     0 2014-04-09 01:09 image/user-owned
Run Code Online (Sandbox Code Playgroud)

但是,磁盘上的文件仍然是用户所有的,所以这里没有安全风险:

$ ls -l image/

total 0
-rw-r--r-- 1 renato renato 0 Abr  9 01:09 root-owned
-rw-r--r-- 1 renato renato 0 Abr  9 01:09 user-owned
Run Code Online (Sandbox Code Playgroud)