Jsch ssh登陆
package com.xxxx;
import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Created by xxx on 2017/4/5.
*/
public class JshMain {
public static void main(String args[]){
JSch jsch = new JSch();
try {
// Create and connect session.
Session session = jsch.getSession("root", "192.168.60.225", 22);
session.setPassword("xxxx");
session.setUserInfo(new MyUserInfo());
session.connect();
// Create and connect channel.
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("ls");
channel.setInputStream(null);
BufferedReader input = new BufferedReader(new InputStreamReader(channel
.getInputStream()));
channel.connect();
System.out.println("The remote command is: " + "ls");
// Get the output of remote command.
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
// Get the return code only after the channel is closed.
//if (channel.isClosed()) {
// returnCode = channel.getExitStatus();
//}
// Disconnect the channel and session.
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyUserInfo implements UserInfo {
private String password;
private String passphrase;
@Override
public String getPassphrase() {
System.out.println("MyUserInfo.getPassphrase()");
return null;
}
@Override
public String getPassword() {
System.out.println("MyUserInfo.getPassword()");
return null;
}
@Override
public boolean promptPassphrase(final String arg0) {
System.out.println("MyUserInfo.promptPassphrase()");
System.out.println(arg0);
return false;
}
@Override
public boolean promptPassword(final String arg0) {
System.out.println("MyUserInfo.promptPassword()");
System.out.println(arg0);
return false;
}
//本方法是一个关键的问题,返回true就可以
@Override
public boolean promptYesNo(final String arg0) {
System.out.println("MyUserInfo.promptYesNo()");
System.out.println(arg0);
if (arg0.contains("The authenticity of host")) {
return true;
}
return false;
}
@Override
public void showMessage(final String arg0) {
System.out.println("MyUserInfo.showMessage()");
}
}
无密码登陆
jsch = new JSch();
try {
session = jsch.getSession("admin", host, 22);
String privateKey = "~/.ssh/id_rsa";
jsch.addIdentity(privateKey);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
} catch (Exception e){
//log.error("",e);
baseResult.setData(e);
return baseResult;
}