Java‎ > ‎

Exec

Execute operating system (OS) commands

import java.util.Scanner;
import java.io.*;
 
public class test {
    public static void main(String[] args) {       
        try {
            String[] cmd = new String[3];
            cmd[0] = "cmd.exe";
            cmd[1] = "/C";
            cmd[2] = "dir";
            Process p = Runtime.getRuntime().exec(cmd);

            Scanner sc = new Scanner(p.getInputStream());           
            while (sc.hasNext()) System.out.println(sc.nextLine());
            System.out.println("Return Code: " + p.exitValue());
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }
       
       
    }
}


To execute psexec (remote computer command execution in Windows).

import java.util.Scanner;
import java.io.*;
 
public class RWUI {
    public static void main(String[] args) {       
        try {
            String[] cmd = {"cmd.exe", "/c", "start", "/wait", "rwuinstall.bat", "10.0.0.1"};
            Process p = Runtime.getRuntime().exec(cmd);

            try {
                p.waitFor();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
            System.out.println("Return Code: " + p.exitValue());
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Bat file content:

psexec.exe \\%1 -f -c -s C:\bin\WUInstall.exe /search


Comments