将shell脚本转换为python程序

时间:2013-02-11 06:12:08

标签: python linux

我尝试编写一个shell脚本,当磁盘使用率达到70%时会向管理员发出警报。我想在python中编写这个脚本

#!/bin/bash
ADMIN="admin@myaccount.com"
INFORM=70

df -H  | grep -vE ‘^Filesystem|tmpfs|cdrom’ | awk ‘{ print $5 ” ” $6 }’ | while read   output;
do
use=$(echo $output | awk ‘{ print $1}’ | cut -d’%’ -f1  )
partition=$(echo $output | awk ‘{ print $2 }’ )
if [ $use -ge $INFORM ]; then
echo “Running out of space \”$partition ($use%)\” on $(hostname) as on $(date)” |
mail -s “DISK SPACE ALERT: $(hostname)” $ADMIN
fi
done

1 个答案:

答案 0 :(得分:1)

最简单(可理解)的方法是在外部进程上运行df命令,并从返回的输出中提取详细信息。

要在Python中执行shell命令,您需要使用subprocess模块。您可以使用smtplib模块向管理员发送电子邮件。

我编写了一个小脚本,该脚本应该用于过滤不需要监视的文件系统,执行一些字符串操作以提取文件系统和%使用的值,并在使用率超过阈值时打印出来。 / p>

#!/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()
  for line in output:
    parts = line.split()
    filesystem = parts[0]
    if filesystem not in IGNORE_FILESYSTEMS:
      usage = int(parts[4][:-1])  # Strips out the % from 'Use%'
      if usage > LIMIT:
        # Use smtplib sendmail to send an email to the admin.
        print 'Running out of space %s (%s%%) on %s"' % (
            filesystem, usage, datetime.datetime.now())


if __name__ == '__main__':
  main()

执行脚本的输出将是这样的:

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