Normally, one shuts down Apache Tomcat by running its shutdown.sh script (or batch file). In some cases, such as when Tomcat’s web container is hosting a web app that does some crazy things with multi-threading, running shutdown.sh gracefully shuts down some parts of Tomcat (as I can see more available memory returning to the system), but the Tomcat process keeps running.
I’m trying to write a simple Python script that:
- Calls
shutdown.sh - Runs
ps -aef | grep tomcatto find any process with Tomcat referenced - If applicable, kills the process with
kill -9 <PID>
Here’s what I’ve got so far (as a prototype – I’m brand new to 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()
I’m struggling with the middle part – with obtaining the grep results, checking to see if their size is greater than 1 (since grep always returns a reference to itself, at least 1 result will always be returned, methinks), and then parsing that returned PID and passing it into the killPidCmd. Thanks in advance!
you need to replace
grepResults = subprocess.call([grepCmd], shell=true)withgrepResults = subprocess.check_output([grepCmd], shell=true)if you want to save the results of the command in grepResults. Then you can use split to convert that to an array and the second element of the array will be the pid:pid = int(grepResults.split()[1])'That will only kill the first process however. It doesn’t kill all processes if more then one are open. In order to do that you would have to write: