JSch连接linux

package cn.com.servyou.sdi.web.utils;

import cn.com.servyou.sdi.stream.SdiException;
import cn.com.servyou.sdi.web.vo.SshServer;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * java利用jsch远程连接linux进行管理
 **/
public class SSHUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(SSHUtils.class);
    public static Session getJschSession(SshServer sshServer) {
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(sshServer.getSshServerUser(), sshServer.getSshServerUrl());
            session.setPassword(sshServer.getSshServerPassword());
            //第一次访问服务器不用输入yes
            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(60 * 60 * 1000);
            session.connect();
            return session;
        } catch (JSchException e) {
            LOGGER.error("连接SSH服务器失败", e);
            return null;
        }
    }
    public static String executeCommand(SshServer sshServer, String command) {
        // 执行单句命令
        Session session = getJschSession(sshServer);
        if (null == session) {
            throw new Exception("3", "登录SSH服务器失败");
        }
        String result = "";
        try {
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            InputStream in = channelExec.getInputStream();
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();
            result = getResult(in, channelExec);
            channelExec.disconnect();
        } catch (JSchException | IOException e) {
            LOGGER.error("执行指令失败", e);
            throw new Exception("5", "执行指令失败");
        }
        session.disconnect();
        return result;
    }
    public static String executeShell(SshServer sshServer, String[] commands) {
        if (null == commands || commands.length == 0) {
            throw new Exception("12", "无指令");
        }
        String result = "";
        Session session = getJschSession(sshServer);
        if (null == session) {
            throw new Exception("00003", "登录SSH服务器失败");
        }
        try {
            ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
            //从远端到达的数据  都能从这个流读取到
            InputStream inputStream = channelShell.getInputStream();
            channelShell.setPty(true);
            channelShell.connect();
            //写入该流的数据  都将发送到远程端
            OutputStream outputStream = channelShell.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            for (String command : commands) {
                printWriter.println(command);
            }
            //把缓冲区的数据强行输出
            printWriter.flush();
            result = getResult(inputStream, channelShell);
            outputStream.close();
            inputStream.close();
            channelShell.disconnect();
        } catch (JSchException | IOException e) {
            LOGGER.error("执行指令失败", e);
        }
        session.disconnect();
        return result;
    }
    private static String getResult(InputStream in, Channel channel) throws IOException {
        StringBuilder sb = new StringBuilder();
        byte[] tmp = new byte[1024];
        while (!channel.isClosed()) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                sb.append(new String(tmp, 0, i));
            }
        }
        return sb.toString();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值