com.jcraft.jsch.JSch Java Examples

The following examples show how to use com.jcraft.jsch.JSch. 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 File: JSchExecutor.java    From vividus with Apache License 2.0 11 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 File: JschUtil.java    From jumbune with 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 #3
Source File: SftpClientTest.java    From hop with 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 #4
Source File: SftpClientTest.java    From hop with 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 #5
Source File: GitReadSaveTest.java    From blueocean-plugin with 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 #6
Source File: JSchExecutorTests.java    From vividus with 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 #7
Source File: JSchExecutorTests.java    From vividus with 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 #8
Source File: PooledSFTPConnection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addIdentity(JSch jsch, URI key) throws IOException {
	try {
		String keyName = key.toString();
		log.debug("Adding new identity from " + keyName);
		try (InputStream is = FileUtils.getInputStream(null, keyName)) {
			byte[] prvKey = IOUtils.toByteArray(is);
			jsch.addIdentity(keyName, prvKey, null, null);
		}
	} catch (Exception e) {
		throw new IOException("Failed to read private key", e);
	}
}
 
Example #9
Source File: CipherHelper.java    From flow-platform-x with 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 #10
Source File: SFTPUtils.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #11
Source File: KeySettingActivity.java    From mOrgAnd with 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 #12
Source File: SystemInfo.java    From app-runner with 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 #13
Source File: JschFactory.java    From setupmaker with 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 #14
Source File: SFTPClientTest.java    From pentaho-kettle with 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 #15
Source File: IdentityTest.java    From sftp-fs with 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 #16
Source File: SFtpUtil.java    From Aria with 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 #17
Source File: SftpClient.java    From netbeans with 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 #18
Source File: SFTPClientTest.java    From pentaho-kettle with 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 #19
Source File: LazyKnownHosts.java    From orion.server with 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 #20
Source File: HostFingerprintException.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #21
Source File: SftpVerifierExtension.java    From syndesis with 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 #22
Source File: SFTPUtil.java    From bestconf with 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 #23
Source File: IdentityTest.java    From sftp-fs with 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 #24
Source File: JSchHelper.java    From ssh-proxy with 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 #25
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
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 #26
Source File: SSHShell.java    From azure-libraries-for-java with 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 #27
Source File: JobConfigUtil.java    From jumbune with 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 #28
Source File: DeploymentEngine.java    From Microservices-Building-Scalable-Software with MIT License 5 votes vote down vote up
private boolean executeSSH(){ 
	//get deployment descriptor, instead of this hard coded.
	// or execute a script on the target machine which download artifact from nexus
       String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &";
      try{	
   	   System.out.println("Executing "+ command);
          java.util.Properties config = new java.util.Properties(); 
          config.put("StrictHostKeyChecking", "no");
          JSch jsch = new JSch();
          Session session=jsch.getSession("rajeshrv", "localhost", 22);
          session.setPassword("rajeshrv");
          
          session.setConfig(config);
          session.connect();
          System.out.println("Connected");
           
          ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
          InputStream in = channelExec.getInputStream();
          channelExec.setCommand(command);
          channelExec.connect();
         
          BufferedReader reader = new BufferedReader(new InputStreamReader(in));
          String line;
          int index = 0;

          while ((line = reader.readLine()) != null) {
              System.out.println(++index + " : " + line);
          }
          channelExec.disconnect();
          session.disconnect();

          System.out.println("Done!");

      }catch(Exception e){
          e.printStackTrace();
          return false;
      }
	
	return true;
}
 
Example #29
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testReExchangeFromJschClient() throws Exception {
    Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
    setUp(0L, 0L, 0L);

    JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
    JSch sch = new JSch();
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
    try {
        s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
        s.connect();

        com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL);
        c.connect();
        try (OutputStream os = c.getOutputStream();
             InputStream is = c.getInputStream()) {

            String expected = "this is my command\n";
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[bytes.length + Long.SIZE];
            for (int i = 1; i <= 10; i++) {
                os.write(bytes);
                os.flush();

                int len = is.read(data);
                String str = new String(data, 0, len);
                assertEquals("Mismatched data at iteration " + i, expected, str);

                outputDebugMessage("Request re-key #%d", i);
                s.rekey();
            }
        } finally {
            c.disconnect();
        }
    } finally {
        s.disconnect();
    }
}
 
Example #30
Source File: GitMirrorAuthTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static boolean isEncrypted(byte[] privateKeyBytes, byte[] publicKeyBytes) {
    try {
        return KeyPair.load(new JSch(), privateKeyBytes, publicKeyBytes).isEncrypted();
    } catch (JSchException e) {
        logger.warn("Failed to load the SSH key: {}", GIT_PRIVATE_KEY, e);
        return true;
    }
}