• java-代码操作服务器之SSH连续发送命令


      java操作Linux服务器可以使用专用的jar包,这里介绍使用jsch操作Linux服务器

    maven 依赖


    com.jcraft
    jsch
    0.1.54


    引入包以后 获取ssh连接

    public static ChannelShell connectShell(Session session) {
    ChannelShell shell = null;
    try {
    shell = (ChannelShell) session.openChannel(type_ssh);
    shell.connect();

    System.out.println();
    System.out.println("shell resource:" + session.equals(shell.getSession()));
    System.out.println("shell login ok:" + shell.getId());
    System.out.println();
    return shell;
    } catch (Exception e) {
    e.printStackTrace();
    }
    return shell;
    }

    以上获取到连接对象可以进行交互操作,在调用方法中定义接收流对象后可以交互执行命令
    一下监听和发送都在一个线程中,所以开启定时任务发送命令,主进程监听消息获取
    getMsg为接收消息方法
    private static PrintStream commander;//定义常量   发送消息使用


    BufferedReader br;
    try {
    OutputStream outputStream = myShellSession_.getChannelShell().getOutputStream();
    InputStream inputStream = myShellSession_.getChannelShell().getInputStream();
    commander = new PrintStream(outputStream, false, MyShellAndSftpUtils.ENCODING);
    br = new BufferedReader(new InputStreamReader(inputStream, MyShellAndSftpUtils.ENCODING));
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
    @Override
    public void run() {
    sendMsg("pwd");//定时发送消息
    System.out.println("shell run , time is "+DataTimeUtils.getDataStrOut());
    }
    },0,DataTimeUtils.getaLong(myShellSession_.getConfigParams().getShellTime()));//立即执行 过15分执行 15分 * 60 秒 * 1000毫秒
    try {
    getMsg();
    } catch (Exception e) {
    e.printStackTrace();
    }


    //接收消息调用
    public static void getMsg() throws Exception {
    StringBuffer buffer = new StringBuffer();
    String line;
    boolean flag = false;
    while ((line = br.readLine()) != null) {
    System.out.println("line " + line);
    if (line.startsWith("Starting Nmap")) {
    flag = true;
    }
    if (flag) {
    buffer.append(line);
    buffer.append(MyShellAndSftpUtils.lineSeparator);
    }
    if (line.startsWith("****:")) {//检测返回信息的开始
    flag = false;
    saveDb(buffer.toString());//执行存储等逻辑
    buffer.setLength(0);
    }

    }
    }

    public static void sendMsg(String msg) {
    commander.println(msg);
    commander.flush();
    }

    以上方案可以连续执行命令,但是返回的结果需要进行判断后才能进入自己的操作
  • 相关阅读:
    HCIA-STP原理与配置
    使用VHDL语言实现简单的卷积神经网络
    音视频SDP协议详解(描述会话的协议)
    字符设备驱动框架(字符设备基础一)
    【算法练习Day16】找树左下角的值&&路径总和&& 从中序与后序遍历序列构造二叉树
    抖音店铺提供优质服务|成都瀚网科技
    2N2222简介及用Arduino模拟
    算法---------空间复杂度
    四轴飞行器的电池研究(Matlab&Simulink仿真)
    LRU和LFU算法的区别
  • 原文地址:https://www.cnblogs.com/CaiNiao-TuFei/p/16592363.html