我正在用 php 运行一个 bash 脚本,而 php 又会运行一个 python 脚本,但我收到很多错误,因为似乎www-data
无法使用我为自己的用户安装的 python 包。那么我如何才能让特定的包可用,www-data
这样做安全吗?此外,将其设置www-data
为特定子树的所有者是否安全/var/www/html
?
这是我运行以下命令时收到的错误:
sudo -u www-data ./bash_script_that_calls_runs_the_pythonscript.sh
Traceback (most recent call last):
File "./file.py", line 5, in <module>
from bs4 import BeautifulSoup
ImportError: No module named 'bs4'
但如果我运行:
./bash_script_that_calls_runs_the_pythonscript.sh
一切都会好起来的。
并且:
~/.local/lib/python3.5/site-packages$ ll | grep bs4
drwxrwxr-x 5 me www-data 4096 Dec 2 15:37 bs4/
drwxrwxr-x 2 me www-data 4096 Dec 2 15:38 bs4-0.0.1.dist-info/
请注意,我已递归设置了该组:
$ ll /home/me/.local/lib/python3.5/site-packages/bs4/
total 180
drwxrwxr-x 5 me www-data 4096 Dec 2 15:37 ./
drwx------ 51 me me 4096 Jan 16 04:33 ../
drwxrwxr-x 3 me www-data 4096 Dec 2 15:37 builder/
-rw-rw-r-- 1 me www-data 29910 Dec 2 15:38 dammit.py
-rw-rw-r-- 1 me www-data 6773 Dec 2 15:38 diagnose.py
-rw-rw-r-- 1 me www-data 68798 Dec 2 15:38 element.py
-rw-rw-r-- 1 me www-data 20394 Dec 2 15:38 __init__.py
drwxrwxr-x 2 me www-data 4096 Dec 2 15:37 __pycache__/
-rw-rw-r-- 1 me www-data 30800 Dec 2 15:38 testing.py
drwxrwxr-x 3 me www-data 4096 Dec 2 15:37 tests/
同样如此bs4-0.0.1.dist-info/
答案1
回答:
添加-H
或-i
选择sudo
:
sudo -i -u www-data ./bash_script_that_calls_runs_the_pythonscript.sh
sudo -H -u www-data ./bash_script_that_calls_runs_the_pythonscript.sh
解释:
您可以使用python -m site
检查导入路径。例如,在 的输出中sudo -u www-data python -m site
,USER_SITE
不是bs4
安装的预期目录。
sys.path = [
'/',
'/usr/local/lib/python3.6.2/lib/python36.zip',
'/usr/local/lib/python3.6.2/lib/python3.6',
'/usr/local/lib/python3.6.2/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6.2/lib/python3.6/site-packages',
]
USER_BASE: '/root/.local' (doesn't exist)
USER_SITE: '/root/.local/lib/python3.6/site-packages' (doesn't exist)
ENABLE_USER_SITE: True
使用sudo -i
或sudo -H
,你可以将主目录切换到用户www-data
并找到正确的USER_SITE
。 的输出sudo -i -u www-data python -m site
可能是:
sys.path = [
'/home/www-data',
'/usr/local/lib/python3.6.2/lib/python36.zip',
'/usr/local/lib/python3.6.2/lib/python3.6',
'/usr/local/lib/python3.6.2/lib/python3.6/lib-dynload',
'/home/www-data/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6.2/lib/python3.6/site-packages',
]
USER_BASE: '/home/www-data/.local' (exists)
USER_SITE: '/home/www-data/.local/lib/python3.6/site-packages' (exists)
ENABLE_USER_SITE: True