I'm trying to get the available disk space on a remote linux host using python. The best way I could think to do this would be to os.popen a df command, and use regex to get the available space from the output. I then need to apply a variable to that free space number, which is where I'm stuck.

The output looks like:

Filesystem           1K-blocks       Used Available  Use% Mounted on
/dev/sdb1            1073409200  321713576 698008536   32%  /mnt/test

Here's what I have so far, and what's gotten me the furthest:

import os
import re

PLINK      = "C:\\plink.exe -pw password root@"

command = os.popen(PLINK + "hostname"  + " df /mnt/test")
output = command.read()
pattern = re.compile('\s\d+\s')
found = pattern.search(output)

now if I do
print found.group(0)

It returns the number of 1k blocks. I cant find a group number that returns the available space. In my rx toolkit that regex matches the 1K blocks and the available space.

Always use raw literal strings with regexes (with the r prefix):

pattern = re.compile(r'\s\d+\s')

it's the only serious way to ensure that backslashes are preserved. You could use a found.findall() which returns a list of string results, or found.finditer() which return an iterable of match objects.
Otherwise your use of plink.exe could probably be replaced by a small code using module paramiko, something along the lines of

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.46.24', username='user', password='password', allow_agent = False)
i, o, e = ssh.exec_command('df /mnt/test')
print o.readlines()

Also, os.popen() is considered obsolete and is deprecated in python 2.6 and does not even exist in py3k. The normal way is to use the subprocess module, but if you choose paramiko for this task, you don't need a subprocess.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.