Tuesday, January 1, 2013

Simple Python Script in UNIX calculating the number of PHP session files

This script reads the number of PHP session files in your server's /tmp directory, then writes a summary report to a log file.


import os
from time import strftime

stamp = strftime("%Y-%m-%d %H:%M:%S")
logfile = '/path/to/your/logfile.log'
path = '/path/to/tmp/directory/'

files = os.listdir(path)
bytes = 0
numfiles = 0

for f in files:
 if f.startswith('sess_'):
  info = os.stat(path + f)
  numfiles += 1
  bytes += info[6]

if numfiles > 1:
 title = 'files'
 title = 'file'

string = stamp + " -- " + str(numfiles) + " session " \
+ title +", " + str(bytes) + " bytes\n"

file = open(logfile,"a")

Listing 12 shows the entire script. Open an editor, and paste the code into it and save the file as tmp.py somewhere on your system. Then run chmod + x on that file to make it executable

Next, create a variable called logfile and put in a path to a file (it doesn't need to exist yet) where you'll actually store log file messages. For simplicity, I put log files in a /logs folder, but you could put them anywhere. Similarly, you need a variable called path that contains the path to your /tmp directory. It can be any path you want as long as you end it with a trailing slash (/).

No comments:

Post a Comment