1,105,581 Community Members

Running console command from within Java

Member Avatar
echocoder
Newbie Poster
10 posts since Oct 2007
Reputation Points: -2 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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();
        }
    }
Member Avatar
masijade
Industrious Poster
4,165 posts since Feb 2006
Reputation Points: 1,351 [?]
Q&As Helped to Solve: 510 [?]
Skill Endorsements: 22 [?]
Team Colleague
Featured
 
0
 

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

Member Avatar
thekashyap
Practically a Posting Shark
809 posts since Feb 2007
Reputation Points: 193 [?]
Q&As Helped to Solve: 77 [?]
Skill Endorsements: 0 [?]
 
0
 

Don't forget to close the streams.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: