Search in sources :

Example 41 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project Jpom by dromara.

the class CommandService method execute.

/**
 * 执行命令
 *
 * @param commandModel        命令模版
 * @param commandExecLogModel 执行记录
 * @param sshModel            ssh
 * @param commandParamsLine   参数
 * @throws IOException io
 */
private void execute(CommandModel commandModel, CommandExecLogModel commandExecLogModel, SshModel sshModel, String commandParamsLine) throws IOException {
    File file = commandExecLogModel.logFile();
    try (BufferedOutputStream outputStream = FileUtil.getOutputStream(file)) {
        if (sshModel == null) {
            this.appendLine(outputStream, "ssh 不存在");
            return;
        }
        String command = commandModel.getCommand();
        String[] commands = StrUtil.splitToArray(command, StrUtil.LF);
        // 
        workspaceEnvVarService.formatCommand(commandModel.getWorkspaceId(), commands);
        // 
        Charset charset = sshModel.getCharsetT();
        sshService.exec(sshModel, (s, session) -> {
            final ChannelExec channel = (ChannelExec) JschUtil.createChannel(session, ChannelType.EXEC);
            channel.setCommand(StrUtil.bytes(s + StrUtil.SPACE + commandParamsLine, charset));
            channel.setInputStream(null);
            channel.setErrStream(outputStream, true);
            InputStream in = null;
            try {
                channel.connect();
                in = channel.getInputStream();
                IoUtil.readLines(in, charset, (LineHandler) line -> this.appendLine(outputStream, line));
                // 更新状态
                this.updateStatus(commandExecLogModel.getId(), CommandExecLogModel.Status.DONE);
            } catch (Exception e) {
                DefaultSystemLog.getLog().error("执行命令错误", e);
                // 更新状态
                this.updateStatus(commandExecLogModel.getId(), CommandExecLogModel.Status.ERROR);
                // 记录错误日志
                String stacktraceToString = ExceptionUtil.stacktraceToString(e);
                this.appendLine(outputStream, stacktraceToString);
            } finally {
                IoUtil.close(in);
                JschUtil.close(channel);
            }
            return null;
        }, commands);
    }
}
Also used : CronUtils(io.jpom.cron.CronUtils) ExceptionUtil(cn.hutool.core.exceptions.ExceptionUtil) DefaultSystemLog(cn.jiangzeyin.common.DefaultSystemLog) IdUtil(cn.hutool.core.util.IdUtil) BufferedOutputStream(java.io.BufferedOutputStream) JschUtil(cn.hutool.extra.ssh.JschUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) Charset(java.nio.charset.Charset) Service(org.springframework.stereotype.Service) WorkspaceEnvVarService(io.jpom.service.system.WorkspaceEnvVarService) IoUtil(cn.hutool.core.io.IoUtil) ChannelExec(com.jcraft.jsch.ChannelExec) BaseWorkspaceService(io.jpom.service.h2db.BaseWorkspaceService) LineHandler(cn.hutool.core.io.LineHandler) CommandModel(io.jpom.model.data.CommandModel) SshService(io.jpom.service.node.ssh.SshService) IOException(java.io.IOException) SystemUtil(cn.hutool.system.SystemUtil) ICron(io.jpom.cron.ICron) Collectors(java.util.stream.Collectors) File(java.io.File) ChannelType(cn.hutool.extra.ssh.ChannelType) StrUtil(cn.hutool.core.util.StrUtil) List(java.util.List) CommandExecLogModel(io.jpom.model.data.CommandExecLogModel) Task(cn.hutool.cron.task.Task) CharsetUtil(cn.hutool.core.util.CharsetUtil) SshModel(io.jpom.model.data.SshModel) FileUtil(cn.hutool.core.io.FileUtil) JSONObject(com.alibaba.fastjson.JSONObject) ThreadUtil(cn.hutool.core.thread.ThreadUtil) UserModel(io.jpom.model.data.UserModel) BaseServerController(io.jpom.common.BaseServerController) Assert(org.springframework.util.Assert) InputStream(java.io.InputStream) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException)

Example 42 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project Jpom by dromara.

the class TestJschExec method test2.

@Test
public void test2() throws IOException, JSchException {
    Charset charset = CharsetUtil.CHARSET_UTF_8;
    Session session = JschUtil.createSession("192.168.1.8", 22, "root", "123456+");
    ChannelExec channel = (ChannelExec) JschUtil.createChannel(session, ChannelType.EXEC);
    // 添加环境变量
    channel.setCommand(cmd);
    channel.setErrStream(System.err);
    channel.setInputStream(System.in);
    InputStream inputStream = channel.getInputStream();
    InputStream errStream = channel.getErrStream();
    channel.connect((int) TimeUnit.SECONDS.toMillis(5));
    // 
    String error = null;
    String result = null;
    try {
        result = IoUtil.read(inputStream, charset);
    } catch (Exception e) {
        e.printStackTrace();
        if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
            DefaultSystemLog.getLog().error("读取 exec 流发生异常", e);
            result = "读取 exec 流发生异常" + e.getMessage();
        }
    }
    try {
        error = IoUtil.read(errStream, charset);
    } catch (Exception e) {
        e.printStackTrace();
        if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
            DefaultSystemLog.getLog().error("读取 exec err 流发生异常", e);
            error = "读取 exec err 流发生异常" + e.getMessage();
        }
    }
    System.out.println("结束 " + result + "  " + error);
}
Also used : InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException) Session(com.jcraft.jsch.Session) Test(org.junit.Test)

Example 43 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project commons-vfs by apache.

the class SftpFileSystem method executeCommand.

/**
 * Executes a command and returns the (standard) output through a StringBuilder.
 *
 * @param command The command
 * @param output  The output
 * @return The exit code of the command
 * @throws JSchException       if a JSch error is detected.
 * @throws FileSystemException if a session cannot be created.
 * @throws IOException         if an I/O error is detected.
 */
private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException {
    final ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
    try {
        channel.setCommand(command);
        channel.setInputStream(null);
        try (InputStreamReader stream = new InputStreamReader(channel.getInputStream(), StandardCharsets.UTF_8)) {
            channel.setErrStream(System.err, true);
            channel.connect(DurationUtils.toMillisInt(connectTimeout));
            // Read the stream
            final char[] buffer = new char[EXEC_BUFFER_SIZE];
            int read;
            while ((read = stream.read(buffer, 0, buffer.length)) >= 0) {
                output.append(buffer, 0, read);
            }
        }
        // Wait until the command finishes (should not be long since we read the output stream)
        while (!channel.isClosed()) {
            try {
                Thread.sleep(SLEEP_MILLIS);
            } catch (InterruptedException e) {
                // Someone asked us to stop.
                break;
            }
        }
    } finally {
        channel.disconnect();
    }
    return channel.getExitStatus();
}
Also used : InputStreamReader(java.io.InputStreamReader) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 44 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project hopsworks by logicalclocks.

the class RemoteCommandExecutor method executeInternal.

private RemoteCommandResult executeInternal(RemoteCommand command) throws ServiceException {
    Channel channel = null;
    Session session = null;
    try {
        LOGGER.log(Level.FINE, "Executing remote command: " + command);
        JSch jsch = new JSch();
        jsch.addIdentity(command.getIdentity().toString());
        session = jsch.getSession(command.getUser(), command.getHost(), command.getPort());
        session.setConfig(command.getSSHConfig());
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(command.getConnectTimeout());
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command.getCommand());
        String stdout = waitForCommandToFinish(channel, command);
        int exitCode = channel.getExitStatus();
        return new RemoteCommandResult(stdout, exitCode);
    } catch (JSchException | IOException ex) {
        LOGGER.log(Level.WARNING, "Error executing remote command " + command, ex);
        throw new ServiceException(RESTCodes.ServiceErrorCode.ERROR_EXECUTING_REMOTE_COMMAND, Level.WARNING, "Error while executing remote command", "Error executing remote command: " + command, ex);
    } catch (RemoteCommandTimeoutException ex) {
        return new RemoteCommandResult("Command time-out: " + ex.getMessage(), 20);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) ServiceException(io.hops.hopsworks.exceptions.ServiceException) Channel(com.jcraft.jsch.Channel) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) ChannelExec(com.jcraft.jsch.ChannelExec) Session(com.jcraft.jsch.Session)

Example 45 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project kylin by apache.

the class SSHClient method scpFileToRemote.

public void scpFileToRemote(String localFile, String remoteTargetDirectory) throws Exception {
    FileInputStream fis = null;
    try {
        logger.info("SCP file " + localFile + " to " + remoteTargetDirectory);
        Session session = newJSchSession();
        session.connect();
        boolean ptimestamp = false;
        // exec 'scp -t rfile' remotely
        String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteTargetDirectory;
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();
        channel.connect();
        if (checkAck(in) != 0) {
            System.exit(0);
        }
        File _lfile = new File(localFile);
        if (ptimestamp) {
            command = "T " + (_lfile.lastModified() / 1000) + " 0";
            // The access time should be sent here,
            // but it is not accessible with JavaAPI ;-<
            command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
            out.write(command.getBytes(StandardCharsets.UTF_8));
            out.flush();
            if (checkAck(in) != 0) {
                throw new Exception(ERROR_IN_CHECK_ACK);
            }
        }
        // send "C0644 filesize filename", where filename should not include '/'
        long filesize = _lfile.length();
        command = "C0644 " + filesize + " ";
        if (localFile.lastIndexOf("/") > 0) {
            command += localFile.substring(localFile.lastIndexOf("/") + 1);
        } else if (localFile.lastIndexOf(File.separator) > 0) {
            command += localFile.substring(localFile.lastIndexOf(File.separator) + 1);
        } else {
            command += localFile;
        }
        command += "\n";
        out.write(command.getBytes(StandardCharsets.UTF_8));
        out.flush();
        if (checkAck(in) != 0) {
            throw new Exception(ERROR_IN_CHECK_ACK);
        }
        // send a content of lfile
        fis = new FileInputStream(localFile);
        byte[] buf = new byte[1024];
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0)
                break;
            // out.flush();
            out.write(buf, 0, len);
        }
        fis.close();
        fis = null;
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        if (checkAck(in) != 0) {
            throw new Exception(ERROR_IN_CHECK_ACK);
        }
        out.close();
        channel.disconnect();
        session.disconnect();
    } catch (Exception e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(fis);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileInputStream(java.io.FileInputStream) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException) File(java.io.File) Session(com.jcraft.jsch.Session)

Aggregations

ChannelExec (com.jcraft.jsch.ChannelExec)99 InputStream (java.io.InputStream)63 IOException (java.io.IOException)59 JSchException (com.jcraft.jsch.JSchException)50 Channel (com.jcraft.jsch.Channel)48 Session (com.jcraft.jsch.Session)31 JSch (com.jcraft.jsch.JSch)29 FileInputStream (java.io.FileInputStream)26 InputStreamReader (java.io.InputStreamReader)26 BufferedReader (java.io.BufferedReader)23 OutputStream (java.io.OutputStream)22 File (java.io.File)17 Properties (java.util.Properties)16 FileOutputStream (java.io.FileOutputStream)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 SftpException (com.jcraft.jsch.SftpException)6 GFacException (org.apache.airavata.gfac.core.GFacException)6 ArrayList (java.util.ArrayList)5 Charset (java.nio.charset.Charset)4 UserInfo (com.jcraft.jsch.UserInfo)3