Posted By

bcmoney on 08/17/12


Tagged

system commands


Versions (?)

ExecuteSystemCommand.java


 / Published in: Java
 

WARNING: Don't use this one lightly, you can run just about any command the JVM has access to and could corrupt data or bring your system crashing to a halt. Certainly do not recommend putting this behind a user-accessible front-end such as a Web Form, Servlet or GUI control without intense scrutiny, validation and filtering of the inputs.

  1. import java.io.*;
  2.  
  3. /**
  4.  * ExecuteSystemCommand.java
  5.  * Runs any command from the Operating System command-line.
  6.  */
  7.  
  8. public class ExecuteSystemCommand {
  9.  
  10. public void ExecuteSystemCommand() {
  11.  
  12. }
  13.  
  14. public String run(String cmdLine) {
  15. String line;
  16. String output = "";
  17. try {
  18. Process p = Runtime.getRuntime().exec(cmdLine);
  19. (new InputStreamReader(p.getInputStream()));
  20. while ((line = input.readLine()) != null) {
  21. output += (line + '\n');
  22. }
  23. input.close();
  24. }
  25. catch (Exception ex) {
  26. ex.printStackTrace();
  27. }
  28. return output;
  29. }
  30.  
  31. public static void main(String[] args) {
  32. ExecuteSystemCommand cmd = new ExecuteSystemCommand();
  33. //CAREFUL HERE!!!!!!!!!!!
  34. System.out.println(cmd.run("ls -a"));
  35. }
  36. }

Report this snippet  

You need to login to post a comment.