我試圖使用PHP的exec()函數執行python腳本。PHP exec(python.py),權限被拒絕寫入文件
的PHP頁面加載在瀏覽器:
<?php
echo exec("whoami");
echo(exec("/bin/python2.7 /var/www/cgi-bin/api/download.py"));
?>
下面是python腳本:如果執行的.py或.PHP作爲Apache用戶
# -*- encoding: UTF-8 -*-
import os
import httplib2
import io
import sys
from httplib2 import Http
from oauth2client import client
from oauth2client import tools
from apiclient import discovery
from oauth2client.file import Storage
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
from apiclient.http import MediaIoBaseDownload
from oauth2client.service_account import ServiceAccountCredentials
scopes = ['https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('/opt/scripts/full-patator-preprod.json', scopes)
delegated_credentials = credentials.create_delegated('#############')
http_auth = delegated_credentials.authorize(Http())
drive_service = build('drive', 'v2', http=http_auth)
def get_file(service,fileId):
file = service.files().get(fileId=fileId).execute(http=http_auth);
return file
item = get_file(drive_service,"#############")
print(item.get('title'))
delegated_credentials = credentials.create_delegated("#############")
http_auth = delegated_credentials.authorize(Http())
request = drive_service.files().export_media(fileId="#############", mimeType='application/pdf')
fh = io.FileIO("api/test.pdf","wb")
downloader = MediaIoBaseDownload(fh, request)
done = False
counter=0;
while done is False:
status, done = downloader.next_chunk()
print "Download %d%%." % int(status.progress() * 100)
counter+=1
if counter > 10:
done=True
with open("test.pdf") as f: ## PDF File
print(type(f)) ## Open file is TextIOWrapper
bw=io.TextIOWrapper(fh) ## Conversion to TextIOWrapper
print(type(bw)) ## Just to confirm
一切正常。 但是用我的瀏覽器,當它涉及到寫入文件:
fh = io.FileIO("api/test.pdf","wb")
我有這個輸出在我的Apache的error_log:
Traceback (most recent call last): File "/var/www/cgi-bin/api/download.py", line 46, in fh = io.FileIO("test.pdf","wb") IOError: [Errno 13] Permission denied: 'test.pdf'
好吧,我敢肯定,這是由於權限父文件夾,然後是父項的父項權限。但我對這些文件夾設置了777權限,它什麼也沒做。
我的PHP腳本是在/var/www/html/manager/execute.php 我的.py腳本在/var/www/cgi-bin/api/download.py
文件夾/ WWW/,/ cgi-bin /,/ api /擁有777個權限。
我知道這不是一個好習慣,但我想在做一些更乾淨的事情之前解決這個問題。
在此先感謝
如果你調用PHP文件在瀏覽器中的你將成爲用戶'WWW-data'。而普通的'www-data'在命令行上不應該擁有太多的權限。 – JustOnUnderMillions
PHP腳本以誰的身份運行?該用戶/組是否有權運行Python腳本? –
你好,我可以假設PHP運行爲Apache用戶,因爲當我執行: shell_exec(「whoami」); 它返回我「apache」 當然,apache是.py文件的所有者 –