Search in sources :

Example 6 with JSch

use of com.jcraft.jsch.JSch 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 7 with JSch

use of com.jcraft.jsch.JSch in project quickstarts by jboss-switchyard.

the class CamelFtpBindingTest method startUp.

@BeforeClass
public static void startUp() throws Exception {
    FtpServerFactory serverFactory = new FtpServerFactory();
    ListenerFactory listenerFactory = new ListenerFactory();
    listenerFactory.setPort(2222);
    serverFactory.addListener("default", listenerFactory.createListener());
    ListenerFactory sslListenerFactory = new ListenerFactory();
    sslListenerFactory.setPort(2221);
    SslConfigurationFactory ssl = new SslConfigurationFactory();
    ssl.setKeystoreFile(new File("src/test/resources/ftpserver.jks"));
    ssl.setKeystorePassword("password");
    sslListenerFactory.setSslConfiguration(ssl.createSslConfiguration());
    // Setting it to true will not read the file
    sslListenerFactory.setImplicitSsl(false);
    serverFactory.addListener("ftps", sslListenerFactory.createListener());
    PropertiesUserManagerFactory managerFactory = new PropertiesUserManagerFactory();
    managerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
    managerFactory.setFile(new File("src/test/resources/users.properties"));
    UserManager createUserManager = managerFactory.createUserManager();
    serverFactory.setUserManager(createUserManager);
    NativeFileSystemFactory fileSystemFactory = new NativeFileSystemFactory();
    fileSystemFactory.setCreateHome(true);
    serverFactory.setFileSystem(fileSystemFactory);
    File file = new File("target/ftp/ftps");
    file.mkdirs();
    file = new File("target/ftp/sftp");
    file.mkdirs();
    ftpServer = serverFactory.createServer();
    ftpServer.start();
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setPort(2220);
    sshd.setKeyPairProvider(createTestKeyPairProvider("src/test/resources/hostkey.pem"));
    sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystem.Factory()));
    sshd.setCommandFactory(new ScpCommandFactory());
    sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
    sshd.start();
    JSch sch = new JSch();
    Session session = sch.getSession("camel", "localhost", 2220);
    session.setUserInfo(new SimpleUserInfo("isMyFriend"));
    session.connect();
    ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
    c.connect();
    System.out.println("Home: " + c.getHome());
    c.chmod(777, ".");
    c.chmod(777, "target");
    c.chmod(777, "target/ftp");
    c.chmod(777, "target/ftp/sftp");
    c.disconnect();
    session.disconnect();
}
Also used : FtpServerFactory(org.apache.ftpserver.FtpServerFactory) NativeFileSystemFactory(org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory) NativeFileSystemFactory(org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory) ScpCommandFactory(org.apache.sshd.server.command.ScpCommandFactory) PropertiesUserManagerFactory(org.apache.ftpserver.usermanager.PropertiesUserManagerFactory) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory) SslConfigurationFactory(org.apache.ftpserver.ssl.SslConfigurationFactory) FtpServerFactory(org.apache.ftpserver.FtpServerFactory) NamedFactory(org.apache.sshd.common.NamedFactory) JSch(com.jcraft.jsch.JSch) ClearTextPasswordEncryptor(org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor) SshServer(org.apache.sshd.SshServer) ScpCommandFactory(org.apache.sshd.server.command.ScpCommandFactory) ChannelSftp(com.jcraft.jsch.ChannelSftp) Command(org.apache.sshd.server.Command) UserManager(org.apache.ftpserver.ftplet.UserManager) PropertiesUserManagerFactory(org.apache.ftpserver.usermanager.PropertiesUserManagerFactory) SslConfigurationFactory(org.apache.ftpserver.ssl.SslConfigurationFactory) File(java.io.File) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory) ServerSession(org.apache.sshd.server.session.ServerSession) Session(com.jcraft.jsch.Session) BeforeClass(org.junit.BeforeClass)

Example 8 with JSch

use of com.jcraft.jsch.JSch in project KeyBox by skavanagh.

the class AuthKeysAction method generateUserKey.

/**
	 * generates public private key from passphrase
	 *  
	 * @param username username to set in public key comment
	 * @param keyname keyname to set in public key comment
	 * @return public key
	 */
public String generateUserKey(String username, String keyname) {
    //set key type
    int type = KeyPair.RSA;
    if ("dsa".equals(SSHUtil.KEY_TYPE)) {
        type = KeyPair.DSA;
    } else if ("ecdsa".equals(SSHUtil.KEY_TYPE)) {
        type = KeyPair.ECDSA;
    }
    JSch jsch = new JSch();
    String pubKey = null;
    try {
        KeyPair keyPair = KeyPair.genKeyPair(jsch, type, SSHUtil.KEY_LENGTH);
        OutputStream os = new ByteArrayOutputStream();
        keyPair.writePrivateKey(os, publicKey.getPassphrase().getBytes());
        //set private key
        servletRequest.getSession().setAttribute(PVT_KEY, EncryptionUtil.encrypt(os.toString()));
        os = new ByteArrayOutputStream();
        keyPair.writePublicKey(os, username + "@" + keyname);
        pubKey = os.toString();
        keyPair.dispose();
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }
    return pubKey;
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JSch(com.jcraft.jsch.JSch)

Example 9 with JSch

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

the class SFTPUpload method authenticateSftp.

private static ChannelSftp authenticateSftp(String user, String host, File keyFile) throws JSchException {
    Session session;
    Channel channel;
    JSch jsch = new JSch();
    session = SSHClient.authenticateWithKey(jsch, user, host, keyFile);
    session.connect();
    channel = session.openChannel("sftp");
    channel.connect();
    return (ChannelSftp) channel;
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) Channel(com.jcraft.jsch.Channel) JSch(com.jcraft.jsch.JSch) Session(com.jcraft.jsch.Session)

Example 10 with JSch

use of com.jcraft.jsch.JSch 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)

Aggregations

JSch (com.jcraft.jsch.JSch)35 Session (com.jcraft.jsch.Session)23 JSchException (com.jcraft.jsch.JSchException)16 IOException (java.io.IOException)14 Channel (com.jcraft.jsch.Channel)8 ChannelExec (com.jcraft.jsch.ChannelExec)7 File (java.io.File)7 InputStream (java.io.InputStream)7 ChannelSftp (com.jcraft.jsch.ChannelSftp)6 FileInputStream (java.io.FileInputStream)6 OutputStream (java.io.OutputStream)6 UserInfo (com.jcraft.jsch.UserInfo)5 Properties (java.util.Properties)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 KeyPair (com.jcraft.jsch.KeyPair)2 SftpException (com.jcraft.jsch.SftpException)2 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)2 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)2 UserInfoPrompted (edu.umass.cs.aws.networktools.UserInfoPrompted)2 HeadlessException (java.awt.HeadlessException)2