JAVA SSH2工具类

计划

  • ssh2utils
  • connection
  • 常规session操作 未完成
  • 常规scf操作 未完成

简介

使用java进行ssh 操作,执行脚本,scp文件的包装

依赖

     
        
            com.trilead
            trilead-ssh2
            1.0.0-build221
        
        

接口

public abstract class SSH2Utils {

    private final static Logger logger = LoggerFactory.getLogger(SSH2Utils.class);

    /**
     * 根据 远程主机地址获得  连接,之后需要依次进行 connect 和 鉴权
     *
     * @param host 远程主机地址
     */
    public static EnhanceConnection just(String host) {
        return EnhanceConnection.onAssembly(host);
    }

    /**
     * 根据 远程主机地址 以及端口 获得  连接,之后需要依次进行 connect 和 鉴权
     *
     * @param host 远程主机地址
     * @param port 端口
     */
    public static EnhanceConnection just(String host, int port) {
        logger.info("suggest use easy to get connection");
        return EnhanceConnection.onAssembly(host, port);
    }

    /**
     * @param host     远程主机地址
     * @param port     端口
     * @param userame  用户名
     * @param password 密码
     */
    public static EnhanceConnection easy(String host, int port, String userame, String password) {
        return just(host, port).connect().authenticate(userame, password);
    }


}

业务逻辑

EnhanceConnection.class


public class EnhanceConnection {


    private Connection connection;

    public static EnhanceConnection onAssembly(String host) {
        return new EnhanceConnection(host);
    }

    public static EnhanceConnection onAssembly(String host, int port) {
        return new EnhanceConnection(host, port);
    }

    private EnhanceConnection(String host) {
        connection = new Connection(host);
    }

    private EnhanceConnection(String host, int port) {
        connection = new Connection(host, port);
    }


    // authentication
    public EnhanceConnection authenticate(String username, String passwald) {
        try {

            boolean boolen = connection.authenticateWithPassword(username, passwald);
            if (boolen) {
                return this;
            } else {
                throw new RuntimeException("Authentication Failed");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Username or Password Error" + e);
        }
    }

    // connect to the server
    public EnhanceConnection connect() {
        try {
            connection.connect((ServerHostKeyVerifier) null, 0, 0);

            return this;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("There was a problem during connect" + e);
        }
    }

    public Connection getConnection() {
        if (connection == null) {
            throw new RuntimeException("connection nout init");
        }
        return connection;
    }

    public EnhanceSession session() {
        return EnhanceSession.onAssembly(this);
    }

    public EnhanceSCP scpClient() {
        return EnhanceSCP.onAssembly(this);
    }
}

你可能感兴趣的:(java)