zoukankan      html  css  js  c++  java
  • Java使用ganymed工具包执行LINUX命令教程

    了解更多开发技巧,请访问,架构师小跟班官网:https://www.jiagou1216.com

    package com.jiagou;

    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.Session;
    import ch.ethz.ssh2.StreamGobbler;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    /**
    * ganymed简单教程Demo,第一步:引入jar包
    * <dependency>
    * <groupId>ch.ethz.ganymed</groupId>
    * <artifactId>ganymed-ssh2</artifactId>
    * <version>262</version>
    * </dependency>
    */
    public class GanymedDemo {
    //命令集
    private static List<String> commands = null;
    private static void initCommands() {
    commands = new ArrayList<String>();
    //查看token.conf文件内容
    commands.add("cat /usr/local/websockify/token/token.conf");
    //追加文本到token.conf文件
    commands.add("echo jiagou1216.com >> /usr/local/websockify/token/token.conf");
    }

    public static void main(String[] args) {
    //第二步:连接Linux服务器
    String hostName = "192.168.1.75";
    String userName = "root";
    String password = "admin@123";
    try {
    //连接服务器
    Connection conn = new Connection(hostName);
    conn.connect();
    boolean isAuthenticated = conn.authenticateWithPassword(userName, password);
    if (!isAuthenticated) {
    throw new IOException("Authentication failed.");
    }
    //初始化命令参数
    initCommands();
    //第三步:执行shell命令
    StringBuffer details = new StringBuffer();
    for (String command : commands) {
    Session sess = conn.openSession();
    sess.execCommand(command);
    InputStream stdout = new StreamGobbler(sess.getStdout());
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
    while (true) {
    String line = br.readLine();
    if (line == null) {
    break;
    }
    details.append(line + " ");//换行
    }
    System.out.println(details);
    }
    conn.close();
    } catch (IOException e) {
    e.printStackTrace(System.err);
    }
    }
    }
  • 相关阅读:
    多线程编程(2):线程的同步
    C#中listview实现排序
    [PLC]S7-300的数据类型
    C# 多线程编程(4):多线程与UI操作
    Thunderbird 80 column FIX 发出的邮件也需要在80列处line break
    vsftp 500 OOPS: vsftpd: refusing to run with writable anonymous root
    科普 What is YUV
    转载:网站真的可以无密码登录么?
    Ubuntu 12.04安装Microsoft lifecam studio摄像头
    Thunderbird on Ubuntu 12.04 调整邮件列表行间距
  • 原文地址:https://www.cnblogs.com/xyhero/p/12188848.html
Copyright © 2011-2022 走看看