Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through mount points using Python

Tags:

python

shell

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.

like image 769
drunkenfist Avatar asked Sep 30 '14 03:09

drunkenfist


4 Answers

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.

like image 125
isedev Avatar answered Oct 17 '22 17:10

isedev


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
like image 28
Michel Samia Avatar answered Oct 17 '22 19:10

Michel Samia


The bash way to do it, just for fun:

awk '{print $2}' /proc/mounts | df -h | mail -s `date +%Y-%m-%d` "[email protected]"
like image 2
Burhan Khalid Avatar answered Oct 17 '22 18:10

Burhan Khalid


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

like image 2
Michael Petch Avatar answered Oct 17 '22 18:10

Michael Petch