7

Ubuntu server 16.04.5 LTS

I have a python script which creates log files using the following code:

today = datetime.today()
datem = datetime(today.year, today.month, today.day)
logger = logging.getLogger('processImport')
hdlr = logging.FileHandler('{0}myLog_{1}-{2}-{3}.log'.format(myLogFileLocation, datem.year, datem.month, datem.day))
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.INFO)

saving a log entry with:

logger.info(logMessage)

I then have a cron job that deletes older log files after a certain period by executing a python file which uses os.remove(fullFilePath) to delete the file.

However, I am getting a permissions error when this cron job executes.

OSError: [Errno 13] Permission denied: PathToTheFile\theLogFileName.log

When I check the permissions for the file they are set to:

-rw-r--r-- 1 www-data www-data etc etc

What do I need to do to enable the cron job to have permission to delete the log files please?

Thank you.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Doug
  • 665
  • 2
  • 8
  • 22

1 Answers1

9

There seems to be a write issue permission with the folder. Changing the permission should help.

Try this:

log_dir = '/abs/path/of/directory'

os.chmod(log_dir, 0777)   # for Python2
os.chmod(log_dir, 0o777)  # for Python3

Let me know how it goes.

Note that Python3 requires prefixing octal numbers with 0o now instead of just 0. See here: Invalid Token when using Octal numbers. Otherwise you'll get this error:

SyntaxError: invalid token

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
Sagar Dawda
  • 1,126
  • 9
  • 17
  • Thanks, solved. It was the permissions on the parent folder. I changed these with `chmod 777 DirName` directly from terminal rather than with python (I had tried that yesterday and I guess for the same reasons that too had a permissions error). – Doug Nov 27 '18 at 03:26
  • 4
    This is a very bad idea as the permissions are too loose. Now everyone has permissions to create and delete files there. Apart from destroying the logfiles to hide hacking attempts one can also replace them with symlinks and have the daemon then write to other files the user has no access too. – Goswin von Brederlow Nov 11 '19 at 14:00
  • 4
    In Python 3, you need to prefix the mode (if octal) with `0o`: ```os.chmod(log_dir, 0o777)``` – Agnes Kis Oct 11 '20 at 12:58
  • 1
    Using `0o777` sets permissions to read/write/execute for everyone (user and group and other). If the file is _not_ an executable, use `0o666` instead. That gives everyone only read/write permissions, leaving off the executable part. – Gabriel Staples Dec 13 '22 at 17:05