2016-01-24 152 views
0
private String user = "root", 
      newPassword = "test123"; 

private int port = 22; 

public SSHConnection(String host, String password) { 
    try { 
     JSch jsch = new JSch(); 

     Session session = jsch.getSession(user, host, port); 
     session.setPassword(password); 
     Properties config = new Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     session.setConfig(config); 
     session.connect(); 

     ChannelExec channel = (ChannelExec)session.openChannel("exec"); 
     OutputStream out = channel.getOutputStream(); 
     ((ChannelExec)channel).setErrStream(System.err); 
     channel.connect(); 

     out.write(password.getBytes()); 
     out.flush(); 
     out.write(newPassword.getBytes()); 
     out.flush(); 
     out.write(newPassword.getBytes()); 
     out.flush(); 

     channel.disconnect(); 
     session.disconnect(); 
    } 
    catch(Exception e) { 
     e.printStackTrace(); 
    } 
} 

我被要求在第一次登录服务器时更改密码。我正在尝试使用JSch来做到这一点,但我不知道该如何实现。据我了解,我可以不使用任何命令,我被迫做任何事情之前更改密码,所以我不能用Java SSH在登录时更改密码

(echo old_password; echo new_password; echo new_password) | passwd username 
+0

'passwd'从tty获取输入,而不是从stdin输入。 – EJP

+0

什么样的更改密码提示是?它是一种工具,像'passwd'吗?或者它是一个内置的SSH“更改密码”请求? –

+0

这是您输入当前登录详细信息后得到的内容。 “您需要立即更改密码(root执行)”,并且您被要求输入“(当前)UNIX密码”并且重复两次新密码 – user2821023

回答

0

我解决我的问题,通过调用channel.setPty(真);

private String user = "root", 
      newPassword = "test123"; 

private int port = 22; 

public SSHConnection(String host, String password) { 
    try { 
     JSch jsch = new JSch(); 

     Session session = jsch.getSession(user, host, port); 
     session.setPassword(password); 
     Properties config = new Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     session.setConfig(config); 
     session.connect(); 

     ChannelExec channel = (ChannelExec)session.openChannel("exec"); 
     OutputStream out = channel.getOutputStream(); 

     ((ChannelExec)channel).setErrStream(System.err); 
     channel.setPty(true); 
     channel.connect(); 

     out.write((password + "\n").getBytes()); 
     out.flush(); 
     Thread.sleep(1000); 

     out.write((newPassword + "\n").getBytes()); 
     out.flush(); 
     Thread.sleep(1000); 

     out.write((newPassword + "\n").getBytes()); 
     out.flush(); 
     Thread.sleep(1000); 

     channel.disconnect(); 
     session.disconnect(); 
    } 
    catch(Exception e) { 
     e.printStackTrace(); 
    } 
} 

我每个输入的一致性前加入睡觉,通常你会想要进入每个密码之前必须等待输出,但对于我的用途,这将做。

+1

您是否介意在答案中明确指出通过调用'setPty'解决了这个问题? –