diary | | | geek interests | | | publications | | | projects | | | web |
2/03/2006 11:05:00 AM |
So today I had to write a quick script on Darwin(i.e. MacOS X) that was to run a command line app and interact with it. Basically what would happen is that the command line would run and it would prompt the user to enter a password. At first the viscious hack involved writing a dead simple C extension to python that simluated a key press (i.e as if a human being really hit the key on a keyboard) -- I would've liked to just use python, but the ioctl module was not available for the platform. The python extension wrapper is ugly, so I'll just show you a command line version of what I did.
Then things got weird when the password prompt showed up arbitrary number of times depending on the argument used for the command line app. So I needed a way to read in from the terminal and only type the password when it was explicitly asked for. At first I just used popen to get access to the stdin, stdout, stderr to see if I can read the prompt in, but it seemed like the command line was writing directly to the terminal... =( So I essentially had to find a way to somehow create a terminal-like environment, run the command line in that and intercept the output it's piping to the terminal. After some asking around and googling I noticed that the pty module had its own fork function that forked a child process inside a pseudo-terminal which it returned the file descriptor of! So the hack came out as such:
There you have it. Just thought I'd blog about it, since I couldn't find anything immediately on the net... So if you want to interact with terminal apps by reading its output and typing in some input, this should give you a good start. Hope that helps! |
Want some more? Dig in to the archive for past entries.