码迷,mamicode.com
首页 > 编程语言 > 详细

java使用ganymed-ssh2执行linux命令

时间:2015-07-22 16:09:11      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:linux

ganymed-ssh2简介

Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。

下载地址

使用方法

将 ganymed-ssh2-build210.jar 加入到项目的lib中即可

举例说明

获取linux服务器上某个目录的占用空间大小

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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

public class SShUtil {

    public static String getDirSize(String path){
        String hostname = "linux服务器ip地址";
        String username = "linux用户";
        String password = "linux密码";
        String size = "";
        try {
            /* Create a connection instance */
            Connection conn = new Connection(hostname);
            /* Now connect */
            conn.connect();
            /*
             * Authenticate. If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */

            boolean isAuthenticated = conn.authenticateWithPassword(username,
                    password);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

            /* Create a session */

            Session sess = conn.openSession();
            sess.execCommand("du -m --max-depth=0 "+path);
            /*
             * This basic example does not handle stderr, which is sometimes
             * dangerous (please read the FAQ).
             */

            InputStream stdout = new StreamGobbler(sess.getStdout());

            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

            String line = br.readLine();

            String ss[] = line.split("\\s+");
            size = ss[0];
            /* Show exit status, if available (otherwise "null") */
            // System.out.println("ExitCode: " + sess.getExitStatus());
            /* Close this session */
            sess.close();
            /* Close the connection */
            conn.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(2);
        }
        return size;
    }
    public static void main(String[] args) {
        System.out.println(getDirSize("/mnt/online/resource/media"));
    }

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

java使用ganymed-ssh2执行linux命令

标签:linux

原文地址:http://blog.csdn.net/u013628152/article/details/47004005

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!