Java JSch多通道同一会话
我正试图通过单个Java JSch多通道同一会话,java,session,jsch,Java,Session,Jsch,我正试图通过单个jSCH会话打开多个频道 这是我的密码 public class PoolTest { private static Hashtable<String, Session> pool = new Hashtable<>(); /** * @param args * @throws InterruptedException * @throws IOException * @throws JSchEx
jSCH会话打开多个频道
这是我的密码
public class PoolTest {
private static Hashtable<String, Session> pool = new Hashtable<>();
/**
* @param args
* @throws InterruptedException
* @throws IOException
* @throws JSchException
*/
public static void main(String[] args) throws JSchException, IOException, InterruptedException {
PoolTest test = new PoolTest();
test.runCommand("show system");
test.runCommand("show version");
}
private void runCommand(String command) throws JSchException, IOException, InterruptedException{
Session session = createNewSession();
System.out.println(session.isConnected());
Channel channel = session.openChannel("shell");
((ChannelShell) channel).setPtyType("dumb");
channel.connect();
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.connect();
ps.println(command);
ps.close();
InputStream in=channel.getInputStream();
byte[] bt=new byte[1024];
while(true)
{
while(in.available()>0)
{
int i=in.read(bt, 0, 1024);
if(i<0)
break;
String str=new String(bt, 0, i);
//displays the output of the command executed.
System.out.print(str);
}
if(channel.isClosed())
{
break;
}
Thread.sleep(1000);
channel.disconnect();
}
channel.disconnect();
}
private Session createNewSession() throws JSchException{
if(pool.get("10.94.101.235")==null){
System.out.println("creating new session");
JSch jsch = new JSch();
Session session;
session = jsch.getSession("unknown", "10.94.101.235", 22);
session.setPassword("wont_tell");
session.setConfig("StrictHostKeyChecking", "no");
session.setTimeout(60000);
session.connect();
pool.put("10.94.101.235", session);
return session;
}
else
return pool.get("10.94.101.235");
}
}
公共类池测试{
私有静态哈希表池=新哈希表();
/**
*@param args
*@抛出中断异常
*@抛出异常
*@JSchException
*/
公共静态void main(字符串[]args)抛出JSCHEException、IOException、InterruptedException{
PoolTest测试=新的PoolTest();
test.runCommand(“显示系统”);
test.runCommand(“显示版本”);
}
私有void runCommand(String命令)抛出JSCHEException、IOException、InterruptedException{
会话会话=createNewSession();
System.out.println(session.isConnected());
Channel=session.openChannel(“shell”);
((ChannelShell)channel.setPtyType(“哑”);
channel.connect();
OutputStream ops=channel.getOutputStream();
PrintStream ps=新的PrintStream(ops,true);
channel.connect();
ps.println(命令);
ps.close();
InputStream in=channel.getInputStream();
字节[]bt=新字节[1024];
while(true)
{
while(in.available()>0)
{
inti=in.read(bt,0,1024);
如果(我疯狂猜测你正在连接一个Cisco,它不支持创建多个shell通道(即使你试图断开第一个通道-它可能会延迟,因为你没有在
中显式关闭输入流).这是一个Dell交换机..我也尝试过显式关闭InputStream,但没有成功。它很可能遵循与cisco相同的行为,即在整个会话期间必须保持第一个通道打开。如果关闭它,则会中断整个会话。(第一条评论是错误的,Cisco支持每个会话有多个通道)。为什么要断开通道两次连接?当可以返回旧会话时,为什么要调用方法createNewSession()
?