Newbie - Running Commands Interactively

C

Chris Bingham

Hi everyone,

I'm new to python, and I was wondering if anyone could help me with a
couple of problems I've hit please?

I'm trying to write a wrapper script for the passwd command, so that we
can log everytime someone uses it, which options they used with it and
if they succeeded or cancelled the command. The idea is that it'll look
to the user like they're running the original system passwd command,
but actually they're running it though this script.

At the moment my script looks like this:


#!/usr/bin/env python

import os
import coLog
import sys

result='failed'
if len(sys.argv) > 1:
cmd="passwd"
for arg in sys.argv[1:]:
cmd=cmd + " " + arg
else:
cmd="passwd"

cmdRun=os.popen(cmd)

result=str(cmdRun.readlines())
print result
subResult=result.find('successfully')
print subResult

if subResult != '-1':
coLog.add('Passwd', 'The user successfully executed the following
command: ' + cmd, 'CLI')
else:
coLog.add('Passwd', 'The user executed the following command, but
it failed or was cancelled: ' + cmd, 'CLI')

# EOF


The 'coLog' module that get's imported at the start is 1 I wrote to do
the actual logging, so that i can easily reuse the code in other
scripts.

I've got 2 problems with it that i just haven't been able to fix;

1. Firstly, if I use os.popen to execute the command, the first & last
lines of the command's output don't get displayed, i can get them later
from the 'cmdRun' variable and print them, but then it doens't look
like the original passwd command. I've found that using os.system
instead fixes this issue, but then pressing ctrl-c during the command
causes the shell ure in to go cooco-lala on u! :) os.popen works
correctly with ctrl-c. I also tried os.popen2, but this caused the
passwd command to go nuts!

2. Secondly, if ctrl-c is pressed the script gets killed along with the
command, so it doens't log cancelled commands. I've tried using various
variations of 'try, except', including catching the KeyboardInterrupt
and catching all exceptions, but nothing seemed to work!

I've been struggling with these 2 issues for the last week, and so far
no joy. If anyone has any idea how to fix them I'd really appreciate
the help! :)

Thanks in advance for any help anybody can give,

Chris
 

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

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top