JSch:如何保持会话处于活动状态
2022-09-02 09:46:58
我正在使用SSH编写用于静态路由管理的Java GUI程序。我的代码如下:
import com.jcraft.jsch.*;
import java.io.*;
public class Konsep {
String status;
static String username;
static String hostname;
String inputcommand;
String output;
static Session session;
JSch jsch = new JSch();
public String status(String stringstatus) {
stringstatus = status;
return stringstatus;
}
public String InputCommand(String inputcommandstatus) {
inputcommandstatus = inputcommand;
return inputcommandstatus;
}
public void connect(String usernamelokal, String hostnamelokal,
String password, int port) {
// JSch jsch=new JSch();
try {
Session sessionlokal = jsch.getSession(usernamelokal,
hostnamelokal, port);
sessionlokal.setPassword(password);
UserInfo ui = new UserInfoku.Infoku();
sessionlokal.setUserInfo(ui);
sessionlokal.setTimeout(0);
sessionlokal.connect();
status = "tersambung \n";
username = usernamelokal;
hostname = hostnamelokal;
session = sessionlokal;
System.out.println(username + " " + hostname);
} catch (Exception e) {
System.out.println(e);
status = "Exception = \n " + e + "\n";
}
}
public void disconnect() {
// JSch jsch=new JSch();
try {
Session sessionlokal = jsch.getSession(username, hostname);
// System.out.println(username +" "+ hostname);
sessionlokal.disconnect();
status = "wes pedhoott \n";
} catch (Exception e) {
System.out.println(e);
status = "Exception = \n " + e + "\n";
}
}
public void addRoute() {
// JSch jsch=new JSch();
System.out.println(username + " " + hostname);
try {
Session sessionlokal = session; // =jsch.getSession(username, hostname);
Channel channel = sessionlokal.openChannel("exec");
((ChannelExec) channel).setCommand(inputcommand);
channel.setInputStream(null);
channel.connect();
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: "
+ channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
} catch (Exception e) {
System.out.println(e);
}
}
}
问题是当我调用 connect 方法,然后调用 addroute 时,程序返回
root 192.168.50.2
root 192.168.50.2
com.jcraft.jsch.JSchException: session is down
我一直在尝试获取会话状态
Session sessionlokal=session; //returns com.jcraft.jsch.JSchException: ChannelExec
或
Session sessionlokal=jsch.getSession(username, hostname); //returns session is down
我也尝试过使用keepalive,但它也不起作用。
我的目的是创建一个会话来托管(登录),同时保持会话打开状态,执行一个或多个命令,也许稍后执行其他命令,然后在不需要时关闭会话(注销)。我一直在这个论坛上搜索,我发现了这个问题,但代码是创建一个方法来定义一个命令,首先执行,然后创建会话,调用命令的方法并关闭会话。
关于如何做我上面提到的任何想法?