App to auto turn off computer if idle for length of time

dave selby dave6502 at googlemail.com
Wed Oct 17 21:08:33 BST 2007


Did a bit of hacking - the following works for me & helps save the planet :)

Cheers

Dave


#!/usr/bin/env python

# Small script to shut down the PC after shutdownMins providing there
has been no mouse / keyboard
# activity, a low load average and a low TCP download rate ... ie
system truely idle

import xf86misc, os, time, tempfile

ethPort = 'eth1'
shutdownMins = 60

debug = False

def loadAverage():
    tempFile = tempfile.mktemp()
    os.system("uptime > " + tempFile)
    f = open(tempFile, 'r')
    uptime = f.read()
    loadAv = float(uptime.split()[8][:-1])
    f.close()
    os.remove(tempFile)
    return loadAv

def netPackets():
    tempFile = tempfile.mktemp()
    os.system("netstat -i > " + tempFile)
    f = open(tempFile, 'r')
    netstat = f.readlines()
    # only interested in TCP downloaded packets via ethPort
    for line in netstat:
        if line[:4] == ethPort: break
    numPackets = int(line.split()[3])
    f.close()
    os.remove(tempFile)
    return numPackets

def main():
    if debug: print 'auto_shutdown is starting up ...'
    # Sleep till X is up & running
    time.sleep(5)
    loadCount = netCount = idleCount = 0
    oldNumPackets = netPackets()
    shutdownCount = shutdownMins / 5

    xg = xf86misc.XF86Server()
    xscreen = xg.getDefaultScreen()
    oldIdle = xscreen.getIdleSeconds()
    while True:

        # Filters out optical mouse jitter
        idleMinCount = 0
        for i in xrange(5):
            time.sleep(60)
            idle = xscreen.getIdleSeconds()
            idleDiff = idle - oldIdle
            oldIdle = idle
            if idleDiff > 59: idleMinCount += 1
        if idleMinCount >= 3: idleCount += 1
        else: idleCount = 0

        loadAv = loadAverage()
        if loadAv < 0.75: loadCount += 1
        else: loadCount = 0

        numPackets = netPackets()
        numPacketsDiff = numPackets - oldNumPackets
        oldNumPackets = numPackets
        if numPacketsDiff < 600: netCount += 1
        else: netCount = 0

	if debug: print 'load count=' + str(loadCount) + '  network count=' +
str(netCount) + '  idle count=' + str(idleCount) +'  shutdown count='
+ str(shutdownCount)

        if loadCount >= shutdownCount and netCount >= shutdownCount
and idleCount >= shutdownCount:
            os.system('/usr/bin/dcop --all-sessions --all-users
ksmserver ksmserver logout 0 2 0 &> /dev/null')
            # Idealy sould be along the lines of .... but no luck & no
time to fix :)
            #computerObject =
dbus.bus.get_object("org.freedesktop.Hal",
u'/org/freedesktop/Hal/devices/computer')
            #computerObject.Shutdown(dbus_interface="org.freedesktop.Hal.Device.SystemPowerManagement")

if __name__ == "__main__":
    main()



More information about the kubuntu-users mailing list