当前位置: 技术问答>linux和unix
用java程序修改unix下用户的口令
来源: 互联网 发布时间:2016-01-11
本文导语: 我用了以下代码去修改用户的口令,但只修改为空,测试时,发现使用命令,系统没有返回New password或Re-enter new password字符,因此没有办法传入实际的口令 代码如下: public boolean chgPassword ( String accountname , String...
我用了以下代码去修改用户的口令,但只修改为空,测试时,发现使用命令,系统没有返回New password或Re-enter new password字符,因此没有办法传入实际的口令
代码如下:
public boolean chgPassword ( String accountname , String password )
{
String line = null ;
boolean result = false ;
Process Process = null ;
try {
Process = Runtime.getRuntime ().exec ( "passwd " + accountname ) ;
BufferedReader in = new BufferedReader ( new InputStreamReader ( Process.getInputStream () ) ) ;
OutputStreamWriter out = new OutputStreamWriter ( Process.getOutputStream () ) ;
while ( ( line = in.readLine () ) != null ) {
if ( line.indexOf ( "New password" ) != -1 ) {
out.write ( "passwd " + password ) ;
out.flush () ;
} else if ( line.indexOf ( "Re-enter new password" ) != -1 ) {
out.write ( "passwd" + password ) ;
out.flush () ;
} else if ( line.indexOf ( "Passwd successfully changed" ) != -1 ) {
result = true ;
out.close () ;
in.close () ;
break ;
}
out = null ;
in = null ;
Process.destroy () ;
Process = null ;
}
}
catch ( Exception ex ) {
System.out.println ( "create user occur Exception:" + ex.getMessage () ) ;
}
return result ;
}
代码如下:
public boolean chgPassword ( String accountname , String password )
{
String line = null ;
boolean result = false ;
Process Process = null ;
try {
Process = Runtime.getRuntime ().exec ( "passwd " + accountname ) ;
BufferedReader in = new BufferedReader ( new InputStreamReader ( Process.getInputStream () ) ) ;
OutputStreamWriter out = new OutputStreamWriter ( Process.getOutputStream () ) ;
while ( ( line = in.readLine () ) != null ) {
if ( line.indexOf ( "New password" ) != -1 ) {
out.write ( "passwd " + password ) ;
out.flush () ;
} else if ( line.indexOf ( "Re-enter new password" ) != -1 ) {
out.write ( "passwd" + password ) ;
out.flush () ;
} else if ( line.indexOf ( "Passwd successfully changed" ) != -1 ) {
result = true ;
out.close () ;
in.close () ;
break ;
}
out = null ;
in = null ;
Process.destroy () ;
Process = null ;
}
}
catch ( Exception ex ) {
System.out.println ( "create user occur Exception:" + ex.getMessage () ) ;
}
return result ;
}
|
shell可以这么写
echo "$NEWPASSWORD" | passwd --stdin "$username"
echo "$NEWPASSWORD" | passwd --stdin "$username"