0

shutdown.sh通常,通过运行其脚本(或批处理文件)来关闭 Apache Tomcat 。在某些情况下,例如当 Tomcat 的 Web 容器托管一个使用多线程执行一些疯狂操作的 Web 应用程序时,shutdown.sh优雅地运行会关闭Tomcat 的某些部分(因为我可以看到更多可用内存返回到系统),但是 Tomcat进程继续运行。

我正在尝试编写一个简单的 Python 脚本:

  1. 来电shutdown.sh
  2. 运行ps -aef | grep tomcat以查找引用了 Tomcat 的任何进程
  3. 如果适用,终止进程kill -9 <PID>

这是我到目前为止所得到的(作为原型 - 我是 Python BTW 的新手):

#!/usr/bin/python

# Imports
import sys
import subprocess

# Load from imported module.
if __init__ == "__main__":
    main()

# Main entry point.
def main():
    # Shutdown Tomcat
    shutdownCmd = "sh ${TOMCAT_HOME}/bin/shutdown.sh"
    subprocess.call([shutdownCmd], shell=true)

    # Check for PID
    grepCmd = "ps -aef | grep tomcat"
    grepResults = subprocess.call([grepCmd], shell=true)

    if(grepResult.length > 1):
        # Get PID and kill it.
        pid = ???
        killPidCmd = "kill -9 $pid"
        subprocess.call([killPidCmd], shell=true)

    # Exit.
    sys.exit()

我在中间部分苦苦挣扎 - 获取grep结果,检查它们的大小是否大于 1(因为grep总是返回对自身的引用,所以总是返回至少 1 个结果,我认为),然后解析返回的PID 并将其传递到killPidCmd. 提前致谢!

4

3 回答 3

1

You can add "c" to ps so that only the command and not the arguments are printed. This would stop grab from matching its self.

I'm not sure if tomcat shows up as a java application though, so this may not work.

PS: Got this from googling: "grep includes self" and the first hit had that solution.

EDIT: My bad! OK something like this then?

p = subprocess.Popen(["ps caux | grep tomcat"], shell=True,stdout=subprocess.PIPE)
out, err = p.communicate()
out.split()[1] #<-- checkout the contents of this variable, it'll have your pid!

Basically "out" will have the program output as a string that you can read/manipulate

于 2012-10-02T02:27:12.770 回答
1

如果要将命令的结果保存在 grepResults 中,则需要替换grepResults = subprocess.call([grepCmd], shell=true)为。grepResults = subprocess.check_output([grepCmd], shell=true)然后您可以使用 split 将其转换为数组,数组的第二个元素将是 pid:pid = int(grepResults.split()[1])'

然而,这只会杀死第一个进程。如果打开的进程不止一个,它不会杀死所有进程。为此,您必须编写:

grepResults = subprocess.check_output([grepCmd], shell=true).split()
for i in range(1, len(grepResults), 9):
  pid = grepResults[i]
  killPidCmd = "kill -9 " + pid
  subprocess.call([killPidCmd], shell=true)
于 2012-10-02T02:44:05.237 回答
0

不需要创建子进程来运行ps和字符串匹配输出。grepPython 具有出色的字符串处理功能,并且 Linux 在 /proc 中公开了所有需要的信息。procfs mount 是命令行实用程序获取此信息的地方。还不如直接上源码。

import os

SIGTERM = 15

def pidof(image):
    matching_proc_images = []
    for pid in [dir for dir in os.listdir('/proc') if dir.isdigit()]:
        lines = open('/proc/%s/status' % pid, 'r').readlines()
        for line in lines:
            if line.startswith('Name:'):
                name = line.split(':', 1)[1].strip()
                if name == image:
                    matching_proc_images.append(int(pid))

    return matching_proc_images


for pid in pidof('tomcat'): os.kill(pid, SIGTERM)
于 2012-10-02T03:36:42.813 回答