Jsch支持command模式

使用如下方式打开一个channel:

 channel = session.openChannel("exec");

全部代码如下:

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

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

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

public class JSchCommandDemo {
    Logger logger = null;

    private String charset = "UTF-8"; //

    private String user; //

    private String passwd; //

    private String host; //

    private JSch jsch;

    private Session session;

    String path = null;

    String retn = null;

    public JSchCommandDemo(String user, String passwd, String host) {
        this.user = user;
        this.passwd = passwd;
        this.host = host;
        this.path = getClass().getResource("/").getFile().toString();
        PropertyConfigurator.configure(path + File.separator + "log4j.properties");

        System.out.println("Init JSchDemo....");
        this.logger = Logger.getLogger(JSchCommandDemo.class);
    }

    public void connect() throws JSchException {
        jsch = new JSch();
        logger.info("[JSchDemo]: user is " + user + " and host is " + host);
        session = jsch.getSession(user, host, 22);
        logger.info("[JSchDemo]: session is " + session);
        session.setPassword(passwd);
        logger.info("[JSchDemo]: passwd is " + passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        logger.info("[JSchDemo]: session connected or not is " + session.isConnected());
    }

    @SuppressWarnings("resource")
    public void execCmd() throws InterruptedException {
        // BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String command = "ll \n";
        BufferedReader reader = null;
        Channel channel = null;

        try {
            if (command != null) {
                channel = session.openChannel("exec");
                logger.info("[JSchDemo]: channel is " + channel);
                // ((ChannelExec) channel).setCommand(command);
                logger.info("[JSchDemo]: channel is " + channel);
                channel.setInputStream(null);
                ((ChannelExec) channel).setErrStream(System.err);
                InputStream in = channel.getInputStream();
                InputStream extIn = channel.getExtInputStream();
                channel.connect();
                logger.info("[JSchDemo]: channel connected is " + channel.isConnected());

                // byte[] bte = new byte[1024];
                int res = -1;
                logger.info("[JSchDemo]: in is " + in);
                // BufferReader reader = new BufferReader(new InputStreamReader);
                logger.info("in.available() is " + in.available());
                StringBuffer buf = new StringBuffer(1024);
                byte[] tmp = new byte[1024];
                boolean isSuccess = true;
                while (true) {
                    while (in.available() > 0) {
                        int i = in.read(tmp, 0, 1024);
                        if (i < 0)
                            break;
                        String s = new String(tmp, 0, i);
                        System.out.print(s);
                        logger.debug(s);
                    }
                    if (channel.isClosed()) {
                        System.out.println("exit-status: " + channel.getExitStatus());
                        logger.debug("exit-status: " + channel.getExitStatus());
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    }
                    catch (Exception ee) {
                    }
                }
                logger.info("[JSchDemo]: bufLast is " + buf.toString());
            }
        }
        catch (IOException e) {
            logger.error("[JSchDemo]: IOException is " + e.getMessage());
        }
        catch (JSchException e) {
            logger.error("[JSchDemo]: JSchException is " + e.getMessage());
        }
        finally {
            try {
                if (reader != null) {
                    reader.close();
                }

            }
            catch (IOException e) {
                e.printStackTrace();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }

        }
    }

    public static void main(String[] args) throws Exception {

        String user = args[1];
        String passwd = args[2];
        String host = args[0];

        JSchCommandDemo demo = new JSchCommandDemo(user, passwd, host);
        System.out.println(demo.path);

        demo.connect();
        demo.execCmd();
    }
}

附上ssh rfc地址:
ssh rfc

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,287评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Java NIO(New IO)是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的Java I...
    JackChen1024阅读 7,583评论 1 143
  • 背景: 阅读新闻 12C CDB模式下RMAN备份与恢复 [日期:2016-11-29] 来源:Linux社区 作...
    阳屯okyepd阅读 3,605评论 0 7
  • /老月光/ 上一章 /猜测/ 当眩光透过双眼开始自动旋转,酒吧里的气氛便开始变得稠密而柔和。这个时候,响起的手机铃...
    青老七阅读 172评论 0 0