Iterate over mount points using Python

How to iterate through mount points of a Linux system using Python? I know I can do this with the df command, but is there a Python built-in function for this?

Also, I'm just writing a Python script to track the use of mount points and send email notifications. Would it be better / faster to do this as a regular shell script compared to a Python script?

Thanks.

+5
source share
4 answers

Python and cross-platform way:

pip install psutil # or add it to your setup.py install_requires 

And then:

 import psutil partitions = psutil.disk_partitions() for p in partitions: print p.mountpoint, psutil.disk_usage(p.mountpoint).percent 
+14
source

I don't know any library that does this, but you can just run mount and return all the mount points in the 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 extracts all the text from mount -v , breaks the output into a list of lines, and then parses each line for the third field, which represents the path of the mount point.

If you want to use df , then you can do it too, but you need to delete the first row that 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 of them using code as follows:

 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 you can find information in Python Docs

+1
source

The bash way to do this is just for fun:

 awk '{print $2}' /proc/mounts | df -h | mail -s `date +%Y-%m-%d` " you@me.com " 
+1
source

Running the mount command from 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 with the corresponding lines.

+1
source

Source: https://habr.com/ru/post/1203671/


All Articles