简体   繁体   English

通过Python脚本启动/停止Apache

[英]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. 在运行Python 2.6.6的RHEL 6.7服务器上,我尝试以Python脚本中的非特权用户身份启动和停止Apache Web服务器。

The command I am using is "sudo service httpd " where parameter is "start", "stop" or "status". 我正在使用的命令是“ sudo service httpd”,其中参数是“ start”,“ stop”或“ 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. 更新: sudoers文件包含一行,该行允许我的用户无密码运行这些命令。

Neither code works (with and without .communicate() ). 两种代码都.communicate()带有和不带有.communicate() )。

You should use instead (assuming passwordless sudo for these commands): 您应该改用(假设这些命令使用无密码sudo ):

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 subprocess函数默认情况下不运行Shell,因此该字符串被解释为命令的名称:您应该使用列表在POSIX上传递多个命令行参数
  2. Popen() starts the command and returns immediately without waiting for it to finish ie, it may happen before httpd is started. Popen()启动命令并立即返回,而无需等待命令完成,即可能在httpd启动之前发生。 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). 假设Popen()调用是固定的, .communicate()等待子进程终止,因此它将在httpd启动之后返回(无论它是否成功)。

There are different reasons for that to happen: 1. the user is in sudoers and configured to not insert password. 发生这种情况的原因有很多:1.用户处于sudoers状态,并且配置为不插入密码。

  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 sudo会记住您的密码一段时间(取决于您的系统配置),请参阅: https : //unix.stackexchange.com/questions/37299/how-does-sudo-remember-you-already-entered-roots-password

does it work in a brand new terminal session? 是否可以在全新的终端会话中使用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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