Python Forum

Full Version: how can I find the disk space on a remote hosts ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can find the disk space for the host I am on using this script

#!/usr/bin/env python3
import shutil
total, used, free = shutil.disk_usage(__file__)
print( int(total/1024), int(used/1024), int(free/1024))

What I need is to find the disk space ON A REMOTE HOST.
I want to replace a bash script with a python script

I want to go through a list of hosts and determine the  disk space usage.  

We use redhat 5/6/7
There is more then one way to get the free disk space.
One solution can be to execute df on the remote host and grab the output and parse it.
If you're forced to use python 2.6 you should use Popen instead of check_output.

import subprocess
from collections import namedtuple

def remote_df(user, ip, path):     
    """
    Executes df on remote host and return
    (total, free, used) as int in bytes
    """
    Result = namedtuple('diskfree', 'total used free')
    output = subprocess.check_output(['ssh', '%s@%s' % (user, ip), '-C', 'df'], shell=False)
    output = output.splitlines()
    for line in output[1:]:                                                                                                     
        result = line.decode().split()
        if result[-1] == path:
            used = int(result[2])
            free = int(result[3])
            total = used + free
            return Result(total, used, free)
        else:
            raise Exception('Path "%s" not found' % path)
In [4]: remote_df('root', '5.9.xx.xx', '/')
Out[4]: diskfree(total=1002937124, used=55634764, free=947302360)
I'm using ssh-key based authentication. To use ssh with passwords you can use paramiko.
If you want to do more advanced stuff with ssh, you should take a look http://www.paramiko.org/.
Another solution can be a remote service on every host, which supplies the manager with data from the remote hosts.