将Shell脚本转换为Python程序

-2 投票
1 回答
4024 浏览
提问于 2025-04-17 15:28

我尝试写一个脚本,当磁盘使用率达到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 个回答

2

对你来说,最简单明了的方法就是在一个外部进程中运行 df 命令,然后从返回的结果中提取你需要的信息。

要在Python中执行一个命令行指令,你需要用到 subprocess 模块。同时,你可以使用 smtplib 模块来给管理员发送邮件。

我写了一个小脚本,它可以过滤掉你不需要监控的文件系统,进行一些字符串处理,提取出文件系统和使用百分比的值,并在使用量超过设定的阈值时打印出来。

#!/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

撰写回答