码迷,mamicode.com
首页 > Web开发 > 详细

JSCH执行linux命令

时间:2017-11-09 17:17:27      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:throws   lin   pos   exec   amp   port   host   logs   command   

pom.xml 添加jar依赖

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

 

java类

package com.aliyun.utility.jsch;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.InputStream;

import java.util.Properties;


public class JSCHUtil {
    private static JSCHUtil instance;

    private JSCHUtil() {
    }

    public static JSCHUtil getInstance() {
        if (instance == null) {
            instance = new JSCHUtil();
        }

        return instance;
    }

    private Session getSession(String host, int port, String ueseName)
        throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(ueseName, host, port);

        return session;
    }

    public Session connect(String host, int port, String ueseName,
        String password) throws Exception {
        Session session = getSession(host, port, ueseName);
        session.setPassword(password);

        Properties config = new Properties();
        config.setProperty("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        return session;
    }

    public String execCmd(Session session, String command)
        throws Exception {
        if (session == null) {
            throw new RuntimeException("Session is null!");
        }

        ChannelExec exec = (ChannelExec) session.openChannel("exec");
        InputStream in = exec.getInputStream();
        byte[] b = new byte[1024];

        exec.setCommand(command);
        exec.connect();

        StringBuffer buffer = new StringBuffer();

        while (in.read(b) > 0) {
            buffer.append(new String(b));
        }

        exec.disconnect();

        return buffer.toString();
    }

    public void clear(Session session) {
        if ((session != null) && session.isConnected()) {
            session.disconnect();
            session = null;
        }
    }

    public static void main(String[] args) throws Exception {
        Session session = JSCHUtil.getInstance()
                                  .connect("10.9.9.135", 22, "yy", "yy");
        String cmd = "cd /" + ";" + "ls -al |grep home";
        String result = JSCHUtil.getInstance().execCmd(session, cmd); // ???????;?? 
        System.out.println(result);
        System.exit(0);
    }
}

 

JSCH执行linux命令

标签:throws   lin   pos   exec   amp   port   host   logs   command   

原文地址:http://www.cnblogs.com/lovedaodao/p/7810060.html

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