Skip to content
Advertisement

Command is Not Interpreting in Java [closed]

I have this block;

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("bash -c "mkdir .typo && mkdir .typo/lib && mkdir src/ && mkdir bin/ && ln -sFf .typo/lib lib && mkdir .typo/runtime && touch src/main.typo && echo "@include !mainnndef main(str[255] args) {n    std:out("Hello, world!");nn    return 0;n}n" >> src/main.typo"");

try {
    process.waitFor();
} catch (InterruptedException interruptedException) {
    System.exit(130);
}

And when I execute it, nothing happens. It sometimes happens but mostly it doesn’t works. I also checked file system and there is nothing different too.

( InterruptedException is imported with import java.lang.InterruptedException. )

I tried and error is;

.typo: -c: line 0: unexpected EOF while looking for matching `"'
.typo: -c: line 1: syntax error: unexpected end of file

Advertisement

Answer

In line with OWASP, I made this to help in making commands more readable and also retrieving their output (once executed).

public class SafeShellExecution {

    
    public String Execute(String[] command) {
        
        StringBuilder strAppend = new StringBuilder();
        
        try {
                String line;
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((line = in.readLine()) != null) {
                    strAppend.append(line);
                }
                in.close();
        } catch (IOException ex) {
            Logging.LogException(ex);
        }
        
        return strAppend.toString();
    }

}

And then define the command cleanly:

    public static final String[] GetIPAddress = {
        "/bin/sh",
        "-c",
        "ifconfig | grep -v '127.0.0.' | grep -i 'inet ' | awk {' print $2 '} | paste -sd ','"
    };

And then execute:

SafeShellExecution.Execute(GetIPAddress);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement