java 私钥登录ssh

11 篇文章 1 订阅
package org.utils.ssh;

import com.jcraft.jsch.*;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * rsa ssh 登录
 */
public class PublicKeyLogin {

    private static Session session;

    private static Channel channel;

    public static Session getSession() {
        return session;
    }

    public static Channel getChannel() {
        return channel;
    }

    /**
     * 不进行连接,只返回session
     * @param host
     * @param port
     * @param userName
     * @param pkeyPath 密钥路径
     * @param securityLevel 公钥检查  no、ask、yes
     * @return
     * @throws JSchException
     */
    public  static Session  getSession(String host,String port,String userName,String pkeyPath,String securityLevel) throws JSchException {
        if(session != null ){

                return  session;

        }
        //从配置文件中读取 目标服务器ip、端口、用户名、私钥路径
//        String ftpHost = prop.getProperty("downloadHost");
//        String port = prop.getProperty("downloadftpPort");
//        String ftpUserName = prop.getProperty("downloadUserName");
//        String priKeyBasePath = prop.getProperty("priBaseKeyPath");
        //建立JSch对象
        JSch jsch = new JSch();
        try{
            //添加私钥
            jsch.addIdentity(pkeyPath);
            try{
            session=jsch.getSession(userName, host);
            }catch (Exception e){
                System.out.println("ss"+e.getMessage());
            }
            Properties sessionConfig = new Properties();
            //SSH 公钥检查机制 no、ask、yes
            /**
             * 当StrictHostKeyChecking=yes时,SSH 执行严格公钥检查模式,拒绝连接没有记录在/etc/ssh/ssh_known_hosts列表中的远程主机。
             *
             * 当StrictHostKeyChecking=ask时,SSH 执行默认公钥检查模式,当用户连接远程主机时,会检查主机的公钥。如果用户是第一次连接该主机,会显示出该远程主机的公钥摘要,并提示用户是否信任该远程主机。选择接受,则将该远程主机的公钥追加到文件~/.ssh/known_hosts中,用户下次再连接时,就不会出现提示信息了。
             *
             * 当StrictHostKeyChecking=no时,SSH 执行宽松公钥检查模式,自动将连接的远程主机的公钥追加到文件~/.ssh/known_hosts中,不出现提示信息提示用户信任该远程主机。
             */
            sessionConfig.put("StrictHostKeyChecking", securityLevel);
            session.setConfig(sessionConfig);
           // session.connect();
            return  session;
//            channelSftp = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
//            channelSftp.connect();
//            //进行操作 如进入指定文件夹
//            channelSftp.cd(config.getFileDir());
        }catch (JSchException e) {
           throw  new JSchException();
        }
    }

    /**
     * 设置私钥登录密码
     * @param passPhrase
     */
    public static void setPassPhrase(String passPhrase){
        UserInfo ui = new GoldwindUser(passPhrase);
        session.setUserInfo(ui);
    }



    /**
     *不进行连接,只进行创建
     * @param timeout 连接超时时间 ,毫秒
     * @param type 创建channel的类型
     * @return channel
     * @throws JSchException
     */
    public static Channel getChannel(int timeout,String type) throws JSchException {
        //获取jsch的会话
        //Properties config = new Properties();
        //连接  超时时间30s,30000
        //session.connect(timeout);
        //开启shell通道,shell
        channel = session.openChannel(type);
        //通道连接 超时时间3s
        //channel.connect(timeout);
        return channel;
    }

    public  static String runExec(String commands,String charset) throws JSchException, IOException {
        try {
            ChannelExec channelExec = (ChannelExec) getChannel(50000, "exec");
            System.out.println(PublicKeyLogin.getSession().isConnected());
            channelExec.setPty(false);
            channelExec.setCommand(commands);
            channelExec.connect();
            InputStream std = channelExec.getInputStream();
            InputStream error = channelExec.getErrStream();
            BufferedReader brStd = new BufferedReader(new InputStreamReader(std, StandardCharsets.UTF_8));
            BufferedReader brError = new BufferedReader(new InputStreamReader(error, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = brStd.readLine()) != null) {
                if (!line.equals("")) {
                    sb.append(line + "\n");
                }
            }

            while ((line = brError.readLine()) != null) {
                if (!line.equals("")) {
                    sb.append(line + "\n");
                }
            }
            channelExec.disconnect();
            return  sb.substring(0);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return  "";
        }

    }


    /**
     * 执行命令
     * @param commands
     * @param charset
     * @return
     */
    public  static String runExec(String[] commands,String charset) throws JSchException, IOException {

        //String[] commands = new String[]{"ls -l ","echo 123123"};
        String command = commands[0];
        for (int i = 1; i <commands.length ; i++) {
            command += " && "+commands[i];
        }
        String sb = runExec(command,charset);
        return  sb;
    }

    public static  String runShell(String cmd, String charset) throws Exception {
        String temp = null;

        InputStream instream = null;
        OutputStream outstream = null;
        try {
            instream = channel.getInputStream();
            outstream = channel.getOutputStream();
            outstream.write(cmd.getBytes());
            outstream.flush();
            TimeUnit.SECONDS.sleep(2);
            if (instream.available() > 0) {
                byte[] data = new byte[instream.available()];
                int nLen = instream.read(data);

                if (nLen < 0) {
                    throw new Exception("network error...桌面有错误");
                }

                temp = new String(data, 0, nLen, "UTF-8");
            }
        }  finally {
            outstream.close();
            instream.close();
        }
        return temp;
    }

    public static  void closeSession() {

        session.disconnect();
    }

    public static void closeChannel(){
        channel.disconnect();
    }

    public  static void  close(){
        channel.disconnect();
        session.disconnect();
    }
    public static class GoldwindUser implements  UserInfo{
        private String passphrase = null;

        public GoldwindUser(String passphrase) {
            this.passphrase = passphrase;
        }
        @Override
        public String getPassphrase() {
            return passphrase;
        }

        @Override
        public String getPassword() {
            return null;
        }

        @Override
        public boolean promptPassword(String s) {
            return true;
        }

        @Override
        public boolean promptPassphrase(String s) {
            return true;
        }

        @Override
        public boolean promptYesNo(String s) {
            return true;
        }

        @Override
        public void showMessage(String s) {
            System.out.println("passPhrase:"+s);
        }
    }


}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值