问题
sorry if my english is so bad. i wanna ask about executing "passwd" command from Java (i use Netbeans IDE & JSCH Library)
This is my code
String username = txtusername.getText();
String password = txtpassword.getText();
String ip = txtIP.getText();
int port = 22;
Session session = null;
Session session2=null;
ChannelExec channel = null;
Channel channel2 = null;
StringBuffer result = new StringBuffer();
try
{
JSch shell = new JSch();
session = shell.getSession(username, ip, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect(3000);
channel = (ChannelExec) session.openChannel("exec");
((ChannelExec)channel).setCommand("passwd");
channel.setInputStream(null);
channel.setOutputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
OutputStream out=channel.getOutputStream();
PrintStream char_to_send_to_channel = new PrintStream(out,true);
BufferedReader out_from_channel=new BufferedReader(new InputStreamReader(in));
char_to_send_to_channel.println();
String line;
channel.connect();
JOptionPane.showMessageDialog(null,"Channel opened!" +"\n");
// Process p = Runtime.getRuntime().exec("passwd");
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0) {
break;
}
}
}
} catch (IOException ex) {
Logger.getLogger(connect.class.getName()).log(Level.SEVERE, null, ex);
} catch(JSchException | HeadlessException e){
JOptionPane.showMessageDialog(null, e);
}
}
The problem is, my output is just like
(current) UNIX password:
And if i type / input current UNIX password,nothing happened. I want change Ubuntu Server account password, its installed on my VMWare. And i run this program on my original OS. Simply, i want my output interactive (input and output just like output from linux command 'passwd')
Whats wrong with my code? :( Need Suggestions
回答1:
passwd
will by default read directly from the pty instead of stdin. You will need to pass the --stdin
option to passwd
.
For more information, see the answers to this question: Using the passwd command from within a shell script.
来源:https://stackoverflow.com/questions/14846514/change-unix-password-with-java