-2

我尝试编写一个 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
4

1 回答 1

2

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

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

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

#!/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
于 2013-02-11T07:25:49.060 回答