Java Code Examples for com.jcraft.jsch.JSch

The following examples show how to use com.jcraft.jsch.JSch. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: vividus   Source File: JSchExecutor.java    License: Apache License 2.0 7 votes vote down vote up
private JSch createJSchInstance(ServerConfiguration server) throws AgentProxyException, JSchException
{
    JSch jSch = new JSch();
    if (server.isAgentForwarding())
    {
        Connector connector = ConnectorFactory.getDefault().createConnector();
        jSch.setIdentityRepository(new RemoteIdentityRepository(connector));
    }
    else if (server.getPrivateKey() != null && server.getPublicKey() != null)
    {
        String passphrase = server.getPassphrase();
        jSch.addIdentity("default", getBytes(server.getPrivateKey()), getBytes(server.getPublicKey()),
                passphrase != null ? getBytes(passphrase) : null);
    }
    return jSch;
}
 
Example 2
Source Project: vividus   Source File: JSchExecutorTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void shouldExecuteSuccessfullyWithAgentForwarding() throws Exception
{
    ServerConfiguration server = getDefaultServerConfiguration();
    server.setAgentForwarding(true);
    JSch jSch = mock(JSch.class);
    whenNew(JSch.class).withNoArguments().thenReturn(jSch);
    mockStatic(ConnectorFactory.class);
    ConnectorFactory connectorFactory = mock(ConnectorFactory.class);
    when(ConnectorFactory.getDefault()).thenReturn(connectorFactory);
    Connector connector = mock(Connector.class);
    when(connectorFactory.createConnector()).thenReturn(connector);
    RemoteIdentityRepository remoteIdentityRepository = mock(RemoteIdentityRepository.class);
    whenNew(RemoteIdentityRepository.class).withArguments(connector).thenReturn(remoteIdentityRepository);
    doNothing().when(jSch).setIdentityRepository(remoteIdentityRepository);
    Session session = mock(Session.class);
    when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session);
    ChannelExec channelExec = mockChannelOpening(session);
    SshOutput actual = new TestJSchExecutor().execute(server, COMMANDS);
    assertEquals(SSH_OUTPUT, actual);
    InOrder ordered = inOrder(jSch, session, channelExec);
    ordered.verify(jSch).setIdentityRepository(remoteIdentityRepository);
    verifyFullConnection(ordered, server, session, channelExec);
}
 
Example 3
Source Project: vividus   Source File: JSchExecutorTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void shouldFailOnChannelOpeningError() throws Exception
{
    ServerConfiguration server = getDefaultServerConfiguration();
    server.setPrivateKey(null);
    JSch jSch = mock(JSch.class);
    whenNew(JSch.class).withNoArguments().thenReturn(jSch);
    Session session = mock(Session.class);
    when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session);
    JSchException jSchException = new JSchException();
    when(session.openChannel(EXEC)).thenThrow(jSchException);
    CommandExecutionException exception = assertThrows(CommandExecutionException.class,
        () -> new TestJSchExecutor().execute(server, COMMANDS));
    assertEquals(jSchException, exception.getCause());
    InOrder ordered = inOrder(jSch, session);
    verifySessionConnection(ordered, server, session);
    ordered.verify(session).openChannel(EXEC);
    ordered.verify(session).disconnect();
}
 
Example 4
Source Project: blueocean-plugin   Source File: GitReadSaveTest.java    License: MIT License 6 votes vote down vote up
private void startSSH(@Nullable User u) throws Exception {
    if (sshd == null) {
        // Set up an SSH server with access to a git repo
        User user;
        if(u == null) {
            user = login();
        } else {
            user = u;
        }
        final BasicSSHUserPrivateKey key = UserSSHKeyManager.getOrCreate(user);
        final JSch jsch = new JSch();
        final KeyPair pair = KeyPair.load(jsch, key.getPrivateKey().getBytes(), null);

        File keyFile = new File(System.getProperty("TEST_SSH_SERVER_KEY_FILE", File.createTempFile("hostkey", "ser").getCanonicalPath()));
        int port = Integer.parseInt(System.getProperty("TEST_SSH_SERVER_PORT", "0"));
        boolean allowLocalUser = Boolean.getBoolean("TEST_SSH_SERVER_ALLOW_LOCAL");
        String userPublicKey = Base64.encode(pair.getPublicKeyBlob());
        sshd = new SSHServer(repoForSSH.getRoot(), keyFile, port, allowLocalUser, ImmutableMap.of("bob", userPublicKey), true);
        // Go, go, go
        sshd.start();
    }
}
 
Example 5
Source Project: hop   Source File: SftpClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a folder under an existing folder given an absolute path.
 */
@Test
public void folderCreation_Absolute_Simple() throws Exception {
  System.setProperty( SftpClient.ENV_PARAM_USERAUTH_GSSAPI, "yes" );
  SftpClient client = spy( new SftpClient( server, port, username ) {
    @Override
    JSch createJSch() {
      return jSch;
    }
  } );

  doReturn( true ).when( client ).folderExists( "/var" );
  doReturn( true ).when( client ).folderExists( "/var/ftproot" );

  client.login( password );
  client.createFolder( "/var/ftproot/myfolder" );

  verify( channel, times( 1 ) ).mkdir( anyString() );
  verify( channel, times( 1 ) ).mkdir( "/var/ftproot/myfolder" );
}
 
Example 6
Source Project: hop   Source File: SftpClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a folder under an existing folder given an absolute path.
 * The specified folder ends with a slash.
 */
@Test
public void folderCreation_Absolute_TrailingSlash() throws Exception {
  System.setProperty( SftpClient.ENV_PARAM_USERAUTH_GSSAPI, "yes" );
  SftpClient client = spy( new SftpClient( server, port, username ) {
    @Override
    JSch createJSch() {
      return jSch;
    }
  } );

  doReturn( true ).when( client ).folderExists( "/var" );
  doReturn( true ).when( client ).folderExists( "/var/ftproot" );

  client.login( password );
  client.createFolder( "/var/ftproot/myfolder/" );

  verify( channel, times( 1 ) ).mkdir( anyString() );
  verify( channel, times( 1 ) ).mkdir( "/var/ftproot/myfolder" );
}
 
Example 7
Source Project: flow-platform-x   Source File: CipherHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static SimpleKeyPair gen(String email) {
    try (ByteArrayOutputStream pubKeyOS = new ByteArrayOutputStream()) {
        try (ByteArrayOutputStream prvKeyOS = new ByteArrayOutputStream()) {
            JSch jsch = new JSch();
            SimpleKeyPair rsa = new SimpleKeyPair();

            KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
            kpair.writePrivateKey(prvKeyOS);
            kpair.writePublicKey(pubKeyOS, email);

            rsa.setPublicKey(pubKeyOS.toString());
            rsa.setPrivateKey(prvKeyOS.toString());

            kpair.dispose();
            return rsa;
        }
    } catch (IOException | JSchException e) {
        throw new StatusException("Unable to generate RSA key pair");
    }
}
 
Example 8
/**
 * Returns a new session created with given {@code host}, {@code port}, {@code username}, {@code
 * password}, {@code privateKey} and optional {@code passphrase}.
 *
 * @throws JSchException if {@code username} or {@code host} are invalid, or if {@code passphrase}
 *     is not right.
 */
public static Session createSession(
    String host, int port, String username, String password, String privateKey, String passphrase)
    throws JSchException {
  JSch jsch = new JSch();

  if (privateKey != null) {
    jsch.addIdentity(privateKey, passphrase);
  }

  Session session = jsch.getSession(username, host, port);
  session.setPassword(password);
  session.setConfig("StrictHostKeyChecking", "no");

  return session;
}
 
Example 9
Source Project: mOrgAnd   Source File: KeySettingActivity.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String GetKeyprint(String keyfilePath, String passphrase) {
    try {
        KeyPair keyPair = KeyPair.load(new JSch(), keyfilePath);
        if (!passphrase.isEmpty() && keyPair.isEncrypted())
            keyPair.decrypt(passphrase);
        else if (passphrase.isEmpty() && keyPair.isEncrypted()) {
            Toast.makeText(this, R.string.error_key_need_pass, Toast.LENGTH_LONG).show();
            return "";
        }
        String fingerprint = keyPair.getFingerPrint();
        keyPair.dispose();
        return fingerprint;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 10
Source Project: app-runner   Source File: SystemInfo.java    License: MIT License 6 votes vote down vote up
private static List<String> getPublicKeys() throws Exception {
    return new JschConfigSessionFactory() {
        @Override
        protected void configure(OpenSshConfig.Host hc, Session session) {
        }
        List<String> getPublicKeys() throws Exception {
            JSch jSch = createDefaultJSch(FS.DETECTED);
            List<String> keys = new ArrayList<>();
            for (Object o : jSch.getIdentityRepository().getIdentities()) {
                Identity i = (Identity) o;
                KeyPair keyPair = KeyPair.load(jSch, i.getName(), null);
                StringBuilder sb = new StringBuilder();
                try (StringBuilderWriter sbw = new StringBuilderWriter(sb);
                     OutputStream os = new WriterOutputStream(sbw, "UTF-8")) {
                    keyPair.writePublicKey(os, keyPair.getPublicKeyComment());
                } finally {
                    keyPair.dispose();
                }
                keys.add(sb.toString().trim());
            }
            return keys;
        }
    }.getPublicKeys();
}
 
Example 11
Source Project: setupmaker   Source File: JschFactory.java    License: Apache License 2.0 6 votes vote down vote up
public JschFactory(String host, String username, String password, String initRemDir) throws JSchException
{
    if (!initRemDir.endsWith("/")) initRemDir = initRemDir.concat("/");
    this.initRemDir = initRemDir;
    
    session = (new JSch()).getSession(username, host, 22);
    //ssh.setKnownHosts("/path/of/known_hosts/file");
    session.setPassword(password);
    session.setOutputStream(System.out);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setTimeout(30000);
    session.connect();
    channel = session.openChannel("sftp");
    channel.setOutputStream(System.out);
    channel.connect();
}
 
Example 12
Source Project: jumbune   Source File: JschUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Verify password.
 *
 * @param user the user
 * @param encryptedPasswrd the encrypted passwrd
 * @return true, if successful
 * @throws Exception the exception
 */
//TODO: Require to make sure we are not using localhost
public static boolean verifyPassword(String user, String encryptedPasswrd) throws Exception {
	JSch jsch = new JSch();
	Session session = null;
	java.util.Properties conf = new java.util.Properties();
	session = jsch.getSession(user, "localhost", RemotingConstants.TWENTY_TWO);
	UserInfo info = new JumbuneUserInfo(StringUtil.getPlain(encryptedPasswrd));
	session.setUserInfo(info);
	conf.put(STRICT_HOST_KEY_CHECKING, "no");
	session.setConfig(conf);
//	LOGGER.debug("Session Established, for user ["+user+"]");
	boolean isConnected = false;
	if(session!=null){
		session.connect();
		isConnected = session.isConnected();
		LOGGER.debug("Session Connected, for user ["+user+"]");
		session.disconnect();
	}
	return isConnected;
}
 
Example 13
Source Project: pentaho-kettle   Source File: SFTPClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a folder with nested folders under an existing folder given an absolute path.
 */
@Test
public void folderCreation_Absolute_Nested() throws Exception {
  System.setProperty( SFTPClient.ENV_PARAM_USERAUTH_GSSAPI, "yes" );
  SFTPClient client = spy( new SFTPClient( server, port, username ) {
    @Override
    JSch createJSch() {
      return jSch;
    }
  } );

  doReturn( true ).when( client ).folderExists( "/var" );
  doReturn( true ).when( client ).folderExists( "/var/ftproot" );

  client.login( password );
  client.createFolder( "/var/ftproot/myfolder/subfolder/finalfolder" );

  verify( channel, times( 3 ) ).mkdir( anyString() );
  verify( channel, times( 1 ) ).mkdir( "/var/ftproot/myfolder" );
  verify( channel, times( 1 ) ).mkdir( "/var/ftproot/myfolder/subfolder" );
  verify( channel, times( 1 ) ).mkdir( "/var/ftproot/myfolder/subfolder/finalfolder" );
}
 
Example 14
Source Project: sftp-fs   Source File: IdentityTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFromDataPrivateKeyNonNullPublicKeyAndNonNullBytePassphrase() throws JSchException {
    String name = "test";
    byte[] privateKey = PRIVATE_KEY.clone();
    byte[] publicKey = PUBLIC_KEY.clone();
    byte[] passphrase = PASSPHRASE.clone();

    Identity identity = Identity.fromData(name, privateKey, publicKey, passphrase);

    JSch jsch = spy(new JSch());

    identity.addIdentity(jsch);

    verify(jsch).addIdentity(name, privateKey, publicKey, passphrase);

    assertArrayEquals(PRIVATE_KEY, privateKey);
    assertArrayEquals(PUBLIC_KEY, publicKey);
}
 
Example 15
Source Project: Aria   Source File: SFtpUtil.java    License: Apache License 2.0 6 votes vote down vote up
private void setKnowHost(JSch jSch, FtpUrlEntity entity) throws JSchException {
  IdEntity idEntity = entity.idEntity;
  if (idEntity.knowHost != null) {
    File knowFile = new File(idEntity.knowHost);
    if (!knowFile.exists()) {
      FileUtil.createFile(knowFile);
    }
    jSch.setKnownHosts(idEntity.knowHost);

    //HostKeyRepository hkr = jSch.getHostKeyRepository();
    //hkr.add(new HostKey(entity.hostName, HostKey.SSHRSA, getPubKey(idEntity.pubKey)), new JschUserInfo());
    //
    //HostKey[] hks = hkr.getHostKey();
    //if (hks != null) {
    //  System.out.println("Host keys in " + hkr.getKnownHostsRepositoryID());
    //  for (int i = 0; i < hks.length; i++) {
    //    HostKey hk = hks[i];
    //    System.out.println(hk.getHost() + " " +
    //        hk.getType() + " " +
    //        hk.getFingerPrint(jSch));
    //  }
    //}
  }
}
 
Example 16
Source Project: netbeans   Source File: SftpClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void disconnect(boolean force) throws RemoteException {
    if (sftpSession == null) {
        // nothing to do
        LOGGER.log(Level.FINE, "Remote client not created yet => nothing to do");
        return;
    }
    if (!force
            && sftpSession.getServerAliveInterval() > 0) {
        LOGGER.log(Level.FINE, "Keep-alive running and disconnecting not forced -> do nothing");
        return;
    }
    LOGGER.log(Level.FINE, "Remote client trying to disconnect");
    if (sftpSession.isConnected()) {
        LOGGER.log(Level.FINE, "Remote client connected -> disconnecting");
        JSch.setLogger(DEV_NULL_LOGGER);
        sftpSession.disconnect();
        LOGGER.log(Level.FINE, "Remote client disconnected");
    }
    sftpClient = null;
    sftpSession = null;

    sftpLogger.info("QUIT"); // NOI18N
    sftpLogger.info(NbBundle.getMessage(SftpClient.class, "LOG_Goodbye"));
}
 
Example 17
Source Project: pentaho-kettle   Source File: SFTPClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a folder under the current user's home.
 */
@Test
public void folderCreation_Relative_Simple() throws Exception {
  System.setProperty( SFTPClient.ENV_PARAM_USERAUTH_GSSAPI, "yes" );
  SFTPClient client = spy( new SFTPClient( server, port, username ) {
    @Override
    JSch createJSch() {
      return jSch;
    }
  } );

  doReturn( "/home/admin" ).when( client ).pwd();

  client.login( password );
  client.createFolder( "myfolder" );

  verify( channel, times( 1 ) ).mkdir( anyString() );
  verify( channel, times( 1 ) ).mkdir( "/home/admin/myfolder" );
}
 
Example 18
Source Project: orion.server   Source File: LazyKnownHosts.java    License: Eclipse Public License 1.0 6 votes vote down vote up
LazyKnownHosts(JSch jsch, String knownHosts) throws JSchException {
	if (knownHosts != null) {
		try {
			final InputStream in = new ByteArrayInputStream(knownHosts.getBytes("UTF8"));
			try {
				jsch.setKnownHosts(in);
			} finally {
				in.close();
			}
		} catch (IOException e) {
			// no known hosts
		}
	}
	this.repo = jsch.getHostKeyRepository();

}
 
Example 19
/**
 * Return information about host and its fingerprint returned by server
 * 
 * @return JSON representation of host and key
 */
public JSONObject formJson() {
	JSONObject result = new JSONObject();
	try {
		if (hostkey != null) {
			result.put(HOST, hostkey.getHost());
			result.put(HOST_FINGERPRINT, hostkey.getFingerPrint(new JSch()));
			result.put(HOST_KEY, hostkey.getKey());
			result.put(KEY_TYPE, hostkey.getType());
		}
	} catch (JSONException e) {
		// only when keys are null
	}
	return result;

}
 
Example 20
Source Project: syndesis   Source File: SftpVerifierExtension.java    License: Apache License 2.0 6 votes vote down vote up
private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) {

        final String host = ConnectorOptions.extractOption(parameters, "host");
        final Integer port = ConnectorOptions.extractOptionAndMap(parameters, "port", Integer::parseInt, 22);
        final String userName = ConnectorOptions.extractOption(parameters, "username");
        final String password = ConnectorOptions.extractOption(parameters, "password", "");

        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(userName, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();
        } catch (JSchException e) {
            builder.error(ResultErrorBuilder
                    .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage()).build());
        } finally {
            if (session != null) {
                session.disconnect();
                jsch = null;
            }

        }
    }
 
Example 21
Source Project: bestconf   Source File: SFTPUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Session connect(String host, Integer port, String user, String password) throws JSchException{
	Session session = null;
	try {
		JSch jsch = new JSch();
		if(port != null){
			session = jsch.getSession(user, host, port.intValue());
		}else{
			session = jsch.getSession(user, host);
		}
		session.setPassword(password);
		
		session.setConfig("StrictHostKeyChecking", "no");
		//time out
		session.connect(3000);
	} catch (JSchException e) {
		e.printStackTrace();
		System.out.println("SFTPUitl connection error");
		throw e;
	}
	return session;
}
 
Example 22
Source Project: sftp-fs   Source File: IdentityTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFromDataPrivateKeyNonNullPublicKeyAndNullBytePassphrase() throws JSchException {
    String name = "test";
    byte[] privateKey = PRIVATE_KEY.clone();
    byte[] publicKey = PUBLIC_KEY.clone();

    Identity identity = Identity.fromData(name, privateKey, publicKey, null);

    JSch jsch = spy(new JSch());

    identity.addIdentity(jsch);

    verify(jsch).addIdentity(name, privateKey, publicKey, null);

    assertArrayEquals(PRIVATE_KEY, privateKey);
    assertArrayEquals(PUBLIC_KEY, publicKey);
}
 
Example 23
Source Project: ssh-proxy   Source File: JSchHelper.java    License: Apache License 2.0 6 votes vote down vote up
protected static void reconfigureServerHostKeyOrder(ServerHostKeySortOrder hostKeySortOrder) {
	List<HostKeyType> serverHostKeys = new ArrayList<>(getServerHostKeys());
	if (hostKeySortOrder == ServerHostKeySortOrder.PREFER_ECDSA) {
		serverHostKeys.sort(CMP_PREFER_ECDSA);
	} else if (hostKeySortOrder == ServerHostKeySortOrder.PREFER_RSA) {
		serverHostKeys.sort(CMP_PREFER_RSA);
	} else {
		throw new IllegalArgumentException("Unknown host key sort order: " + hostKeySortOrder);
	}

	if (!getServerHostKeys().equals(serverHostKeys)) {
		log.debug("changing server host key order to: {}", serverHostKeys);

		List<String> serverHostKeyNames = new ArrayList<>();
		for (HostKeyType serverHostKey : serverHostKeys) {
			serverHostKeyNames.add(serverHostKey.getTypeString());
		}

		String newHostKeyOrder = Utils.join(serverHostKeyNames, SERVER_HOST_KEY_SEPARATOR);
		JSch.setConfig(JSCH_CONFIG_KEY_SERVER_HOST_KEY, newHostKeyOrder);
	}
}
 
Example 24
private SshSessionFactory getSshSessionFactory(String remotePrivateKey, final Path tempKey) {
    try {

        Files.write(tempKey, remotePrivateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = super.createDefaultJSch(fs);
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example 25
Source Project: azure-libraries-for-java   Source File: SSHShell.java    License: MIT License 6 votes vote down vote up
/**
 * Automatically generate SSH keys.
 * @param passPhrase the byte array content to be uploaded
 * @param comment the name of the file for which the content will be saved into
 * @return SSH public and private key
 * @throws Exception exception thrown
 */
public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws Exception {
    JSch jsch = new JSch();
    KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
    ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048);
    ByteArrayOutputStream publicKeyBuff = new ByteArrayOutputStream(2048);

    keyPair.writePublicKey(publicKeyBuff, (comment != null) ? comment : "SSHCerts");

    if (passPhrase == null  || passPhrase.isEmpty()) {
        keyPair.writePrivateKey(privateKeyBuff);
    } else {
        keyPair.writePrivateKey(privateKeyBuff, passPhrase.getBytes());
    }

    return new SshPublicPrivateKey(privateKeyBuff.toString(), publicKeyBuff.toString());
}
 
Example 26
Source Project: jumbune   Source File: JobConfigUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Session getSession(String host, String username, String password, String privateKeyPath)
		throws JSchException {
	JSch jsch = new JSch();
	Session session = null;
	if (StringUtils.isNotBlank(privateKeyPath)) {
		jsch.addIdentity(privateKeyPath);
	}
	session = jsch.getSession(username, host, 22);

	Properties config = new Properties();
	config.put("StrictHostKeyChecking", "no");
	if (StringUtils.isNotBlank(password)) {
		session.setPassword(password);
		config.put("PreferredAuthentications", "password");
	}
	session.setConfig(config);
	session.connect();
	return session;
}
 
Example 27
Source Project: jsch-extension   Source File: SessionFactory.java    License: MIT License 5 votes vote down vote up
protected SessionFactoryBuilder( JSch jsch, String username, String hostname, int port, Proxy proxy, Map<String, String> config, UserInfo userInfo ) {
    this.jsch = jsch;
    this.username = username;
    this.hostname = hostname;
    this.port = port;
    this.proxy = proxy;
    this.config = config;
    this.userInfo = userInfo;
}
 
Example 28
Source Project: sftp-fs   Source File: SFTPEnvironmentTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInitializeJSchEmpty() throws IOException {
    SFTPEnvironment env = new SFTPEnvironment();

    JSch jsch = mock(JSch.class);
    env.initialize(jsch);

    verifyNoMoreInteractions(jsch);
}
 
Example 29
Source Project: sshd-shell-spring-boot   Source File: AbstractSshSupport.java    License: Apache License 2.0 5 votes vote down vote up
Session openSession(String username, String password) throws JSchException {
    JSch jsch = new JSch();
    Session session = jsch.getSession(username, props.getShell().getHost(), props.getShell().getPort());
    session.setPassword(password);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    return session;
}
 
Example 30
Source Project: aws-cf-templates   Source File: ATest.java    License: Apache License 2.0 5 votes vote down vote up
protected final Session tunnelSSH(final String host, final KeyPair key, final Integer localPort, final String remoteHost, final Integer remotePort) throws JSchException {
    final JSch jsch = new JSch();
    final Session session = jsch.getSession("ec2-user", host);
    jsch.addIdentity(key.getKeyName(), key.getKeyMaterial().getBytes(), null, null);
    jsch.setConfig("StrictHostKeyChecking", "no"); // for testing this should be fine. adding the host key seems to be only possible via a file which is not very useful here
    session.setPortForwardingL(localPort, remoteHost, remotePort);
    session.connect(10000);
    return session;
}