Calling JMX MBean method from a shell script

Dougnukem picture Dougnukem · Nov 17, 2009 · Viewed 131.8k times · Source

Are there any libraries that would allow me to call a JMX MBean method from a shell script. We expose some operations/admin commands through JMX, and we could have our admins use JConsole, or VisualVM, but some tasks are better left to automation. In that automation we'd like to be able to call a JMX MBean method on our running server, preferably from a shell script.

Answer

Dougnukem picture Dougnukem · Nov 17, 2009

The following command line JMX utilities are available:

  1. jmxterm - seems to be the most fully featured utility.
  2. cmdline-jmxclient - used in the WebArchive project seems very bare bones (and no development since 2006 it looks like)
  3. Groovy script and JMX - provides some really powerful JMX functionality but requires groovy and other library setup.
  4. JManage command line functionality - (downside is that it requires a running JManage server to proxy commands through)

Groovy JMX Example:

import java.lang.management.*
import javax.management.ObjectName
import javax.management.remote.JMXConnectorFactory as JmxFactory
import javax.management.remote.JMXServiceURL as JmxUrl

def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:9003/jmxrmi'
String beanName = "com.webwars.gameplatform.data:type=udmdataloadsystem,id=0"
def server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection
def dataSystem = new GroovyMBean(server, beanName)

println "Connected to:\n$dataSystem\n"

println "Executing jmxForceRefresh()"
dataSystem.jmxForceRefresh();

cmdline-jmxclient example:

If you have an

  • MBean: com.company.data:type=datasystem,id=0

With an Operation called:

  • jmxForceRefresh()

Then you can write a simple bash script (assuming you download cmdline-jmxclient-0.10.3.jar and put in the same directory as your script):

#!/bin/bash

cmdLineJMXJar=./cmdline-jmxclient-0.10.3.jar
user=yourUser
password=yourPassword
jmxHost=localhost
port=9003

#No User and password so pass '-'
echo "Available Operations for com.company.data:type=datasystem,id=0"
java -jar ${cmdLineJMXJar} ${user}:${password} ${jmxHost}:${port} com.company.data:type=datasystem,id=0

echo "Executing XML update..."
java -jar ${cmdLineJMXJar} - ${jmxHost}:${port} com.company.data:type=datasystem,id=0 jmxForceRefresh