如何授予sudo日志文件权限?

时间:2019-03-27 21:30:25

标签: python logging

我按如下所示设置日志记录,但是由于位置/gerrit_v2/hooks/changemergedlogs需要sudo权限,因此记录失败,如何通过脚本赋予sudo权限?

代码:-

import os,time,logging

# setup logging
changemergedhooklog = 'change_merged_hook_log_' + time.strftime("%m%d%Y") + '_' + time.strftime("%H%M%S") + '.txt'
#log = os.path.join(os.path.dirname(os.path.realpath(__file__)),changemergedhooklog)
log = os.path.join(os.path.dirname(os.path.realpath(__file__)),'changemergedlogs',changemergedhooklog)
logger = logging.getLogger(__name__)
#logger.setLevel(logging.DEBUG)
logger.setLevel(10)
ch = logging.StreamHandler()
#ch.setLevel(logging.DEBUG)
ch.setLevel(10)
formatter = logging.Formatter('%(asctime)s %(filename)-15s %(funcName)-20s %(lineno)-5s  %(levelname)-8s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
ch.setFormatter(formatter)
logger.addHandler(ch)

fh = logging.FileHandler(log, 'w')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)

错误:-

  File "copytest.py", line 17, in <module>
    fh = logging.FileHandler(log, 'w')
  File "/Network/Servers/nwna40a.apple.com/vol/homedir4/wgerrit/.pyenv/versions/2.7.6/lib/python2.7/logging/__init__.py", line 903, in __init__
    StreamHandler.__init__(self, self._open())
  File "/Network/Servers/nwna40a.apple.com/vol/homedir4/wgerrit/.pyenv/versions/2.7.6/lib/python2.7/logging/__init__.py", line 926, in _open
    stream = open(self.baseFilename, self.mode)
IOError: [Errno 13] Permission denied: '/gerrit_v2/hooks/changemergedlogs/change_merged_hook_log_03272019_142144.txt'

1 个答案:

答案 0 :(得分:0)

以root用户或sudo的身份运行脚本。

如果这不是一个选项,则可以通过sudo调用os.geteuid()来检测何时不运行。如果os.geteuid() != 0不是使用sudo运行的。如果是这种情况,您可以再次给自己打电话,但是这次使用sudo,类似subprocess.call(['sudo', 'python3', *sys.argv])