我正在尝试在python中创建一个脚本,它获取所用磁盘空间的百分比值。 我通过在子进程中运行df -h命令,然后将值存储在diskspace var。
中来完成此操作稍后当我在我的IF语句中使用它时,似乎它没有正确地获取该值。
磁盘空间百分比为76.我设置IF语句以触发电子邮件并在百分比高于90时打印消息。但是,尽管值较低,它仍会触发电子邮件并打印消息在IF。
我想这与我在python中获得的输出不仅仅是76的整数值而是('76 \ n',None)的事实有关,所以它将其视为字符串值?
有人有建议吗?
#!/usr/bin/python
import subprocess
import smtplib
import socket
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
hostname = socket.gethostname()
me = 'user@gmail.com'
you = ['a@gmail.com', 'b@gmail.com', 'c@gmail.com', 'd@gmail.com']
getdiskspace = "df -k / | awk 'NR > 1 {sub( \"%\", \"\", $5); print $5 }'"
proc = subprocess.Popen(getdiskspace, stdout=subprocess.PIPE, shell=True)
diskspace = proc.communicate()
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Disk space getting full ' + hostname
msg['From'] = me
msg['To'] = ", ".join(you)
msg['X-Priority'] = '1'
msg['X-MSMail-Priority'] = 'High'
text = "Disk space getting full on the " + hostname
html = """\
<html>
<head></head>
<body>
<p>
Diskspace is getting full on one of the servers, go check it out.
</p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
server = smtplib.SMTP("smtp.gmail.com", "587")
server.ehlo()
server.starttls()
server.login('user@gmail.com', 'MYPASS')
if (diskspace > 90):
print('This is not ok, load is ' + repr(diskspace))
server.sendmail(me, you, msg.as_string())
server.quit()
else:
print('this is ok.')