• 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();
    }

    以上方案可以连续执行命令,但是返回的结果需要进行判断后才能进入自己的操作
  • 相关阅读:
    leetcode:2446. 判断两个事件是否存在冲突(python3解法)
    【C++】STL——vector(万字详解)
    645. 错误的集合
    1042 Shuffling Machine
    【工作小技巧】刚入职的软件测试工程师怎么快速上手新岗位
    AMRT 3D 数字孪生引擎(轻量化图形引擎、GIS/BIM/3D融合引擎):智慧城市、智慧工厂、智慧建筑、智慧校园。。。
    RabbitMQ原理(一):基础知识
    微信小程序开发入门与实战(Behaviors使用)
    【数学】主成分分析(PCA)的详细深度推导过程
    SQL血缘解析原理
  • 原文地址:https://www.cnblogs.com/CaiNiao-TuFei/p/16592363.html