Search in sources :

Example 11 with JSchException

use of com.jcraft.jsch.JSchException in project DataX by alibaba.

the class SftpHelperImpl method loginFtpServer.

@Override
public void loginFtpServer(String host, String username, String password, int port, int timeout) {
    JSch jsch = new JSch();
    try {
        this.session = jsch.getSession(username, host, port);
        if (this.session == null) {
            throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, "创建ftp连接this.session失败,无法通过sftp与服务器建立链接,请检查主机名和用户名是否正确.");
        }
        this.session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // config.put("PreferredAuthentications", "password");
        this.session.setConfig(config);
        this.session.setTimeout(timeout);
        this.session.connect();
        this.channelSftp = (ChannelSftp) this.session.openChannel("sftp");
        this.channelSftp.connect();
    } catch (JSchException e) {
        if (null != e.getCause()) {
            String cause = e.getCause().toString();
            String unknownHostException = "java.net.UnknownHostException: " + host;
            String illegalArgumentException = "java.lang.IllegalArgumentException: port out of range:" + port;
            String wrongPort = "java.net.ConnectException: Connection refused";
            if (unknownHostException.equals(cause)) {
                String message = String.format("请确认ftp服务器地址是否正确,无法连接到地址为: [%s] 的ftp服务器, errorMessage:%s", host, e.getMessage());
                LOG.error(message);
                throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message, e);
            } else if (illegalArgumentException.equals(cause) || wrongPort.equals(cause)) {
                String message = String.format("请确认连接ftp服务器端口是否正确,错误的端口: [%s], errorMessage:%s", port, e.getMessage());
                LOG.error(message);
                throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message, e);
            }
        } else {
            String message = String.format("与ftp服务器建立连接失败,请检查主机、用户名、密码是否正确, host:%s, port:%s, username:%s, errorMessage:%s", host, port, username, e.getMessage());
            LOG.error(message);
            throw DataXException.asDataXException(FtpWriterErrorCode.FAIL_LOGIN, message);
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties)

Example 12 with JSchException

use of com.jcraft.jsch.JSchException in project GNS by MobilityFirst.

the class Sudo method main.

/**
   *
   * @param arg
   */
public static void main(String[] arg) {
    try {
        JSch jsch = new JSch();
        Session session = SSHClient.authenticateWithKey(jsch, null, null, null);
        UserInfo ui = new UserInfoPrompted();
        session.setUserInfo(ui);
        session.connect();
        String command = JOptionPane.showInputDialog("Enter command, execed with sudo", "printenv SUDO_USER");
        String sudo_pass = null;
        {
            JTextField passwordField = new JPasswordField(8);
            Object[] ob = { passwordField };
            int result = JOptionPane.showConfirmDialog(null, ob, "Enter password for sudo", JOptionPane.OK_CANCEL_OPTION);
            if (result != JOptionPane.OK_OPTION) {
                System.exit(-1);
            }
            sudo_pass = passwordField.getText();
        }
        Channel channel = session.openChannel("exec");
        // man sudo
        //   -S  The -S (stdin) option causes sudo to read the password from the
        //       standard input instead of the terminal device.
        //   -p  The -p (prompt) option allows you to override the default
        //       password prompt and use a custom one.
        ((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
        InputStream in = channel.getInputStream();
        OutputStream out = channel.getOutputStream();
        ((ChannelExec) channel).setErrStream(System.err);
        ((ChannelExec) channel).setPty(true);
        channel.connect();
        out.write((sudo_pass + "\n").getBytes());
        out.flush();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (JSchException | HeadlessException | IOException e) {
        System.out.println(e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) UserInfoPrompted(edu.umass.cs.aws.networktools.UserInfoPrompted) HeadlessException(java.awt.HeadlessException) InputStream(java.io.InputStream) Channel(com.jcraft.jsch.Channel) OutputStream(java.io.OutputStream) UserInfo(com.jcraft.jsch.UserInfo) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) JTextField(javax.swing.JTextField) ChannelExec(com.jcraft.jsch.ChannelExec) IOException(java.io.IOException) HeadlessException(java.awt.HeadlessException) JSchException(com.jcraft.jsch.JSchException) JPasswordField(javax.swing.JPasswordField) Session(com.jcraft.jsch.Session)

Example 13 with JSchException

use of com.jcraft.jsch.JSchException in project opennms by OpenNMS.

the class SftpUrlConnection method connect.

/* (non-Javadoc)
     * @see java.net.URLConnection#connect()
     */
@Override
public void connect() throws IOException {
    if (m_connected) {
        return;
    }
    m_connected = true;
    if (url.getUserInfo() == null) {
        throw new IOException("User credentials required.");
    }
    JSch jsch = new JSch();
    try {
        // TODO: Experimental authentication handling using Private/Public keys
        // FIXME: We can include this property on the request object, for example:
        // <request>
        //   <parameter name='sftp.private-key.location' value='/opt/opennms/etc/private.key'/>
        // </request>
        // http://wiki.jsch.org/index.php?Manual%2FExamples%2FJschPubkeyAuthExample
        String prvkey = System.getProperty("sftp.private-key.location");
        if (prvkey != null) {
            jsch.addIdentity(prvkey);
        }
        int port = url.getPort() > 0 ? url.getPort() : url.getDefaultPort();
        String[] userInfo = url.getUserInfo().split(":");
        m_session = jsch.getSession(userInfo[0], url.getHost(), port);
        if (userInfo.length > 1) {
            m_session.setPassword(userInfo[1]);
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        m_session.setConfig(config);
        m_session.setTimeout(DEFAULT_TIMEOUT);
        m_session.connect();
        m_channel = (ChannelSftp) m_session.openChannel("sftp");
        m_channel.connect();
    } catch (JSchException e) {
        disconnect();
        throw new IOException("Can't connect using " + url + " because " + e.getMessage());
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties)

Example 14 with JSchException

use of com.jcraft.jsch.JSchException in project voltdb by VoltDB.

the class SFTPSession method exec.

public String exec(String command, int timeout) {
    ChannelExec channel = null;
    BufferedReader outStrBufRdr = null;
    BufferedReader errStrBufRdr = null;
    StringBuilder result = new StringBuilder(2048);
    try {
        try {
            channel = (ChannelExec) m_session.openChannel("exec");
        } catch (JSchException jex) {
            throw new SSHException("opening ssh exec channel", jex);
        }
        // Direct stdout output of command
        try {
            InputStream out = channel.getInputStream();
            InputStreamReader outStrRdr = new InputStreamReader(out, "UTF-8");
            outStrBufRdr = new BufferedReader(outStrRdr);
        } catch (IOException ioex) {
            throw new SSHException("geting exec channel input stream", ioex);
        }
        // Direct stderr output of command
        try {
            InputStream err = channel.getErrStream();
            InputStreamReader errStrRdr = new InputStreamReader(err, "UTF-8");
            errStrBufRdr = new BufferedReader(errStrRdr);
        } catch (IOException ioex) {
            throw new SSHException("getting exec channel error stream", ioex);
        }
        channel.setCommand(command);
        StringBuffer stdout = new StringBuffer();
        StringBuffer stderr = new StringBuffer();
        try {
            channel.connect(timeout);
            int retries = timeout / 100;
            while (!channel.isClosed() && retries-- > 0) {
                // Read from both streams here so that they are not blocked,
                // if they are blocked because the buffer is full, channel.isClosed() will never
                // be true.
                int ch;
                try {
                    while (outStrBufRdr.ready() && (ch = outStrBufRdr.read()) > -1) {
                        stdout.append((char) ch);
                    }
                } catch (IOException ioex) {
                    throw new SSHException("capturing '" + command + "' output", ioex);
                }
                try {
                    while (errStrBufRdr.ready() && (ch = errStrBufRdr.read()) > -1) {
                        stderr.append((char) ch);
                    }
                } catch (IOException ioex) {
                    throw new SSHException("capturing '" + command + "' error", ioex);
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ignoreIt) {
                }
            }
            if (retries < 0) {
                throw new SSHException("'" + command + "' timed out");
            }
        } catch (JSchException jex) {
            throw new SSHException("executing '" + command + "'", jex);
        }
        // In case there's still some more stuff in the buffers, read them
        int ch;
        try {
            while ((ch = outStrBufRdr.read()) > -1) {
                stdout.append((char) ch);
            }
        } catch (IOException ioex) {
            throw new SSHException("capturing '" + command + "' output", ioex);
        }
        try {
            while ((ch = errStrBufRdr.read()) > -1) {
                stderr.append((char) ch);
            }
        } catch (IOException ioex) {
            throw new SSHException("capturing '" + command + "' error", ioex);
        }
        if (stderr.length() > 0) {
            throw new SSHException(stderr.toString());
        }
        result.append(stdout.toString());
        result.append(stderr.toString());
    } finally {
        if (outStrBufRdr != null)
            try {
                outStrBufRdr.close();
            } catch (Exception ignoreIt) {
            }
        if (errStrBufRdr != null)
            try {
                errStrBufRdr.close();
            } catch (Exception ignoreIt) {
            }
        if (channel != null && channel.isConnected()) {
            // Shutdown the connection
            channel.disconnect();
        }
    }
    return result.toString();
}
Also used : JSchException(com.jcraft.jsch.JSchException) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) ChannelExec(com.jcraft.jsch.ChannelExec) SftpException(com.jcraft.jsch.SftpException) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException)

Example 15 with JSchException

use of com.jcraft.jsch.JSchException in project che by eclipse.

the class JschSshProcess method start.

// todo how to manage disconnections due to network failures?
@Override
public void start(LineConsumer output) throws MachineException {
    try (PipedOutputStream pipedOS = new PipedOutputStream();
        PipedInputStream pipedIS = new PipedInputStream(pipedOS);
        BufferedReader outReader = new BufferedReader(new InputStreamReader(pipedIS))) {
        exec.setOutputStream(pipedOS);
        exec.setExtOutputStream(pipedOS);
        exec.connect();
        String outLine;
        while ((outLine = outReader.readLine()) != null) {
            output.writeLine(outLine);
        }
    } catch (IOException | JSchException e) {
        throw new MachineException("Ssh machine command execution error:" + e.getLocalizedMessage());
    } finally {
        exec.disconnect();
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) InputStreamReader(java.io.InputStreamReader) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) BufferedReader(java.io.BufferedReader) PipedOutputStream(java.io.PipedOutputStream) PipedInputStream(java.io.PipedInputStream) IOException(java.io.IOException)

Aggregations

JSchException (com.jcraft.jsch.JSchException)40 IOException (java.io.IOException)20 Session (com.jcraft.jsch.Session)19 JSch (com.jcraft.jsch.JSch)14 ChannelSftp (com.jcraft.jsch.ChannelSftp)11 Channel (com.jcraft.jsch.Channel)9 SftpException (com.jcraft.jsch.SftpException)9 ChannelExec (com.jcraft.jsch.ChannelExec)6 InputStream (java.io.InputStream)6 ArrayList (java.util.ArrayList)6 UserInfo (com.jcraft.jsch.UserInfo)5 File (java.io.File)5 MachineException (org.eclipse.che.api.machine.server.exception.MachineException)5 SSHShell (com.microsoft.azure.management.samples.SSHShell)4 Properties (java.util.Properties)4 BufferedReader (java.io.BufferedReader)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileInputStream (java.io.FileInputStream)3 InputStreamReader (java.io.InputStreamReader)3 OutputStream (java.io.OutputStream)3