java读取远程服务器上的log日志

上一篇 / 下一篇  2012-07-16 11:49:41 / 个人分类:java

通过ssh链接到对应的服务器上,然后通过tail -f xx.log 来动态读取服务器上的log日志
public class Basic{

    private static Connection conn = null;

    private String hostname = "";
    private String username = "";
    private String password = "";
    private String[] commands;
    /**
     *
     * @param hostname
     * @return
     */
    private Connection getConnection(String hostname) {
        if (conn == null) {
            conn = new Connection(hostname);
        }

        return conn;
    }

    public void exec(String[] commands) {
        for (int i = 0; commands != null && i < commands.length; i++) {
            Connection conn = getConnection(hostname);
            try {
                conn.connect();
                boolean isAuthenticated = conn.authenticateWithPassword(
                        username, password);
                if (isAuthenticated == false)
                    throw new IOException("Authentication failed.");
                Session sess = conn.openSession();
                sess.execCommand(commands[i]);
                InputStream stdout = new StreamGobbler(sess.getStdout());

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        stdout));
                while (true) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    System.out.println(line);
                }
                sess.close();
                conn.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Basic b = new Basic();
        b.setHostname("IP地址");
        b.setUsername("用户名");
        b.setPassword("y密码");
        String[] commands = { "shell命令" };
        b.exec(commands);
    }
    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Long getBizId() {
        return bizId;
    }

    public void setBizId(Long bizId) {
        this.bizId = bizId;
    }

    public LogMessageService getLogService() {
        return logService;
    }

    public void setLogService(LogMessageService logService) {
        this.logService = logService;
    }

    public String[] getCommands() {
        return commands;
    }

    public void setCommands(String[] commands) {
        this.commands = commands;
    }
}


TAG:

 

评分:0

我来说两句

Open Toolbar