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

    以上方案可以连续执行命令,但是返回的结果需要进行判断后才能进入自己的操作
  • 相关阅读:
    算法基础习题—内存分配(区间树实现)
    自动驾驶概述
    Python递归次数统计写法及邮件发送失败后的重新发送
    matlab判断下列级数的收敛性
    xcode Simulator 手动安装
    C++ 学习(六)函数 及 函数的分文件编写
    【送书活动】揭秘分布式文件系统大规模元数据管理机制——以Alluxio文件系统为例
    python驾到~障碍通通闪开,美女批量入内存~
    Linux常用命令
    软件测试需要学习什么 3分钟带你了解软测的学习内容
  • 原文地址:https://www.cnblogs.com/CaiNiao-TuFei/p/16592363.html