1

我正在使用 Linux 12.04,apache 和 php 已安装在其上。我想访问 /root/ 文件夹中的文本文件。我对权限感到非常困惑。我正在使用的 php 脚本

<?php
$file = fopen("/root/cr.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached

while(!feof($file))
  {
  echo fgets($file). "<br>";
  }

fclose($file);
?>

此脚本能够访问文件 /var/www 文件夹,但无法访问 /root/ip.txt 文件。请帮助并解释一步一步的可能。

4

2 回答 2

1

我会忘记这样做的安全隐患,并将开始做生意:

如果你已经完成了 ls -l /var/www 和 ls -l /root 你会注意到两者都有不同的权限:

$ ls -l /root/cr.txt 总计 2 -rw-r----- 1 root root 0 Jul 9 01:28 cr.txt $ ls -l /var/www 总计 2 -rw-r--r -- 1 www-data www-data 0 Jul 9 01:28 somefile

/root 仅对 root 用户可读,而 /var/www 对 www-data 用户可读。现在,如果您检查 apache 进程,您会注意到它正在使用 www-data 用户运行。

$ ps辅助| grep apache www-data 5133 0.0 0.2 6512 1208 ?R+ 10:04 0:00 阿帕奇

现在,您正试图让 apache 与 www-data 用户一起运行读取文件。您可以采取三种行动:

1.将文件移动到 /var/www 并更改它的权限,以便 www-data 用户可以读取它。

mv /root/cr.txt /var/www/
chown www-data:www-data /var/www/cr.txt

2.这是最好的方法。

Create a symlink to the file in the /var/www directory:

ln /root/cr.txt /var/www/

3.在某些情况下,这并不能确保您的文件正在被读取。

这是危险的,不应该这样做!将 www-data 用户添加到根组,或更改文件所有权,以便 www-data 用户可以读取:

chown :www-data /root/cr.txt
## Or
sudo adduser www-data root

如果您不了解风险,则不应这样做!

于 2013-08-08T17:52:47.650 回答
0

首先,让 apache 访问 root 通常是个坏主意。如果你坚持 ...

安装 ACL(访问控制列表) 安装 ACL

然后,假设您的 apache 服务器使用 'apache2' 运行它的用户和组,请授予 apache2 用户和组对目录/文件的访问权限:

setfacl -m "group:apache2:r-x" /root/whatever.file
setfacl -m "user:apache2:r-x" /root/whatever.file

# *** only need the next two lines if you plan on writing new files in the specified  directory.  It sets the default file permissions that will be used when the new file is created.
setfacl -d -m "group:apache2:r-x" /root
setfacl -d -m "user:apache2:r-x" /root

将 rx 权限更改为您需要的任何内容

编辑 - 没有 ACL 的潜在解决方案

以下内容未经测试,可能需要调整,但应该让您朝着正确的方向前进。使用风险自负!

创建一个新组。该名称可以是任何名称,但对于本示例,我将使用groupadd将其称为“wwwadmins”

 groupadd wwwadmins

使用usermod将 root 和 apache2 用户添加到这个新组

 usermod -a -G wwwadmins root
 usermod -a -G wwwadmins apache2

使用chown将文件的组所有者更改为新组

 chown :wwwadmins /root/whatever.file
于 2013-08-06T12:03:31.070 回答