将shell脚本转换为python程序
我曾尝试编写一个shell脚本,当磁盘使用率达到70%时会提醒管理员。我想用python编写这个脚本将shell脚本转换为python程序,python,linux,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’%’
#!/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
对于您来说,最简单(可以理解)的方法是在外部进程上运行df
命令,并从返回的输出中提取细节
要在Python中执行shell命令,需要使用子流程
模块。您可以使用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
你试过什么?StackOverflow不是来为您编写代码的。目标很好。哪些部分您不知道如何使用Python?如果答案是“全部”,对你来说可能不是个好主意。你只需要用一件你不知道的东西来交换另一件你不知道的东西。我是python新手,问这个问题是为了得到一些指导,当然不是为了修改整个代码。如果我的问题看起来很苛刻,请原谅