Java Secure Channel的简单实现

参考文章:https://blog.csdn.net/amu0324/article/details/4267520

主要实现类

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

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;


import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;


public class ShellUtils implements ShellUtil{
    private static JSch jsch;
    private static Session session;

    /**
     * 连接到指定的IP
     *
     * @throws JSchException
     */
    public static void connect(String user, String passwd, String host) throws JSchException {
        jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);

        session.connect();
        System.out.println("connect success!!!");
    }


    /**
     * 执行相关的命令
     * @throws JSchException
     */
    public static void execCmd(String command, String user, String passwd, String host) throws JSchException {
        connect(user, passwd, host);
//用来记录服务器反馈的信息

        BufferedReader reader = null;

        Channel channel = null;


        try {
            if (command != null) {
                channel = session.openChannel("exec");
                ((ChannelExec) channel).setCommand(command);


                channel.setInputStream(null);
                ((ChannelExec) channel).setErrStream(System.err);


                channel.connect();
                InputStream in = channel.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));
                //这个buffer是得到显示信息的
                String buf = null;
                while ((buf = reader.readLine()) != null) {
                    log.println(buf);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSchException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            channel.disconnect();
            session.disconnect();
        }
    }
}


猜你喜欢

转载自blog.csdn.net/redistant/article/details/80986794