shell 使用Python遍历挂载点

pdkcd3nj  于 2023-08-07  发布在  Shell
关注(0)|答案(4)|浏览(74)

如何使用Python迭代Linux系统的挂载点?我知道我可以用df命令来完成,但是有没有一个内置的Python函数来完成这个任务?
另外,我正在编写一个Python脚本来监视挂载点的使用情况并发送电子邮件通知。与Python脚本相比,作为普通shell脚本执行此操作会更好/更快吗?

  • 谢谢-谢谢
nfg76nw0

nfg76nw01#

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)

zkure5ic

zkure5ic2#

在Python中运行mount命令并不是解决这个问题的最有效方法。您可以应用Khalid的答案并在纯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>应替换为适当的字符串。

3j86kqsm

3j86kqsm3#

Bash的方式来做,只是为了好玩:

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

字符串

kognpnkq

kognpnkq4#

我不知道有哪个库可以做到这一点,但你可以简单地启动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中找到信息。

相关问题