简体   繁体   中英

Start/Stop Apache via Python script

On a RHEL 6.7 server running Python 2.6.6 I am trying to start and stop the Apache webserver as an unprivileged user in a Python script.

The command I am using is "sudo service httpd " where parameter is "start", "stop" or "status".

p = subprocess.Popen("sudo service httpd start", stdout=subprocess.PIPE, stderr=subprocess.PIPE)

This line alone does not work. Adding a

p.communicate()

lets the commands work as desired. Can somebody tell me why?

UPDATE: The sudoers file contains a line that allows my user to run these commands passwordless.

Neither code works (with and without .communicate() ).

You should use instead (assuming passwordless sudo for these commands):

import subprocess
subprocess.check_call("sudo service httpd start".split())

The reasons:

  1. subprocess functions do not run the shell by default and therefore the string is interpreted as a name of the command: you should use a list to pass multiple command-line arguments on POSIX
  2. Popen() starts the command and returns immediately without waiting for it to finish ie, it may happen before httpd is started. Assuming Popen() call is fixed, .communicate() waits for the child process to terminate and therefore it returns after httpd is started (whether it was successful or not).

There are different reasons for that to happen: 1. the user is in sudoers and configured to not insert password.

  1. sudo remembers your password for some time (depending on your system configuration), see: https://unix.stackexchange.com/questions/37299/how-does-sudo-remember-you-already-entered-roots-password

does it work in a brand new terminal session?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM