关于通过Java向终端发送命令,我遇到了一个非常令人困惑的问题。我有这样的密码:
Process p = Runtime.getRuntime().exec(new String[]{"useradd", server, "-p", pass, "-d", "/home/dakadocp/servers/" + server, "-s", "/bin/false"});
Runtime.getRuntime().exec(new String[]{"echo", server + ":" + pass, "|", "chpasswd"});第一个命令是"useradd user -p password -d /home/ftp/test/ -s /bin/false“,第二个命令应该是回显式username:new_password chpasswd,第一个命令工作正常,并创建我通过"server”变量定义的用户,但是当我试图执行第二个命令来更改用户时,传递该命令的可能永远不会发生,输出为null,密码也不会更改,但是当我将该命令直接输入到终端时,它的工作非常完美,所以这只是一个Java问题。
我认为问题是在字符“x”中,在我尝试使用一些命令之前,它的行为和这个命令是一样的。我做错什么了?
谢谢。韦利特。
发布于 2014-11-29 00:50:21
|是一个shell特性,需要一个shell才能运行。最简单的解决方法是运行一个shell:
Runtime.getRuntime().exec(new String[] { "sh", "-c", "echo something | chpasswd" });但是,java不仅仅能够编写需要shell或echo的进程。更好的方法是单独运行chpasswd并将字符串写入它:
Process p = Runtime.getRuntime().exec(new String[] { "chpasswd" });
PrintWriter writer = new PrintWriter(p.getOutputStream());
writer.println("foo:bar");
writer.close();https://stackoverflow.com/questions/27197652
复制相似问题