在Linux系统下用java执行系统命令实例讲解

<

div id=”content” contentScore=”2195″>在Linux系统下用java执行系统命令例子:

要根据你的系统写一个同的脚.因为不同的系统在创建用户时交互命令不同,比如\r
<代表输入\r
>代表终端输出:

#useradd username<
linux下就行了.只要从WEB得到username,
然后调用Runtime.getRuntime().exec(“useradd “+username);
就可以.

#passwd username<
#>palese input new passwd://不一定象我这样的提示.
#1234567<
#>确认提示
#<1234567
有的系统这时就OK了,有的还要什么fullname什么的.你要知道你的系统的过程.
然后我们来编程:

Process p1 = Runtime.getRuntime().exec(“useradd “+username);
//不要交互
Process p2 = Runtime.getRuntime().exec(“passwod “+username);
//这个过程要交互
BufferedReader in = new Buffered(new InputStreamReader(p2.getInputStream()));

OutputStreamWriter out = new OutputStreamWriter (p2.getOutputStream());
String line=””;
while((line = in.readLine()) != null)
{
if(-1 !=line.indexOf(“等待输入密码的提示”))
out.print(passwd+”\r\n”);
if(-1 !=line.indexOf(“等待再次输入密码的提示”))
out.print(passwd+”\r\n”);
if(-1 !=line.indexOf(“成功提示”))
break;
}

in.close();
out.close();
这样就用JAVA程序执行了一个系统命令

public void CmdExec(String[] cmdline) {
        try {
            String line;
            Process p = null;
            if (p != null) {
                p.destroy();
                p = null;
            }
          
            p = Runtime.getRuntime().exec(cmdline);
            BufferedReader input = new BufferedReader(new InputStreamReader(p
                    .getInputStream()));
            line = input.readLine();
            while (line != null) {
                line = input.readLine();
                System.out.println(line);
            }
            input.close();
            p.waitFor();
            int ret = p.exitValue();
      ¼/div>