Sunday, April 25, 2010

Python: SendKeys

Problem Statement:
Last week I faced an interesting problem t work. I was using runas DOS command using a Python script. After running the command, it asks you to enter a password on the cmd prompt. Now how do I do it with Python? Obvious answer was using subprocess functions (Popen and communicate). But have you tried something unconvenctional?

Solution:
SendKeys module could be the answer. Lets see how!
SendKeys is not available in Python 2.5 with default installation. One has to use that module by installing it.

Binary for the same could be obatainable from:

Here's the code that worked for me:

import SendKeys
import subprocess

password = "PASSWORD"
command = "runas /user:USERNAME Notepad.exe"
subprocess.Popen(command)

send = """
%s{ENTER}
""" % (password)

SendKeys.SendKeys(send)


For more better examples you could refer to:

No comments: