Nieuws:

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

Auteur Topic: [opgelost] automatische start python script  (gelezen 2217 keer)

Offline kilian

  • Lid
[opgelost] automatische start python script
« Gepost op: 2010/08/10, 19:23:47 »
Ik heb volgende code die ik bij iedere start wil laten uitvoeren:
#!/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 = "/media/hdd/Public/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' ,
 'Kilian' ,
 'patrick',
 'kiara',
 'film',
 'public'
 ]

# 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 = [
'/media/hdd/Private/Patrick/lockfile.txt',
'/media/hdd/Private/Kilian/lockfile.txt',
'/media/hdd/Private/Kiara/lockfile.txt',
'/media/hdd/Public/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 = 0
transmissionIdletime = 0
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('halt')
        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

Dit scriptje zou mijn server automatisch moeten doen afsluiten wanneer hij lang genoeg idle is.
Nu heb ik het volgende gedaan
- scriptje naar /etc/init.d gekopieerd
- daar automatisch laten opstarten

Het probleem is echter dat dit een oneindige loop is en dat hierdoor verschilende andere processen (zoals Webmin, Apache) niet meer opstarten. De enige mogelijk is dan om manueel via SSH de processen te starten.
Is er een mogelijkheid om dit toch te laten lopen?
« Laatst bewerkt op: 2010/08/11, 00:21:27 door kilian »

Offline Johan van Dijk

  • Administrator
    • johanvandijk
Re: automatische start python script
« Reactie #1 Gepost op: 2010/08/10, 23:20:02 »
Script weghalen uit /etc/init.d/ en in bijvoorbeeld /root/ zetten.

Vervolgens het script aanroepen vanuit /etc/rc.local, en zet er een & achter.
Dus bijv:
/root/script.py &


Offline kilian

  • Lid
Re: automatische start python script
« Reactie #2 Gepost op: 2010/08/11, 00:21:14 »
Da's weer fantastisch! Bedankt voor de hint!