I am using the following string and Java code to create a user on a Linux box via Java.

...
String x = "/usr/sbin/useradd -g users -s /bin/bash -c 'FIRST M LAST,  STERK,DIV-DIS-OFF,123-456-2913' -p 2342asdfa231rcawef09  -d /home/flast -m flast";

RunCommand(x);
...

However, upon execution it spins a list of the usage of useradd... It has something to do with the spaces in the comment field I think. Anyone have any insight as to a solution to this problem?

public static String RunCommand (String cmd)
        {
        String s = null;
        String results = null;
        try {
        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            // Process p = Runtime.getRuntime().exec("ps -ef");
            Runtime rt = Runtime.getRuntime();
            Process p = rt.exec(cmd);

            BufferedReader stdInput = new BufferedReader(new
                 InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new
                 InputStreamReader(p.getErrorStream()));
            // read the output from the command
            //System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null)
            {
                System.out.println(s);
                results = results + s;
            }
            // read any errors from the attempted command
            //System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null)
            {
                System.out.println(s);
                results = results + s;
            }
            return results.toString();
        }
        catch (IOException e)
        {       
            System.out.println("[RunCommand] - ERROR: " + e.getMessage());
            return e.getMessage();
        }
    }

Recommended Answers

All 2 Replies

Use the array version of the exec method. See the API docs.

Don't forget to close the streams.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.