栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用JSch在远程SSH会话上运行telnet命令

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用JSch在远程SSH会话上运行telnet命令

我知道了。

__在while循环中, line 永远不会为 null

为何在调试中起作用仍是一个谜。

我正在发布 新代码 。我希望它对每个想做类似事情的人都有帮助。

package Utility;import com.jcraft.jsch.Channel;import com.jcraft.jsch.JSch;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.Session;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.InputStreamReader;public class JavaTelnet {    public static void main(String[] arg) {        try { System.out.println(telnetConnection(YOUR_COMMAND,YOUR_USER,YOUR_PASS,YOUR_HOST));        } catch (Exception e) { e.printStackTrace();        }    }    public static String telnetConnection(String command, String user, String password, String host) throws JSchException, Exception {      JSch jsch=new JSch();      Session session=jsch.getSession(user, host, 22);      session.setPassword(password);      // It must not be recommended, but if you want to skip host-key check,       session.setConfig("StrictHostKeyChecking", "no");      session.connect(3000);      //session.connect(30000);   // making a connection with timeout.      Channel channel=session.openChannel("shell");      channel.connect(3000);      DataInputStream dataIn = new DataInputStream(channel.getInputStream());      BufferedReader reader = new BufferedReader(new InputStreamReader(dataIn));      DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());      System.out.println("Starting telnet connection...");      dataOut.writeBytes("telnet localhost 4242rn");//      dataOut.writeBytes("enablern");      dataOut.writeBytes(command+"rn");      dataOut.writeBytes("exitrn"); //exit from telnet       dataOut.writeBytes("exitrn"); //exit from shell       dataOut.flush();      String line = reader.readLine();      String result = line +"n";        while (!(line= reader.readLine()).equals("Connection closed by foreign host")){          result += line +"n";      }      dataIn.close();      dataOut.close();      channel.disconnect();      session.disconnect();      return result;  }}

注意,该外壳是Linux外壳。在Windows中,“退出”命令应该不同



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470434.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号