Nieuws:

Welkom, Gast. Alsjeblieft inloggen of registreren.
Heb je de activerings-mail niet ontvangen?

Auteur Topic: shutdown idle script  (gelezen 2467 keer)

Offline ORbit

  • Lid
    • http://www.mansolein.com
shutdown idle script
« Gepost op: 2011/03/20, 08:39:25 »
Hallo allemaal,

Ik heb nog een oude pc liggen die ik wil gebruiken als nas en torrentdownloader en eventueel meer in de toekomst. De pc reageert goed op WOL maar word niet goed wakker uit slaap of standby stand (zwart beeld) daarom ben ik op zoek gegaan naar een script die de pc volledig uitzet.

Na wat zoeken kwam ik deze tegen http://forum.ubuntu-nl.org/software-en-configuratie/automatische-start-python-script/ , helemaal perfect lijkt me enige nadeel is dat ie hem in suspend zet en geen shutdown doet. Nu ben ik niet genoeg bekend met scripts om deze aan te passen, kan iemand mij daarmee helpen?



Offline Bloom

  • Lid
Re: shutdown idle script
« Reactie #1 Gepost op: 2011/03/20, 12:35:54 »
Als het om een Gnome desktop gaat, kun je toch gewoon Systeem/Voorkeuren/Energiebeheer gebruiken en daar opgeven dat hij zichzelf moet uitzetten na een bepaalde tijd?

Het script dat je noemde is bedoeld voor een server, lijkt me. Hoewel het script commentaren bevat dat het een suspend-actie zou uitvoeren, staat er op het kritieke moment een os.system("halt")-instructie. Dat is een afsluitbevel. Je kunt het ook vervangen door poweroff (de os.system()-aanroep is overbodig bij Ubuntu).

Offline ORbit

  • Lid
    • http://www.mansolein.com
Re: shutdown idle script
« Reactie #2 Gepost op: 2011/03/28, 07:56:39 »
hoi bloom bedankt voor je antwoord en ik kom er nog op terug maar heb het nu helaas wat te druk om ermee verder te gaan.
Zodra ik meer weet laat ik het hier weten, daar is het te leuk voor!

Re: shutdown idle script
« Reactie #3 Gepost op: 2011/03/28, 09:58:13 »
Ik heb hier nog een scriptje liggen wat ik vroeger eens heb zitten uitzoeken. Geen idee of het nog werkt, ik heb geen zin om af te sluiten nu :).

#!/usr/bin/env python

def main():
    answer = raw_input("Do you really want to shutdown your computer? (Y/n): ")
    if answer in ('y', 'Y', ''):
        import dbus
        bus = dbus.SystemBus()
        bus_object = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer")
        bus_object.Shutdown(dbus_interface="org.freedesktop.Hal.Device.SystemPowerManagement")

if __name__ == "__main__":
    main()

Offline ORbit

  • Lid
    • http://www.mansolein.com
Re: shutdown idle script
« Reactie #4 Gepost op: 2011/04/01, 07:17:22 »
Ja dat klopt dit script was geschreven voor een server, ik probeer liever eerst de Desktop versie zo dat ik hem in de toekomst via 'werkplek op afstand' kan beheren.

De bedoeling is om de pc uit te schakelen, energiebeheer geeft alleen standby of suspend als mogelijkheden en dat kan de hardware van mijn pc niet hebben. Ook is het van belang dat hij niet uit gaat zolang er via het netwerk op de gedeelde mappen gekeken word, toen ik dit script tegen kwam en zag dat er zelfs regels in stonden die kijken of transmission actief download was ik helemaal tevreden.

Het lijkt me sowieso een ideaal script voor vele anderen, tijdens mijn zoektocht naar een dergelijk script ben ik heel veel vragen tegen gekomen in het Nederlands maar ook Engels van mensen die een script willen voor hun NAS, server en zelfs desktop die de pc automatisch uitschakelt om hem maar niet onnodig aan te laten staan en energie te laten verbruiken maar nergens word iets geboden als deze oplossing.

Ik loop alleen nu tegen een ander probleem op, het script is nu aangepast en in de /root/ geplaatst,

#!/usr/bin/python

###########################
# HTPC suspend script     #
# author: Hans van Schoot #
###########################
# TODO list: build in a check for ftp server activity

# The purpose of this script is to suspend the machine if it's idle.
# the script checks:
# - if a lockfile is present (this way the script can be bypassed when needed)
# - if XBMC is running, and if it's playing
# - if there is keyboard or mouse activity
# - if transmission download speed is too low to be keeping the system awake
# - if there are samba shares in use (READ ON FOR THIS!)

# To function properly this script needs a couple things:
# - from apt-get: xprintidle
# - from apt-get: transmissioncli
# - the gnome-power-control script (installed in /usr/bin) from AgenT: http://ubuntuforums.org/showpost.php?p=8309702&postcount=16
# - xbmc web server enabled without a password (can be found in xmbc settings under network)
#     (if you don't need xbmc, you can comment out the xbmc section or put the xbmcDelay on 0)
# - to be able to use "sudo smbstatus" (so rootaccess, or if you run the script on userlevel this can be fixed by adding
#     "your_username ALL=(ALL) NOPASSWD: /usr/bin/smbstatus" visudo (run "sudo visudo" in terminal))

# if you're running a minimal ubuntu install (without a x session, like gnome or kde) you can't use/don't need
# the xprintidle stuff. you can remove this from the script, or just don't install xprintidle and put the xDelay on 0


#############################
# Settings and delay values #
#############################
# the system suspends only if all the different items are idle for a longer time than specified for it
# the values are in minutes, unless you change the sleep command at the start of the loop
sambafileDelay = 30
transmissionDelay = 10
# this is the path to the lockfile you can use.
# to lock the system, just use the touchcommand: "touch /home/media/.suspendlockfile" (or create a starter to it)
# to unlock the system, just use rmcommand "rm /home/media/.suspendlockfile" (or create a starter to it)
lockfilePath = "/home/nas/Openbaar/lockfile.txt"
# logindata for the transmission server (this is the same data you need to enter when contacting the demon through the web interface
transmissionlogin = "server"
transmissionpass = "kilian"
# command to contact the transmission server
transmissionAdress = "transmission-remote -n %s:%s " %(transmissionlogin,transmissionpass)
# minimal download speed required to keep the system awake (in kb/s)
transmissionSpeed = 5.0


##### SAMBACHECK SETTINGS #######
# the script checks the output of sudo smbstatus to see if there are locked files
# (usualy someone downloading or playing media from the system)
# if no locked files are found, it checks if there are folders in use that should keep the system awake
#
# smbimportantlist is a list of strings the sambashare should check if they are in use (for instance a documents folder)
# to find out what to put here:
# 1. connect to the share with another computer
# 2. use "sudo smbstatus" in console
# 3. check for the name of the share, it's printed out under "Service"
#
# makeup of the list is: [ 'muziek' , 'Kilian' , 'patrick', 'kiara', 'film', 'public' ]
smbimportantlist = [
 'muziek' ,
 'videos' ,
 'openbaar',
 'afbeeldingen'
 ]

# this list checks for lockfiles in specified home directories, makeup is the same as the smblist, but with pathnames to possible lockfiles
# add/change (or remove) as many lockfile locations as you like
lockfilelist = [
'/home/nas/Muziek/lockfile.txt',
'/home/nas/Afbeeldingen/lockfile.txt',
'/home/nas/Videos/lockfile.txt',
'/home/nas/Openbaar/lockfile.txt',
]

# change this to False if you want the script to run silent
debugmode = True

### the script starts here
#from os import *
import os
from urllib2 import *
from time import sleep

#xbmcIdletime = 0
sambaIdletime = 1
transmissionIdletime = 1
Lockfile = 0
keeponrunnin = True

# this is the loop that keeps the script running. the sleep command makes it wait one minute
# if you want to increase/decrease the frequencies of the checks, change the sleeptimer.
# keep in mind that this wil change the Delay times for xbmc and samba
while keeponrunnin:
    print "\n !!! Niet dichtdoen!!!\n Dit schermpje moet de pc in slaapstand zetten!\n"
    sleep(60)
     
# counting the number of lockfiles
    Lockfile = 0
    for i in lockfilelist:
        if os.path.exists(i):
            Lockfile += 1

#######################################
# next section is the samba checkpart #
#######################################
    try: sambainfo = os.popen('sudo smbstatus').read()
    except IOError, e:
        if debugmode:
            print "No Sambaserver found, or no sudorights for smbstatus"
        sambaIdletime += 1
    else:
        # first we check for file-locks
        if sambainfo.find('Locked files:\n') >= 0:
            sambaIdletime = 0
            if debugmode:
                print "a locked samba file has been found"
        # if no locked files, strip the info and look for keywords, if found reset idletime
        else:
            sambaIdletime += 1
            sambasplit = sambainfo.split('\n')[4:-4]
            sambasplit.reverse()
            for i in sambasplit:
                if i == '-------------------------------------------------------':
                    break
                for j in smbimportantlist:
                    # check to filter out crashes on empty lines
                    if len(i.split()) >= 1:
                        if i.split()[0].find(j) >= 0:
                            sambaIdletime = 0
                            if debugmode:
                                print "an important samba share is in use"


# this is the check for torrent activity. it checks the last value in the last line
# from the transmission-remote command, which is the downloadspeed in kb/s
    try: transmissioninfo = os.popen(transmissionAdress + "-l").read()
    except IOError, e:
        if debugmode:
            print "transmissioncli not installed"
        transmissionIdletime += 1
    else:
        if transmissioninfo.find('Couldn\'t connect to server') >= 0:
            transmissionIdletime += 1
            if debugmode:
                print "transmission draait niet"
        elif float(transmissioninfo.split()[-1]) >= transmissionSpeed:
                transmissionIdletime = 0
                if debugmode:
                    print "transmission is downloading @ %s kb/s" %(transmissioninfo.split()[-1])
        else:
            transmissionIdletime += 1


# this is the final check to see if the system can suspend.
# uncomment the print statements and run in terminal if you want to debug/test the script
    f = open('/var/www/status.html', 'w')
    if (sambaIdletime+1) >=sambafileDelay and (transmissionIdletime+1) >= transmissionDelay and Lockfile == 0:
        os.system('echo Server sluit af binnen 1 minuut | smbclient -NM PC11 >/dev/null')
    if sambaIdletime >= sambafileDelay and transmissionIdletime >= transmissionDelay and Lockfile == 0:
        if debugmode:
            print "suspend allowed"
        f.write('Systeem inactief: shutdown')
        f.close
        os.system('poweroff')
        sambaIdletime = 0
        transmissionIdletime = 0
    else:
        f.write("<p>system is active, not suspending</p>\n<p>samba is idle for "+str(sambaIdletime)+" minutes</p>\n<p>transmission is idle for "+str(transmissionIdletime)+" minutes</p>\n")
        if debugmode:
            print "system is active, not suspending"
            print "samba is idle for ", sambaIdletime, " minutes"
            print "transmission is idle for ", transmissionIdletime, " minutes"
            if Lockfile == 0:
                print "er is geen lockfile gevonden"
                f.write("<p>Er is geen lockfile gevonden</p>")
            else:
                print "er is/zijn %i lockfile gevonden" %(Lockfile)
                f.write("<p>Er is een lockfile gevonden</p>")
        f.close

ook heb ik zoals beschreven staat in het script het gnome-power-controle script gemaakt en geplaatst in /usr/bin/

#!/bin/bash
#
# gnome-power-control
# Author: AgenT

case $1 in
suspend)
echo Suspending
    dbus-send --print-reply \
        --system \
        --dest=org.freedesktop.DeviceKit.Power \
        /org/freedesktop/DeviceKit/Power \
        org.freedesktop.DeviceKit.Power.Suspend
;;
hibernate)
echo Hibernating
    dbus-send --print-reply \
        --system \
        --dest=org.freedesktop.DeviceKit.Power \
        /org/freedesktop/DeviceKit/Power \
        org.freedesktop.DeviceKit.Power.Hibernate
;;
*)
echo Not supported command: '"'$1'"'
echo Usage: $0 '<suspend|hibernate>'
exit 1
;;
esac

ik zie alleen niet waar dit script opgeroepen word door het eerste script.

Als ik het (eerste) script uitvoer in de terminal sluit de terminal na 1 min maar de pc niet... ???


Offline ORbit

  • Lid
    • http://www.mansolein.com
Re: shutdown idle script
« Reactie #5 Gepost op: 2011/04/01, 07:19:31 »
Citaat
heb hier nog een scriptje liggen wat ik vroeger eens heb zitten uitzoeken. Geen idee of het nog werkt, ik heb geen zin om af te sluiten nu Smiley.

bedankt nunslaughter maar zo te zien is dat een manueel afsluitscriptje

Re: shutdown idle script
« Reactie #6 Gepost op: 2011/04/01, 09:56:32 »
bedankt nunslaughter maar zo te zien is dat een manueel afsluitscriptje

Was ook maar wat ik hier heb liggen, het gaat hem vooral over hoe er afgesloten word. "os.system('poweroff')" is nu niet bepaald de beste manier, daarom dat ik even een voorbeeldje postte. Als ge de vraag om af te sluiten weghaalt, is het wel automatisch.

Offline jmbouma

  • Lid
Re: shutdown idle script
« Reactie #7 Gepost op: 2011/04/01, 16:48:01 »
Ik heb deze een tijd gebruikt voordat ik XP installeerde.
(zip file ff uitpakken).

Greetz.

Offline ORbit

  • Lid
    • http://www.mansolein.com
Re: shutdown idle script
« Reactie #8 Gepost op: 2011/04/09, 08:29:36 »
vandaag eindelijk weer tijd om hiermee verder te gaan, ik heb inmiddels gezien dat het script werkt en zichzelf keurig afsluit na de ingestelde tijd maar de pc blijft aan..

hoe kan ik er nu voor zorgen dat dit script het afsluitcommando van Nunslaughter oproept?