Thursday, 15 April 2010

linux - converting a shell script into python program -



linux - converting a shell script into python program -

i have tried writing shell script alerts admin when disk usage reaches 70%. want write script in python

#!/bin/bash admin="admin@myaccount.com" inform=70 df -h | grep -ve ‘^filesystem|tmpfs|cdrom’ | awk ‘{ print $5 ” ” $6 }’ | while read output; use=$(echo $output | awk ‘{ print $1}’ | cutting -d’%’ -f1 ) partition=$(echo $output | awk ‘{ print $2 }’ ) if [ $use -ge $inform ]; echo “running out of space \”$partition ($use%)\” on $(hostname) on $(date)” | mail service -s “disk space alert: $(hostname)” $admin fi done

the easiest(understandable) approach run df command on external process , extract details returned output.

to execute shell command in python, need utilize subprocess module. can utilize smtplib module send emails admin.

i cooked little script should job of filtering filesystems don't need monitor, string manipulation pull out filesystem , % used values , prints out when usage exceeds threshold.

#!/bin/python import subprocess import datetime ignore_filesystems = ('filesystem', 'tmpfs', 'cdrom', 'none') limit = 70 def main(): df = subprocess.popen(['df', '-h'], stdout=subprocess.pipe) output = df.stdout.readlines() line in output: parts = line.split() filesystem = parts[0] if filesystem not in ignore_filesystems: usage = int(parts[4][:-1]) # strips out % 'use%' if usage > limit: # utilize smtplib sendmail send email admin. print 'running out of space %s (%s%%) on %s"' % ( filesystem, usage, datetime.datetime.now()) if __name__ == '__main__': main()

the output of executed script this:

running out of space /dev/mapper/arka-root (72%) on 2013-02-11 02:11:27.682936 running out of space /dev/sda1 (78%) on 2013-02-11 02:11:27.683074 running out of space /dev/mapper/arka-usr+local (81%) on 2013-02-11 02:11

python linux

No comments:

Post a Comment