Search in sources :

Example 51 with JSch

use of com.jcraft.jsch.JSch in project structr by structr.

the class SSHTest method setupSftpClient.

/**
 * Creates an FTP client, a backend user and logs this user in.
 *
 * @param username
 * @return
 */
protected ChannelSftp setupSftpClient(final String username, final String password) {
    try (final Tx tx = app.tx()) {
        ftpUser = createFTPUser(username, password);
        tx.success();
    } catch (FrameworkException fex) {
        logger.error("Unable to create SFTP user", fex);
    }
    JSch jsch = new JSch();
    try {
        final Session session = jsch.getSession(username, host, sshPort);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect(1000);
        final Channel channel = session.openChannel("sftp");
        channel.connect(1000);
        return (ChannelSftp) channel;
    } catch (JSchException ex) {
        ex.printStackTrace();
    }
    return null;
}
Also used : JSchException(com.jcraft.jsch.JSchException) ChannelSftp(com.jcraft.jsch.ChannelSftp) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Channel(com.jcraft.jsch.Channel) JSch(com.jcraft.jsch.JSch) Session(com.jcraft.jsch.Session)

Example 52 with JSch

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

the class SshCache method getSession.

/**
 * Gets a session from the cache or establishes a new session if necessary
 *
 * @param host
 *            to connect to
 * @param port
 *            to use for session (-1 == use standard port)
 * @param username
 *            for the session to use
 * @param userPassword
 *            to use for authentication (optional)
 * @param pemFile
 *            File to use for public key authentication
 * @param pemPassword
 *            to use for accessing the pemFile (optional)
 * @param passFile
 *            to store credentials
 * @param allowedAgentUse
 *            Whether to communicate with an agent for authentication
 * @return session or null if not successful
 * @throws IOException if something goes wrong
 */
public Session getSession(String host, int port, String username, String userPassword, File pemFile, String pemPassword, File passFile, boolean allowedAgentUse) throws IOException {
    Checks.checkNotNull(host, "host");
    Checks.checkNotNull(username, "user");
    Entry entry = getCacheEntry(username, host, port);
    Session session = null;
    if (entry != null) {
        session = entry.getSession();
    }
    if (session == null || !session.isConnected()) {
        Message.verbose(":: SSH :: connecting to " + host + "...");
        try {
            JSch jsch = new JSch();
            if (port != -1) {
                session = jsch.getSession(username, host, port);
            } else {
                session = jsch.getSession(username, host);
            }
            if (allowedAgentUse) {
                attemptAgentUse(jsch);
            }
            if (pemFile != null) {
                jsch.addIdentity(pemFile.getAbsolutePath(), pemPassword);
            }
            session.setUserInfo(new CfUserInfo(host, username, userPassword, pemFile, pemPassword, passFile));
            session.setDaemonThread(true);
            Properties config = new Properties();
            config.setProperty("PreferredAuthentications", "publickey,keyboard-interactive,password");
            session.setConfig(config);
            session.connect();
            Message.verbose(":: SSH :: connected to " + host + "!");
            setSession(username, host, port, session);
        } catch (JSchException e) {
            if (passFile != null && passFile.exists()) {
                passFile.delete();
            }
            throw new IOException(e.getMessage(), e);
        }
    }
    return session;
}
Also used : JSchException(com.jcraft.jsch.JSchException) IOException(java.io.IOException) JSch(com.jcraft.jsch.JSch) Properties(java.util.Properties) Session(com.jcraft.jsch.Session)

Example 53 with JSch

use of com.jcraft.jsch.JSch in project Android-Password-Store by zeapo.

the class GitOperation method executeAfterAuthentication.

/**
 * Executes the GitCommand in an async task after creating the authentication
 *
 * @param connectionMode the server-connection mode
 * @param username       the username
 * @param sshKey         the ssh-key file
 * @param showError      show the passphrase edit text in red
 */
private void executeAfterAuthentication(final String connectionMode, final String username, @Nullable final File sshKey, final boolean showError) {
    if (connectionMode.equalsIgnoreCase("ssh-key")) {
        if (sshKey == null || !sshKey.exists()) {
            new AlertDialog.Builder(callingActivity).setMessage(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_text)).setTitle(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_title)).setPositiveButton(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_import), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int id) {
                    try {
                        // Ask the UserPreference to provide us with the ssh-key
                        // onResult has to be handled by the callingActivity
                        Intent intent = new Intent(callingActivity.getApplicationContext(), UserPreference.class);
                        intent.putExtra("operation", "get_ssh_key");
                        callingActivity.startActivityForResult(intent, GET_SSH_KEY_FROM_CLONE);
                    } catch (Exception e) {
                        System.out.println("Exception caught :(");
                        e.printStackTrace();
                    }
                }
            }).setNegativeButton(callingActivity.getResources().getString(R.string.ssh_preferences_dialog_generate), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        // Duplicated code
                        Intent intent = new Intent(callingActivity.getApplicationContext(), UserPreference.class);
                        intent.putExtra("operation", "make_ssh_key");
                        callingActivity.startActivityForResult(intent, GET_SSH_KEY_FROM_CLONE);
                    } catch (Exception e) {
                        System.out.println("Exception caught :(");
                        e.printStackTrace();
                    }
                }
            }).setNeutralButton(callingActivity.getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // Finish the blank GitActivity so user doesn't have to press back
                    callingActivity.finish();
                }
            }).show();
        } else {
            LayoutInflater layoutInflater = LayoutInflater.from(callingActivity.getApplicationContext());
            @SuppressLint("InflateParams") final View dialogView = layoutInflater.inflate(R.layout.git_passphrase_layout, null);
            final EditText passphrase = (EditText) dialogView.findViewById(R.id.sshkey_passphrase);
            final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(callingActivity.getApplicationContext());
            final String sshKeyPassphrase = settings.getString("ssh_key_passphrase", null);
            if (showError) {
                passphrase.setError("Wrong passphrase");
            }
            JSch jsch = new JSch();
            try {
                final KeyPair keyPair = KeyPair.load(jsch, callingActivity.getFilesDir() + "/.ssh_key");
                if (keyPair.isEncrypted()) {
                    if (sshKeyPassphrase != null && !sshKeyPassphrase.isEmpty()) {
                        if (keyPair.decrypt(sshKeyPassphrase)) {
                            // Authenticate using the ssh-key and then execute the command
                            setAuthentication(sshKey, username, sshKeyPassphrase).execute();
                        } else {
                            // call back the method
                            executeAfterAuthentication(connectionMode, username, sshKey, true);
                        }
                    } else {
                        new AlertDialog.Builder(callingActivity).setTitle(callingActivity.getResources().getString(R.string.passphrase_dialog_title)).setMessage(callingActivity.getResources().getString(R.string.passphrase_dialog_text)).setView(dialogView).setPositiveButton(callingActivity.getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                if (keyPair.decrypt(passphrase.getText().toString())) {
                                    boolean rememberPassphrase = ((CheckBox) dialogView.findViewById(R.id.sshkey_remember_passphrase)).isChecked();
                                    if (rememberPassphrase) {
                                        settings.edit().putString("ssh_key_passphrase", passphrase.getText().toString()).apply();
                                    }
                                    // Authenticate using the ssh-key and then execute the command
                                    setAuthentication(sshKey, username, passphrase.getText().toString()).execute();
                                } else {
                                    settings.edit().putString("ssh_key_passphrase", null).apply();
                                    // call back the method
                                    executeAfterAuthentication(connectionMode, username, sshKey, true);
                                }
                            }
                        }).setNegativeButton(callingActivity.getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                            // Do nothing.
                            }
                        }).show();
                    }
                } else {
                    setAuthentication(sshKey, username, "").execute();
                }
            } catch (JSchException e) {
                new AlertDialog.Builder(callingActivity).setTitle("Unable to open the ssh-key").setMessage("Please check that it was imported.").setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).show();
            }
        }
    } else {
        final EditText password = new EditText(callingActivity);
        password.setHint("Password");
        password.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        new AlertDialog.Builder(callingActivity).setTitle(callingActivity.getResources().getString(R.string.passphrase_dialog_title)).setMessage(callingActivity.getResources().getString(R.string.password_dialog_text)).setView(password).setPositiveButton(callingActivity.getResources().getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                // authenticate using the user/pwd and then execute the command
                setAuthentication(username, password.getText().toString()).execute();
            }
        }).setNegativeButton(callingActivity.getResources().getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
            // Do nothing.
            }
        }).show();
    }
}
Also used : EditText(android.widget.EditText) JSchException(com.jcraft.jsch.JSchException) AlertDialog(android.support.v7.app.AlertDialog) KeyPair(com.jcraft.jsch.KeyPair) DialogInterface(android.content.DialogInterface) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) JSch(com.jcraft.jsch.JSch) View(android.view.View) JSchException(com.jcraft.jsch.JSchException) SuppressLint(android.annotation.SuppressLint) LayoutInflater(android.view.LayoutInflater) SuppressLint(android.annotation.SuppressLint) UserPreference(com.zeapo.pwdstore.UserPreference)

Example 54 with JSch

use of com.jcraft.jsch.JSch in project litle-sdk-for-java by Vantiv.

the class Communication method sendLitleRequestFileToSFTP.

/**
 * This method sends the request file to Litle's server sFTP
 * @param requestFile
 * @param configuration
 * @throws IOException
 */
public void sendLitleRequestFileToSFTP(File requestFile, Properties configuration) throws IOException {
    String username = configuration.getProperty("sftpUsername");
    String password = configuration.getProperty("sftpPassword");
    String hostname = configuration.getProperty("batchHost");
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = null;
    Session session = null;
    try {
        jsch = new JSch();
        session = jsch.getSession(username, hostname);
        session.setConfig(config);
        session.setPassword(password);
        session.connect();
    } catch (JSchException e) {
        throw new LitleBatchException("Exception connection to Litle", e);
    }
    Channel channel = null;
    try {
        channel = session.openChannel("sftp");
        channel.connect();
    } catch (JSchException e) {
        throw new LitleBatchException("Exception connection to Litle", e);
    }
    ChannelSftp sftp = (ChannelSftp) channel;
    boolean printxml = configuration.getProperty("printxml") != null && configuration.getProperty("printxml").equalsIgnoreCase("true");
    if (printxml) {
        BufferedReader reader = new BufferedReader(new FileReader(requestFile));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
    try {
        sftp.put(requestFile.getAbsolutePath(), "inbound/" + requestFile.getName() + ".prg");
        sftp.rename("inbound/" + requestFile.getName() + ".prg", "inbound/" + requestFile.getName() + ".asc");
    } catch (SftpException e) {
        throw new LitleBatchException("Exception SFTP operation", e);
    }
    channel.disconnect();
    session.disconnect();
}
Also used : JSchException(com.jcraft.jsch.JSchException) Properties(java.util.Properties) Channel(com.jcraft.jsch.Channel) SftpException(com.jcraft.jsch.SftpException) Properties(java.util.Properties) JSch(com.jcraft.jsch.JSch) ChannelSftp(com.jcraft.jsch.ChannelSftp) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Session(com.jcraft.jsch.Session)

Example 55 with JSch

use of com.jcraft.jsch.JSch in project opentest by mcdcorp.

the class PutToSftp method run.

@Override
public void run() {
    super.run();
    String sftpHost = this.readStringArgument("sftpHost");
    Integer sftpPort = this.readIntArgument("sftpPort", 22);
    String userName = this.readStringArgument("userName");
    String password = this.readStringArgument("password");
    String sourceDir = this.readStringArgument("sourceDir");
    String sourceFileName = this.readStringArgument("sourceFile");
    String destinationDir = this.readStringArgument("destinationDir");
    String destinationFileName = this.readStringArgument("destinationFile", sourceFileName);
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(userName, sftpHost, sftpPort);
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        this.log.trace("Connected to SFTP host");
        channel = session.openChannel("sftp");
        channel.connect();
        this.log.trace("The SFTP channel was opened and connected");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(destinationDir);
        File sourceFile = new File(sourceDir, sourceFileName);
        FileInputStream inputStream = new FileInputStream(sourceFile);
        channelSftp.put(inputStream, destinationFileName);
        inputStream.close();
    } catch (Exception ex) {
        throw new RuntimeException("SFTP transfer failed", ex);
    } finally {
        if (channelSftp != null) {
            channelSftp.exit();
        }
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
Also used : Channel(com.jcraft.jsch.Channel) JSch(com.jcraft.jsch.JSch) FileInputStream(java.io.FileInputStream) ChannelSftp(com.jcraft.jsch.ChannelSftp) File(java.io.File) Session(com.jcraft.jsch.Session)

Aggregations

JSch (com.jcraft.jsch.JSch)130 Session (com.jcraft.jsch.Session)72 JSchException (com.jcraft.jsch.JSchException)51 IOException (java.io.IOException)50 Channel (com.jcraft.jsch.Channel)35 File (java.io.File)29 InputStream (java.io.InputStream)29 Properties (java.util.Properties)27 ChannelExec (com.jcraft.jsch.ChannelExec)26 ChannelSftp (com.jcraft.jsch.ChannelSftp)22 KeyPair (com.jcraft.jsch.KeyPair)19 BufferedReader (java.io.BufferedReader)16 UserInfo (com.jcraft.jsch.UserInfo)15 InputStreamReader (java.io.InputStreamReader)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 FileInputStream (java.io.FileInputStream)11 OutputStream (java.io.OutputStream)11 SftpException (com.jcraft.jsch.SftpException)10 FS (org.eclipse.jgit.util.FS)8 FileOutputStream (java.io.FileOutputStream)7