1

Basically I wanted to start a daemon in the background that will still prompt the user in the console for a password. I created this with pexpect, but when this program ends it kills the daemon since it is a child process. So obviously pexpect isn't going to work for this. Does any body know of a way to do this?

#!/usr/bin/env python
import pexpect
import getpass
child = pexpect.spawn('python daemon.py &')
child.expect_exact('Password:')

passwd = getpass.getpass()

child.sendline(passwd)

index = child.expect_exact('Started Successfully')
print index
gaucho
  • 55
  • 5
  • Im pretty sure you cant force your prograa not to close ... and so the user can just close your program to circumvent ... – Joran Beasley Sep 28 '12 at 22:51
  • well I'm not worried if a user explicitly closes the daemon. What I am trying to do is start a background process where a user can enter a one time passphrase at the start of the daemon. – gaucho Sep 28 '12 at 22:54
  • 2
    Had you considered using os.fork() and then run the daemon module? – Dany Sep 28 '12 at 22:55
  • yea, but I didn't know how to pass the password to the daemon. Have to keep the password safe i.e. not storing on the hdd and not showing it on the screen. – gaucho Sep 28 '12 at 23:00
  • I could help you if it was windows ... :/ – Joran Beasley Sep 28 '12 at 23:02
  • http://stackoverflow.com/questions/2540460/how-can-i-tell-if-a-given-login-exists-in-my-linux-box-using-python this may be of help ... – Joran Beasley Sep 28 '12 at 23:04
  • daemon process doesn't have controlling terminal and STDIN is bind to /dev/null, and you can not feed it passwords. – Ted Shaw Sep 29 '12 at 04:54

2 Answers2

3

pexpect has a method close(self, force=True) which closes its connection to the child process.

According to the documentation, the child pocess is terminated if force=True so

child.close(force=False)

should disconnect, but leave the application running.

Darian Lewin
  • 172
  • 1
  • 9
1

Dany suggested, "Had you considered using os.fork() and then run the daemon module?"

Your answer was "yea, but I didn't know how to pass the password to the daemon. Have to keep the password safe i.e. not storing on the hdd and not showing it on the screen."

But you don't have to do anything to pass the password to the daemon. After fork, it's still accessible. For example:

passwd = getpass.getpass()
pid = os.fork()
if pid:
  print 'Parent thinks passwd is', passwd
else:
  print 'Child thinks passwd is', passwd

So, read the password in the parent, then fork the daemon; it already has the password, so it doesn't need a tty for anything. Problem solved.

abarnert
  • 354,177
  • 51
  • 601
  • 671