Search in sources :

Example 26 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project nimbus by nimbus-org.

the class SCPClientImpl method get.

public File get(String remote, String local) throws SCPException {
    if (jsch == null) {
        throw new SCPException(scpClientFactoryServiceName, "Connection is not established!");
    }
    if (session == null) {
        throw new SCPException(scpClientFactoryServiceName, "It is not authenticated!");
    }
    if (remote == null || remote.length() == 0) {
        throw new SCPException(scpClientFactoryServiceName, "Path is null.");
    }
    Channel channel = null;
    final String cmd = "scp -f " + remote;
    File localFile = null;
    try {
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);
        OutputStream os = channel.getOutputStream();
        InputStream is = channel.getInputStream();
        channel.connect();
        byte[] buf = new byte[1024];
        buf[0] = 0;
        os.write(buf, 0, 1);
        os.flush();
        int c = checkAck(is);
        if (c == -1) {
            throw new IOException("Remote SCP terminated unexpectedly.");
        }
        is.read(buf, 0, 5);
        long fileSize = 0L;
        while (true) {
            if (is.read(buf, 0, 1) < 0) {
                throw new SCPException(scpClientFactoryServiceName, "Unexpected EOF.");
            }
            if (buf[0] == ' ') {
                break;
            }
            fileSize = fileSize * 10L + (long) (buf[0] - '0');
        }
        String fileName = null;
        for (int i = 0; ; i++) {
            is.read(buf, i, 1);
            if (buf[i] == (byte) 0x0a) {
                fileName = new String(buf, 0, i);
                break;
            }
        }
        buf[0] = 0;
        os.write(buf, 0, 1);
        os.flush();
        if (local == null) {
            localFile = homeDir == null ? new File(fileName) : new File(homeDir, fileName);
        } else {
            localFile = new File(local);
            if (homeDir != null && !localFile.isAbsolute()) {
                localFile = new File(homeDir, local);
            }
        }
        FileOutputStream fos = new FileOutputStream(localFile);
        try {
            int readLen = 0;
            while (true) {
                if (buf.length < fileSize) {
                    readLen = buf.length;
                } else {
                    readLen = (int) fileSize;
                }
                readLen = is.read(buf, 0, readLen);
                if (readLen < 0) {
                    throw new SCPException(scpClientFactoryServiceName, "Unexpected EOF.");
                }
                fos.write(buf, 0, readLen);
                fileSize -= readLen;
                if (fileSize == 0L) {
                    break;
                }
            }
        } finally {
            fos.close();
            fos = null;
        }
        checkAck(is);
        buf[0] = 0;
        os.write(buf, 0, 1);
        os.flush();
    } catch (IOException e) {
        throw new SCPException(scpClientFactoryServiceName, "It failed to mget! from=" + remote + ", to=" + localFile, e);
    } catch (JSchException e) {
        throw new SCPException(scpClientFactoryServiceName, "It failed to mget! from=" + remote + ", to=" + localFile, e);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
    return localFile;
}
Also used : JSchException(com.jcraft.jsch.JSchException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SCPException(jp.ossc.nimbus.service.scp.SCPException) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec) FileOutputStream(java.io.FileOutputStream) File(java.io.File) RecurciveSearchFile(jp.ossc.nimbus.io.RecurciveSearchFile)

Example 27 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project nimbus by nimbus-org.

the class SCPClientImpl method put.

public void put(String local, String remote, String mode) throws SCPException {
    if (jsch == null) {
        throw new SCPException(scpClientFactoryServiceName, "Connection is not established!");
    }
    if (session == null) {
        throw new SCPException(scpClientFactoryServiceName, "It is not authenticated!");
    }
    File localFile = null;
    FileInputStream fis = null;
    OutputStream os = null;
    Channel channel = null;
    try {
        localFile = new File(local);
        if (homeDir != null && !localFile.isAbsolute()) {
            localFile = new File(homeDir, local);
        }
        if (!localFile.exists()) {
            throw new SCPException(scpClientFactoryServiceName, "File not exists! path=" + local);
        }
        StringBuilder command = new StringBuilder("scp -p -t ").append(remote);
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command.toString());
        os = channel.getOutputStream();
        InputStream is = channel.getInputStream();
        channel.connect();
        if (checkAck(is) != 0) {
            throw new IOException("Remote SCP terminated unexpectedly.");
        }
        command.setLength(0);
        command.append("T ").append(localFile.lastModified() / 1000).append(" 0 ");
        command.append(localFile.lastModified() / 1000).append(" 0\n");
        os.write(command.toString().getBytes());
        os.flush();
        if (checkAck(is) != 0) {
            throw new IOException("Remote SCP terminated unexpectedly.");
        }
        command.setLength(0);
        command.append("C");
        if (mode == null) {
            mode = "0644";
        }
        command.append(" ").append(localFile.length()).append(" ");
        if (localFile.getParentFile() != null) {
            command.append(localFile.getName());
        }
        command.append("\n");
        os.write(command.toString().getBytes());
        os.flush();
        if (checkAck(is) != 0) {
            throw new IOException("Remote SCP terminated unexpectedly.");
        }
        fis = new FileInputStream(localFile);
        int length = 0;
        byte[] buf = new byte[1024];
        while ((length = fis.read(buf)) != -1) {
            os.write(buf, 0, length);
        }
        buf[0] = 0;
        os.write(buf, 0, 1);
        os.flush();
        if (checkAck(is) != 0) {
            throw new IOException("Remote SCP terminated unexpectedly.");
        }
    } catch (IOException e) {
        throw new SCPException(scpClientFactoryServiceName, "It failed to put! file=" + localFile, e);
    } catch (JSchException e) {
        throw new SCPException(scpClientFactoryServiceName, "It failed to put! file=" + localFile, e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
            }
        }
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SCPException(jp.ossc.nimbus.service.scp.SCPException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Channel(com.jcraft.jsch.Channel) IOException(java.io.IOException) File(java.io.File) RecurciveSearchFile(jp.ossc.nimbus.io.RecurciveSearchFile) FileInputStream(java.io.FileInputStream) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 28 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project ant-ivy by apache.

the class Scp method get.

/**
 * Download a file from the remote server into an OutputStream
 *
 * @param remoteFile
 *            Path and name of the remote file.
 * @param localTarget
 *            OutputStream to store the data.
 * @throws IOException
 *             in case of network problems
 * @throws RemoteScpException
 *             in case of problems on the target system (connection ok)
 */
@SuppressWarnings("unused")
public void get(String remoteFile, OutputStream localTarget) throws IOException, RemoteScpException {
    ChannelExec channel = null;
    if (remoteFile == null || localTarget == null) {
        throw new IllegalArgumentException("Null argument.");
    }
    String cmd = "scp -p -f " + remoteFile;
    try {
        channel = getExecChannel();
        channel.setCommand(cmd);
        receiveStream(channel, remoteFile, localTarget);
        channel.disconnect();
    } catch (JSchException e) {
        if (channel != null) {
            channel.disconnect();
        }
        throw new IOException("Error during SCP transfer. " + e.getMessage(), e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec)

Example 29 with ChannelExec

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

the class SshFenceByTcpPort method execCommand.

/**
 * Execute a command through the ssh session, pumping its
 * stderr and stdout to our own logs.
 */
private int execCommand(Session session, String cmd) throws JSchException, InterruptedException, IOException {
    LOG.debug("Running cmd: " + cmd);
    ChannelExec exec = null;
    try {
        exec = (ChannelExec) session.openChannel("exec");
        exec.setCommand(cmd);
        exec.setInputStream(null);
        exec.connect();
        // Pump stdout of the command to our WARN logs
        StreamPumper outPumper = new StreamPumper(LOG, cmd + " via ssh", exec.getInputStream(), StreamPumper.StreamType.STDOUT);
        outPumper.start();
        // Pump stderr of the command to our WARN logs
        StreamPumper errPumper = new StreamPumper(LOG, cmd + " via ssh", exec.getErrStream(), StreamPumper.StreamType.STDERR);
        errPumper.start();
        outPumper.join();
        errPumper.join();
        return exec.getExitStatus();
    } finally {
        cleanup(exec);
    }
}
Also used : ChannelExec(com.jcraft.jsch.ChannelExec)

Example 30 with ChannelExec

use of com.jcraft.jsch.ChannelExec in project agileway by fangjinuo.

the class SshCommandTest method executeAndDump.

private void executeAndDump(Session session, String command) throws JSchException, IOException {
    logger.info("\n====== start execute: {} ======", command);
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.connect();
    logger.info("isClosed: {}", channel.isClosed());
    logger.info("isConnected: {}", channel.isConnected());
    InputStream errorStream = channel.getErrStream();
    InputStream outStream = channel.getInputStream();
    String error = IOs.readAsString(errorStream);
    logger.info(error);
    String content = IOs.readAsString(outStream);
    logger.info(content);
    channel.disconnect();
    logger.info("====== finish execute: {} ======", command);
}
Also used : InputStream(java.io.InputStream) ChannelExec(com.jcraft.jsch.ChannelExec)

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