4

Executing shell commands through beanshell in jmeter. I want to execute shell commands in beanshell preprocessor in jmeter

Can any one tell how to do so.

user1788294
  • 1,823
  • 4
  • 24
  • 30

2 Answers2

8

Beanshell is JAVA (scripting language). Below statement should help.

Runtime.getRuntime().exec("COMMAND");
vins
  • 15,030
  • 3
  • 36
  • 47
2

Based on @vins answer I cloud create my ping test to verify my email server is available.

Additionally if you want to log the output of the Runtime.getRuntime().exec("COMMAND"); use something similar to this in your jmeter BeanShell Sampler:

// ********
// Ping the email server to verify it's accessible from the execution server
//
// Preconditions:
// custom variable is available named "emailServer" which contains the IP-Adress of the machine to ping
//
// ********

log.info(Thread.currentThread().getName()+": "+SampleLabel+": Ping email server: " + vars.get("emailServer"));

// Select the ping command depending on your machine type windows or Unix machine. 
//String command = "ping -n 2 " + vars.get("emailServer");    // for windows
String command = "ping -c2 " + vars.get("emailServer");    // for Unix

// Print the generated ping command
log.info(command);

// Create a process object and let this object execute the ping command
Process p = Runtime.getRuntime().exec(command);
p.waitFor();

log.info("Execution complete.");

// Read the output of the ping command and log it
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder logCommandOutput = new StringBuilder();
String line;
while( (line = in.readLine()) != null) {
  logCommandOutput.append(line);
}
in.close();
log.info("Output: " + logCommandOutput.toString());
Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
  • @Dev I've added comments in the answer above what the code does. If you need more specific information for a certain line, let me know. – Bruno Bieri Feb 23 '18 at 07:59
  • thanks. I was trying to understand from the `Process` Object part. Why do we have to take it as a process and not just into a string. Also how does `BufferReader` work here. Do we need `StringBuilder,` can we print the output without it ? – sdgd Feb 23 '18 at 09:55
  • The `Process` I took to be able to show the output in the log. I used this script in an other environment where I wanted to have the output logged. The `BufferReader` we need to actually get the output from the process and the `StringBuilder` is just convenient. I'm sure the whole thing can be reached in a simpler way. – Bruno Bieri Feb 23 '18 at 10:05
  • Thanks for the details Bruno! – sdgd Feb 23 '18 at 10:27
  • Adding the logging helped me! – Vikas Apr 22 '20 at 08:46