java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java ssh连接服务器

java实现ssh连接服务器的方法步骤

作者:Roc-xb

本文主要介绍了java实现ssh连接服务器的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、引入依赖

<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

二、工具类

(1)SSHExecutor类

import com.jcraft.jsch.*;
import java.io.*;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
public class SSHExecutor {
    private static long INTERVAL = 100L;
    private static int SESSION_TIMEOUT = 30000;
    private static int CHANNEL_TIMEOUT = 3000;
    private JSch jsch = null;
    private Session session = null;
    public SSHExecutor(SSHInfo sshInfo) throws JSchException {
        jsch = new JSch();
        session = jsch.getSession(sshInfo.getUser(), sshInfo.getHost(), sshInfo.getPort());
        session.setPassword(sshInfo.getPassword());
        session.setUserInfo(new MyUserInfo());
        session.connect(SESSION_TIMEOUT);
    }
    /*
    * 注意编码转换
    * */
    public long shell(String cmd, String outputFileName) throws JSchException, IOException, InterruptedException {
        long start = System.currentTimeMillis();
        Channel channel = session.openChannel("shell");
        PipedInputStream pipeIn = new PipedInputStream();
        PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
        FileOutputStream fileOut = new FileOutputStream(outputFileName, true);
        channel.setInputStream(pipeIn);
        channel.setOutputStream(fileOut);
        channel.connect(CHANNEL_TIMEOUT);
        pipeOut.write(cmd.getBytes());
        Thread.sleep(INTERVAL);
        pipeOut.close();
        pipeIn.close();
        fileOut.close();
        channel.disconnect();
        return System.currentTimeMillis() - start;
    }
    public int exec(String cmd) throws IOException, JSchException, InterruptedException {
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setCommand(cmd);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        InputStream in = channelExec.getInputStream();
        channelExec.connect();
        int res = -1;
        StringBuffer buf = new StringBuffer(1024);
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                buf.append(new String(tmp, 0, i));
            }
            if (channelExec.isClosed()) {
                res = channelExec.getExitStatus();
                System.out.println( format("Exit-status: %d", res));
                break;
            }
            TimeUnit.MILLISECONDS.sleep(100);
        }
        System.out.println(buf.toString());
        channelExec.disconnect();
        return res;
    }
    public Session getSession() {
        return session;
    }
    public void close() {
        getSession().disconnect();
    }
    /*
    * SSH连接信息
    * */
    public static class SSHInfo {
        private String user;
        private String password;
        private String host;
        private int port;
        public SSHInfo(String user, String password, String host, int port) {
            this.user = user;
            this.password = password;
            this.host = host;
            this.port = port;
        }
        public String getUser() {
            return user;
        }
        public String getPassword() {
            return password;
        }
        public String getHost() {
            return host;
        }
        public int getPort() {
            return port;
        }
    }
    /*
    * 自定义UserInfo
    * */
    private static class MyUserInfo implements UserInfo {
        @Override
        public String getPassphrase() {
            return null;
        }
        @Override
        public String getPassword() {
            return null;
        }
        @Override
        public boolean promptPassword(String s) {
            return false;
        }
        @Override
        public boolean promptPassphrase(String s) {
            return false;
        }
        @Override
        public boolean promptYesNo(String s) {
            System.out.println(s);
            System.out.println("true");
            return true;
        }
        @Override
        public void showMessage(String s) {
        }
    }
}

(2)SSHUtil类

import com.jcraft.jsch.JSchException;
import java.io.IOException;
public class SSHUtil {
    public static SSHExecutor sshExecutor;
    public static void start (){
        // 此处配置服务器信息
        SSHExecutor.SSHInfo sshInfo = new SSHExecutor.SSHInfo("用户名", "密码", "host", "port");
        try {
            sshExecutor = new SSHExecutor(sshInfo);
            System.err.println("ssh灾备日志服务器已链接");
        } catch (Exception e) {
            System.err.println("ssh灾备日志服务器链接失败!!");
            e.printStackTrace();
            sshExecutor.close();
        }
    }
    /**
    * 运行cmd命令
    */
    public static void runCmd (String cmd) throws JSchException, IOException, InterruptedException {
        sshExecutor.exec(cmd);
    }
}

三、使用方法

启动类中加入

SSHUtil.start();

例如:运行cmd命令

SSHUtil.runCmd("cmd");

到此这篇关于java实现ssh连接服务器的方法步骤的文章就介绍到这了,更多相关java ssh连接服务器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文