0

My question is were do I enter the password and were do I enter the command. I am obviously just a hobbyist when it comes to java and programming in general but would greatly appreciate an answer of a link to were I can find more help. If not interested in helping me then sorry for wasting your time and have a nice day, peace.

/*
 * This in not my own code it was wrote by kato2 on stack overflow
 * https://stackoverflow.com/questions/18708087/how-to-execute-bash-command-with-sudo-privileges-in-java/39290245
 */

package com.bart_simp.privileges;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;

public class Privileges {
    public static void main(String[] args) {
        try {
            Process pb = new ProcessBuilder("gedit").start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static boolean runWithPrivileges() {
        InputStreamReader input;
        OutputStreamWriter output;
    
        try {
            //Create the process and start it.
            Process pb = new ProcessBuilder(new String[]{"/bin/bash", "-c", "/usr/bin/sudo -S /bin/cat /etc/sudoers 2>&1"}).start();
            output = new OutputStreamWriter(pb.getOutputStream());
            input = new InputStreamReader(pb.getInputStream());
    
            int bytes, tryies = 0;
            char buffer[] = new char[1024];
            while ((bytes = input.read(buffer, 0, 1024)) != -1) {
                if(bytes == 0)
                    continue;
                //Output the data to console, for debug purposes
                String data = String.valueOf(buffer, 0, bytes);
                System.out.println(data);
                // Check for password request
                if (data.contains("[sudo] password")) {
                    // Here you can request the password to user using JOPtionPane or System.console().readPassword();
                    // I'm just hard coding the password, but in real it's not good.
                    char password[] = new char[]{'t','e','s','t'};
                    output.write(password);
                    output.write('\n');
                    output.flush();
                    // erase password data, to avoid security issues.
                    Arrays.fill(password, '\0');
                    tryies++;
                }
            }
    
            return tryies < 3;
        } catch (IOException ex) {
        }
    
        return false;
    }
}

0 Answers0