简体   繁体   中英

Get a list of all mounted file systems in Linux with python

I am planning to automate a process of cleaning file systems in Linux using a set of scripts in Shell, Python and I'll create a simple dashboard using Node.js to allow a more visual approach.

I have a script in Shell which already cleans a file system in a specific server - but I have to login and then issue this command. Now I am proceeding with a dashboard in HTML/CSS/JS to visualize all servers which are having space problems.

My idea is: create a Python scrip to login and get a list of filesystems and its usage and update a single JSON file, then, my dashboard uses this JSON to feed the screen.

My question is how to get the list of file system in Linux and its usage?

To remote connect to a ssh and retrive a list with the filesystems and usage you can use paramiko SSH client and df command like this:

To install paramiko using pip issue:

sudo pip install paramiko

The regex module should be default installed

import paramiko, re

server = "your_server_ip_or_name"
username = "your_ssh_user"
password = "your_ssh_password"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("df")

filesystems = []
for line in ssh_stdout.readlines()[1:]:
    line = re.sub('\s+', ' ', line).strip()
    parameters = line.split(' ')
    usage_percent =  re.findall(r'\d+', parameters[4])
    filesystems.append({'name' : parameters[0], 'usage' : usage_percent[0]})

print filesystems

It will result in a list of dictionaries containing keys name, and usage like in this example:

[{'usage': u'17%', 'name': u'/dev/root'}, {'usage': u'0%', 'name': u'devtmpfs'}, {'usage': u'0%', 'name': u'tmpfs'}, {'usage': u'9%', 'name': u'tmpfs'}, {'usage': u'1%', 'name': u'tmpfs'}, {'usage': u'0%', 'name': u'tmpfs'}, {'usage': u'31%', 'name': u'/dev/mmcblk0p6'}, {'usage': u'0%', 'name': u'tmpfs'}]

You can use command

df

Provides an option to display sizes in Human Readable formats (eg, 1K 1M 1G) by using '-h'.This is the most common command but you can also check du and di . di in fact provides even more info than df .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM