#!/usr/bin/python import getpass import sys import os import getopt import commands import time __author__ = "Anuj Bhatt (anuj.bhatt@gmail.com)" __date__ = "Nov 3 2008" def printUsage(): """Prints usage info for red.py""" print """ red: A script that tries to emulate what ReadyBoost does (but not quite). RUNNING #./red [-mrh] OPTIONS m: make cache on attached device r: remove cache on attached device h: help (This message will be printed again)""" def doPreprocessing(): """Preprocessing to get details from mount and df""" #Get the last mounted device name cmd_str_mount = "mount | tail -n1" ret_str = commands.getoutput(cmd_str_mount) temp_str = ret_str.split() #Device name is obtained here device_name = temp_str[2] #Get Avail space on device_name cmd_str_df = "df | tail -n1" ret_avail = commands.getoutput(cmd_str_df) temp_str = ret_avail.split() #Avail space is obtained here avail_space = temp_str[3] return device_name, avail_space def makeCache(): """Make cache on the attached device""" device_name, avail_space = doPreprocessing() print "Detected device", device_name, " with available space", avail_space option = raw_input("Proceed? (y/n)") if option == 'y': print "Creating swap space on", device_name t = device_name+"/swap" avail_space = int(avail_space) if avail_space > 1000: print "Too much space available, using 1000" avail_space = 1000 avail_space = str(avail_space) cmd_str = "dd if=/dev/zero of="+t+" bs=1K count="+avail_space ret_val = os.system(cmd_str) time.sleep(4) #Give command some time ret_val = os.system("mkswap "+t+" "+avail_space) time.sleep(4) ret_val = os.system("swapon "+t) time.sleep(4) #print "Done creating cache/swap space ", t return t, avail_space, 1 elif option == 'n': print "Not selected. Exiting." sys.exit(0) def removeCache(): """Remove cache from attached device(s)""" device_name, avail_space = doPreprocessing() device_name = device_name+"/swap" print "Removing cache/swap space from ", device_name ret_val = os.system("swapoff "+device_name) time.sleep(4) ret_val = os.system("rm "+device_name) time.sleep(4) print "Done removing "+device_name if __name__ == '__main__': if getpass.getuser() != 'root': print "Error (red.py): Need to be root to do this." sys.exit(0) optlist, lst = getopt.getopt(sys.argv[1:], 'mrh') for opt in optlist: if opt[0] == '-h': printUsage() if opt[0] == '-m': dev_swap_name, avail_space, flag = makeCache() if opt[0] == '-r': removeCache()