package wm.http.jsch;标签:jsch,jSchSession,jschChannel,io,import,public From: https://www.cnblogs.com/game-server/p/16617425.html
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import wm.common.Log;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
public class JSchConnect {
private io.netty.channel.Channel wsChannel;
private OutputStream writer;
private InputStream inputStream;
private Session jSchSession;
private Channel jschChannel;
private boolean init;
public JSchConnect(io.netty.channel.Channel wsChannel) {
this.wsChannel = wsChannel;
}
public void connect(String userName, String password, String host, int port){
// 创建JSch对象
JSch jSch = new JSch();
boolean reulst = false;
try {
// 根据主机账号、ip、端口获取一个Session对象
jSchSession = jSch.getSession(userName, host, port);
// 存放主机密码
jSchSession.setPassword(password);
Properties config = new Properties();
// 去掉首次连接确认
config.put("StrictHostKeyChecking", "no");
jSchSession.setConfig(config);
// 超时连接时间为3秒
jSchSession.setTimeout(1000 * 30);
// 进行连接
jSchSession.connect();
// 获取连接结果
reulst = jSchSession.isConnected();
jschChannel = jSchSession.openChannel("shell");
jschChannel.connect();
writer = jschChannel.getOutputStream();
inputStream = jschChannel.getInputStream();
init = true;
Log.debug("jsch connect result:" + reulst);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close(){
// 关闭jschSesson流
if (jSchSession != null && jSchSession.isConnected()) {
jSchSession.disconnect();
}
// 关闭sftpChannel
if (jschChannel != null && jschChannel.isConnected()) {
jschChannel.disconnect();
}
}
public void read()throws Exception{
int available = inputStream.available();
if (available > 0){
byte[] chars = new byte[available > 1024 ? 1024 : available];
int read = inputStream.read(chars);
String s = new String(chars, "utf-8");
wsChannel.writeAndFlush(new TextWebSocketFrame(s));
}
}
public void write(String s) {
try {
// if (s.equals("\r")){
// s = s+'\n';
// }
writer.write(s.getBytes(StandardCharsets.UTF_8));
writer.flush();
}catch (Exception e){
e.printStackTrace();
}
}
public boolean isInit() {
return init;
}
}