How do I iterate through the mount points of a Linux system using Python? I know I can do it using df command, but is there an in-built Python function to do this?
Also, I'm just writing a Python script to monitor the mount points usage and send email notifications. Would it be better / faster to do this as a normal shell script as compared to a Python script?
Thanks.
The Python and cross-platform way:
pip install psutil # or add it to your setup.py's install_requires
And then:
import psutil
partitions = psutil.disk_partitions()
for p in partitions:
print p.mountpoint, psutil.disk_usage(p.mountpoint).percent
The bash way to do it, just for fun:
awk '{print $2}' /proc/mounts | df -h | mail -s `date +%Y-%m-%d` "you@me.com"
I don't know of any library that does it but you could simply launch mount
and return all the mount points in a list with something like:
import commands
mount = commands.getoutput('mount -v')
mntlines = mount.split('\n')
mntpoints = map(lambda line: line.split()[2], mntlines)
The code retrieves all the text from the mount -v
command, splits the output into a list of lines and then parses each line for the third field which represents the mount point path.
If you wanted to use df
then you can do that too but you need to remove the first line which contains the column names:
import commands
mount = commands.getoutput('df')
mntlines = mount.split('\n')[1::] # [1::] trims the first line (column names)
mntpoints = map(lambda line: line.split()[5], mntlines)
Once you have the mount points (mntpoints
list) you can use for in
to process each one with code like this:
for mount in mntpoints:
# Process each mount here. For an example we just print each
print(mount)
Python has a mail processing module called smtplib
, and one can find information in the Python docs
Running the mount
command from within Python is not the most efficient way to solve the problem. You can apply Khalid's answer and implement it in pure Python:
with open('/proc/mounts','r') as f:
mounts = [line.split()[1] for line in f.readlines()]
import smtplib
import email.mime.text
msg = email.mime.text.MIMEText('\n'.join(mounts))
msg['Subject'] = <subject>
msg['From'] = <sender>
msg['To'] = <recipient>
s = smtplib.SMTP('localhost') # replace 'localhost' will mail exchange host if necessary
s.sendmail(<sender>, <recipient>, msg.as_string())
s.quit()
where <subject>
, <sender>
and <recipient>
should be replaced by appropriate strings.