java 里面的开源 ssh lib
jsch 例子
JSch jSch = new JSch();
//设置JSch 的日志,可以看到具体日志信息
JSch.setLogger(new Logger() {
@Override
public boolean isEnabled(int level) {
return true;
}
@Override
public void log(int level, String message) {
System.out.println("logger:" + message);
}
});
com.jcraft.jsch.Session session = jSch.getSession("king", "127.0.0.1");
session.setPassword("123456");
//忽略hostkey 检查
session.setConfig("StrictHostKeyChecking", "no");
//设置需要kerbores 验证 键盘交互 忽略
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.connect(60000);
//开启shell,shell 具有上下文交互,执行命令不会马上退出
ChannelShell shell = (ChannelShell) session.openChannel("shell");
//开始 exec 类似linux bash -c exec 执行完命令马上退出
//ChannelExec exec = (ChannelExec)session.openChannel("exec");
//exec.setCommand("");
shell.setPtyType("dumb");
shell.setPty(true);
shell.connect(60000);
boolean connected = shell.isConnected();
OutputStream outputStream = shell.getOutputStream();
InputStream inputStream = shell.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
//通过流写入命令
outputStream.write("pwd\n cd /home\nls\npwd\n".getBytes());
outputStream.flush();
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
sshj 例子
DefaultConfig defaultConfig = new DefaultConfig();
final SSHClient client = new SSHClient(defaultConfig);
String host = "127.0.0.1";
String user = "king";
String password = "123456";
client.setTimeout(60000);
client.loadKnownHosts();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(host);
try {
client.authPassword(user, password);
final SessionChannel session = (SessionChannel) client.startSession();
session.allocateDefaultPTY();
//这里的session 类似 jsch 里面的exec ,可以直接执行命令。
//session.exec("pwd");
SessionChannel shell = (SessionChannel) session.startShell();
try {
OutputStream outputStream = shell.getOutputStream();
outputStream.write("pwd\n".getBytes());
outputStream.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(shell.getInputStream(), "utf-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
client.disconnect();
}