0

I was developing a project in Java to scan the File System and this involves executing dos commands in java with administrative privilege.

I already wrote the program to execute simple dos commands in Java.

public class doscmd {

    public static void main(String args[]) {
        try {
            Process p = Runtime.getRuntime().exec("cmd /C dir");
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }

        } catch (IOException e1) {
        } catch (InterruptedException e2) {
        }

        System.out.println("Done");
    }
}

But as you can see this does not allow to execute elevated commands.

I am developing the project in Netbeans IDE and i was hoping if any of you folks could tell me if there is any code in java to get admin privilege instead of converting the file to .exe and then clicking run as administrator.

Tony Thomas
  • 101
  • 3
  • Possible duplicate of [Run command prompt as Administrator](http://stackoverflow.com/questions/14596599/run-command-prompt-as-administrator) – Idos Jan 15 '16 at 10:36
  • Java doesn't run on DOS, as far as I know. Did you mean Windows console commands? – Harry Johnston Jan 15 '16 at 20:54

2 Answers2

0

try this code, it works for me:

    String command = "cmd /c start cmd.exe";
    Process child = Runtime.getRuntime().exec(command);
    OutputStream output = child.getOutputStream();

    output .write("cd C:/ /r/n".getBytes());
    output .flush();
    output .write("DIR /r/n".getBytes());
    output .close(); 
rdn87
  • 739
  • 5
  • 18
  • This should work.I use this tactic when ping , 100% success. – Tsakiroglou Fotis Jan 15 '16 at 10:42
  • @rdn87 this code works when you open the IDE with administrative privileges but in case i want to deploy my application and make it a runnable jar how do i give that jar admin privileges? – Tony Thomas Jan 15 '16 at 11:20
  • @TonyThomas see this post: http://stackoverflow.com/questions/19037339/run-java-file-as-administrator-with-full-privileges/22110928#22110928 – rdn87 Jan 15 '16 at 11:22
0

Your JVM needs to be running with admin-privileges in order to start a process with admin-privileges.

Build your code and run it as an administrator - every process spawned by your class will have administrator privileges as well.

  • How do i give administrative privileges to my JVM? @TheBigLou13 I know I can externally run the program as an admin but how do I do it within the code itself. – Tony Thomas Jan 15 '16 at 11:25