如何使用Python遍历Linux系统的挂载点?我知道我可以使用df命令来做这件事,但是有没有内置的Python函数来做这件事呢?
另外,我正在编写一个Python脚本来监控挂载点的使用情况并发送电子邮件通知。与Python脚本相比,使用普通shell脚本执行此操作会更好/更快吗?
谢谢。
发布于 2016-02-24 00:21:17
Python和跨平台方式:
pip install psutil # or add it to your setup.py's install_requires然后:
import psutil
partitions = psutil.disk_partitions()
for p in partitions:
print p.mountpoint, psutil.disk_usage(p.mountpoint).percent发布于 2014-09-30 14:10:59
从Python中运行mount命令不是解决该问题的最有效方法。你可以应用哈立德的答案,并用纯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()其中<subject>、<sender>和<recipient>应替换为相应的字符串。
发布于 2014-09-30 12:11:19
我不知道有没有这样做的库,但你可以简单地启动mount并返回一个列表中的所有挂载点,如下所示:
import commands
mount = commands.getoutput('mount -v')
mntlines = mount.split('\n')
mntpoints = map(lambda line: line.split()[2], mntlines)该代码检索来自mount -v命令的所有文本,将输出拆分为一个行列表,然后在每行中解析表示挂载点路径的第三个字段。
如果您想使用df,那么您也可以这样做,但是您需要删除包含列名的第一行:
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)一旦有了挂载点(mntpoints列表),就可以使用for in处理每个挂载点,代码如下:
for mount in mntpoints:
# Process each mount here. For an example we just print each
print(mount)Python有一个名为smtplib的邮件处理模块,用户可以在Python docs中查找信息
https://stackoverflow.com/questions/26112492
复制相似问题