2014-09-11 2 views
7

한다 : 내가 파이썬 ./myCreate.py을 실행할 때
fo = open("./testFile.txt", "wb")내가 myCreate.py라는 파이썬 스크립트의 간단한 조각이 리눅스에서 실행이 소유자 루트

-의 소유자 testFile.txt는 내 사용자를 유지합니다. sudo python ./myCreate.py를 실행할 때 testFile.txt의 소유자가 루트가됩니다. 처형

의 모두 이전에 실행되지 않은

testFile.txt

어떻게 내가 파일의 소유자가 실제 사용자가 아닌 유효 사용자 체류 할 수 있습니다! 감사합니다.

+0

는'를 chown' 5gon12eder. –

+0

내가 실제 사용자로 열길 원하는데, 누가 이건 ... 하드 코딩되지 않은 것입니까? – ABR

+0

현재 사용자를 확인하고 그 사용자에게 chown 할 수 있습니다. –

답변

6

는 루트로 실행 의미한다. 따라서 파일은 루트가 소유하고있는 것이 정상입니다.

파일을 만든 후에 소유권을 변경할 수 있습니다. 이렇게하려면 sudo를 실행하는 사용자를 알아야합니다. 다행히 sudo를 사용할 때 설정되는 SUDO_UID 환경 변수가 있습니다.

그래서, 당신은 할 수 있습니다 :

import os 
print(os.environ.get('SUDO_UID')) 

을 그런 다음 change the file ownership 필요 :

os.chown("path/to/file", uid, gid) 

우리가 함께 넣어 경우 : 물론

import os 

uid = int(os.environ.get('SUDO_UID')) 
gid = int(os.environ.get('SUDO_GID')) 

os.chown("path/to/file", uid, gid) 

, 당신은거야 더 편리하기 때문에 함수로 사용하십시오.

import os 

def fix_ownership(path): 
    """Change the owner of the file to SUDO_UID""" 

    uid = os.environ.get('SUDO_UID') 
    gid = os.environ.get('SUDO_GID') 
    if uid is not None: 
     os.chown(path, int(uid), int(gid)) 

def get_file(path, mode="a+"): 
    """Create a file if it does not exists, fix ownership and return it open""" 

    # first, create the file and close it immediatly 
    open(path, 'a').close() 

    # then fix the ownership 
    fix_ownership(path) 

    # open the file and return it 
    return open(path, mode) 

사용법 :

# If you just want to fix the ownership of a file without opening it 
fix_ownership("myfile.txt") 

# if you want to create a file with the correct rights 
myfile = get_file(path) 

편집 : Robᵩ @ @Basilevs에 대한 내 대답 덕분에 업데이트하고 @ 당신이 그것을 만든 후

+0

훌륭한 설명이지만'SUDO_UID'는'SUDO_USER'보다 더 편리하지 않습니까? –

+0

@ Robᵩ 또는 더 안전한가요? – Basilevs

+0

'SUDO_USER'가 설정되어 있지 않으면 파일을 단순히'chown '하는 것이 더 이식성이 있습니다. – 5gon12eder

2

os.stat을 사용하여 먼저 포함하는 폴더의 사용 권한을 얻은 다음 파일 게시 작성에 적용하는 방법에 대해 설명합니다.

이 (python2를 사용)과 같을 것이다 : 엘리엇으로

import os 

path = os.getcwd() 
statinfo = os.stat(path) 

fo = open("./testFile.txt", "wb") 
fo.close() 
euid = os.geteuid() 
if (euid == 0) # Check if ran as root, and set appropriate permissioning afterwards to avoid root ownership 
    os.chown('./testFile.txt', statinfo.st_uid, statinfo.st_gid) 

는 동시에 여러 개의 파일을 생성 할 수 있다면,이 함수로 더 구조화 될 것이라고 지적했다.

적절한 사용자 ID를 찾을 수 os.environ를 사용하여 사용 os.chown()
2

: sudo를 사용하여 스크립트를 실행

import os 

fo = open("./testFile.txt", "wb") 
fo.close() 
os.chown('./testFile.txt', 
     int(os.environ['SUDO_UID']), 
     int(os.environ['SUDO_GID']))