设为首页 加入收藏

TOP

在Linux系统下用java执行系统命令实例讲解
2014-11-23 22:55:06 来源: 作者: 【 】 浏览:9
Tags:Linux 系统 java 执行 命令 实例 讲解

在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();
System.out.println(ret);
} catch (Exception err) {
err.printStackTrace();
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux内核发展方向深入分析 下一篇Linux内核编译清单详解

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: