@Test public void testCreateClientWillUseKeyIfKeyAndKeyPathPresent() throws Exception { final String testKey = "MyVeryBigKey"; final BapSshCommonConfiguration defaultKeyInfo = new BapSshCommonConfiguration( TEST_PASSPHRASE, testKey, "/this/file/will/not/be/used", false); hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo); getHostConfig().setPassword("Ignore me"); expect( mockJSch.getSession( getHostConfig().getUsername(), getHostConfig().getHostname(), getHostConfig().getPort())) .andReturn(mockSession); mockJSch.addIdentity( isA(String.class), aryEq(BapSshUtil.toBytes(testKey)), (byte[]) isNull(), aryEq(BapSshUtil.toBytes(TEST_PASSPHRASE))); mockSession.setConfig((Properties) anyObject()); mockSession.connect(getHostConfig().getTimeout()); expect(mockSession.openChannel("sftp")).andReturn(mockSftp); mockSftp.connect(getHostConfig().getTimeout()); testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true); mockSftp.cd(getHostConfig().getRemoteRootDir()); assertCreateClient(); }
@Test public void testCreateClientWithOverrideKeyPath() throws Exception { final String testKeyFilename = "myPrivateKey"; final RandomFile theKey = new RandomFile(jenkinsHome.getRoot(), testKeyFilename); hostConfig = createWithOverrideUsernameAndPassword(mockJSch, TEST_PASSPHRASE, testKeyFilename, ""); final BapSshCommonConfiguration commonConfiguration = new BapSshCommonConfiguration("Ignore me", null, null, false); getHostConfig().setCommonConfig(commonConfiguration); expect( mockJSch.getSession( getHostConfig().getUsername(), getHostConfig().getHostname(), getHostConfig().getPort())) .andReturn(mockSession); mockJSch.addIdentity( isA(String.class), aryEq(theKey.getContents()), (byte[]) isNull(), aryEq(BapSshUtil.toBytes(TEST_PASSPHRASE))); mockSession.setConfig((Properties) anyObject()); mockSession.connect(getHostConfig().getTimeout()); expect(mockSession.openChannel("sftp")).andReturn(mockSftp); mockSftp.connect(getHostConfig().getTimeout()); testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true); mockSftp.cd(getHostConfig().getRemoteRootDir()); assertCreateClient(); }
private BapSshClient assertCreateClientWithDefaultKey(final boolean disableExec) throws Exception { final String testKey = "MyVeryBigKey"; final BapSshCommonConfiguration defaultKeyInfo = new BapSshCommonConfiguration(TEST_PASSPHRASE, testKey, null, disableExec); hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo); getHostConfig().setPassword("Ignore me"); expect( mockJSch.getSession( getHostConfig().getUsername(), getHostConfig().getHostname(), getHostConfig().getPort())) .andReturn(mockSession); mockJSch.addIdentity( isA(String.class), aryEq(BapSshUtil.toBytes(testKey)), (byte[]) isNull(), aryEq(BapSshUtil.toBytes(defaultKeyInfo.getPassphrase()))); mockSession.setConfig((Properties) anyObject()); mockSession.connect(getHostConfig().getTimeout()); expect(mockSession.openChannel("sftp")).andReturn(mockSftp); mockSftp.connect(getHostConfig().getTimeout()); testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true); mockSftp.cd(getHostConfig().getRemoteRootDir()); return assertCreateClient(); }
public void addIdentity(String prvkey, String passphrase) throws JSchException { byte[] _passphrase = null; if (passphrase != null) { _passphrase = Util.str2byte(passphrase); } addIdentity(prvkey, _passphrase); if (_passphrase != null) Util.bzero(_passphrase); }
/** * @param userName the name of the account being logged into. * @param hostName this should be the host. I found values like <code>foo.com</code> work, where * <code>http://foo.com</code> don't. * @param userPassword if you are not using key based authentication, then you are likely being * prompted for a password each time you login. This is that password. It is <em>not</em> the * passphrase for the private key! * @param port the default is 22, and if you specify N<0 for this value we'll default it to 22 * @param knownHostsFile this is the known hosts file. If you don't specify it, jsch does some * magic to work without your specification. If you have it in a non well-known location, * however, this property is for you. An example: <code>/home/user/.ssh/known_hosts</code> * @param knownHostsInputStream this is the known hosts file. If you don't specify it, jsch does * some magic to work without your specification. If you have it in a non well-known location, * however, this property is for you. An example: <code>/home/user/.ssh/known_hosts</code>. * Note that you may specify this <em>or</em> the #knownHostsFile - not both! * @param privateKey this is usually used when you want passwordless automation (obviously, for * this integration it's useless since this lets you specify a password once, anyway, but * still good to have if required). This file might be ~/.ssh/id_dsa, or a <code>.pem</code> * for your remote server (for example, on EC2) * @param pvKeyPassPhrase sometimes, to be extra secure, the private key itself is extra * encrypted. In order to surmount that, we need the private key passphrase. Specify that * here. * @throws Exception thrown if any of a myriad of scenarios plays out */ public SftpSession( String userName, String hostName, String userPassword, int port, String knownHostsFile, InputStream knownHostsInputStream, String privateKey, String pvKeyPassPhrase) throws Exception { JSch jSch = new JSch(); if (port <= 0) { port = 22; } this.privateKey = privateKey; this.privateKeyPassphrase = pvKeyPassPhrase; if (!StringUtils.isEmpty(knownHostsFile)) { jSch.setKnownHosts(knownHostsFile); } else if (null != knownHostsInputStream) { jSch.setKnownHosts(knownHostsInputStream); } // private key if (!StringUtils.isEmpty(this.privateKey)) { if (!StringUtils.isEmpty(privateKeyPassphrase)) { jSch.addIdentity(this.privateKey, privateKeyPassphrase); } else { jSch.addIdentity(this.privateKey); } } session = jSch.getSession(userName, hostName, port); if (!StringUtils.isEmpty(userPassword)) { session.setPassword(userPassword); } userInfo = new OptimisticUserInfoImpl(userPassword); session.setUserInfo(userInfo); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); }
/** * Open an ssh seession. * * @return the opened session * @throws JSchException on error */ protected Session openSession() throws JSchException { JSch jsch = new JSch(); if (null != userInfo.getKeyfile()) { jsch.addIdentity(userInfo.getKeyfile()); } if (!userInfo.getTrust() && knownHosts != null) { project.log("Using known hosts: " + knownHosts, Project.MSG_DEBUG); jsch.setKnownHosts(knownHosts); } Session session = jsch.getSession(userInfo.getName(), host, port); session.setUserInfo(userInfo); project.log("Connecting to " + host + ":" + port, Project.MSG_VERBOSE); session.connect(); return session; }
/** * Init Helper Class with connection settings * * @param serverIP IP address of remote server * @param serverPort port of remote server * @param userName username of remote server * @param privateKeyFilename filename of private key * @param passPhrase passphrase * @throws KettleJobException */ public SFTPClient( InetAddress serverIP, int serverPort, String userName, String privateKeyFilename, String passPhrase) throws KettleJobException { if (serverIP == null || serverPort < 0 || userName == null || userName.equals("")) { throw new KettleJobException( "For a SFTP connection server name and username must be set and server port must be greater than zero."); } this.serverIP = serverIP; this.serverPort = serverPort; this.userName = userName; JSch jsch = new JSch(); try { if (!Const.isEmpty(privateKeyFilename)) { // We need to use private key authentication this.prvkey = privateKeyFilename; byte[] passphrasebytes = new byte[0]; if (!Const.isEmpty(passPhrase)) { // Set passphrase this.passphrase = passPhrase; passphrasebytes = GetPrivateKeyPassPhrase().getBytes(); } jsch.addIdentity( getUserName(), FileUtil.getContent(KettleVFS.getFileObject(prvkey)), // byte[] privateKey null, // byte[] publicKey passphrasebytes); // byte[] passPhrase } s = jsch.getSession(userName, serverIP.getHostAddress(), serverPort); } catch (IOException e) { throw new KettleJobException(e); } catch (KettleFileException e) { throw new KettleJobException(e); } catch (JSchException e) { throw new KettleJobException(e); } }
protected void addUserIDFiles() { // if (config.userConfigDir == null) { logger.debug("addUserIDFiles(): No userConfigDir configured"); return; } // Config director is for example" ~/.ssh/ String configDir = config.userConfigDir; FSPath configPath; try { configPath = FSUtil.getDefault().resolvePath(configDir); } catch (IOException e) { logger.error( "addUserIDFiles():Failed to read/acces config directory:{} => IOException:{}", configDir, e); return; } String keys[] = config.privateKeys; if ((keys == null) || (keys.length <= 0)) { logger.info("addUserIDFiles():No private keys"); return; } for (String key : keys) { try { FSPath keyFile = configPath.resolvePath(key); if (keyFile.exists()) { logger.info("addUserIDFiles(): adding existing identity:{}\n", keyFile); jsch.addIdentity(keyFile.getPathname()); } else { logger.info("addUserIDFiles(): ignoring missing identity file:{}\n", keyFile); } } catch (IOException e) { logger.error("Got IOException accessing file:{}/{} => IOException:{}", configPath, key, e); } catch (JSchException e) { logger.error("Got JSchException adding file:{}/{} => JSchException:{}", configPath, key, e); } } }
/* public void addIdentity(String foo) throws JSchException{ addIdentity(foo, null); } public void addIdentity(String foo, String bar) throws JSchException{ // Identity identity=new IdentityFile(foo, this); // if(bar!=null) identity.setPassphrase(bar); // identities.addElement(identity); } */ public void addIdentity(Identity id) throws JSchException { addIdentity(id, null); }
public void addIdentity(String name, byte[] prvkey, byte[] pubkey, byte[] passphrase) throws JSchException { Identity identity = IdentityFile.newInstance(name, prvkey, pubkey, this); addIdentity(identity, passphrase); }
public void addIdentity(String prvkey) throws JSchException { addIdentity(prvkey, (byte[]) null); }
@Override @OnWebSocketConnect public void onConnect(Session session) { super.onConnect(session); this.session.setIdleTimeout(TimeUnit.MINUTES.toMillis(1)); Connector con = null; try { ConnectorFactory cf = ConnectorFactory.getDefault(); con = cf.createConnector(); } catch (AgentProxyException e) { System.out.println(e); } IdentityRepository irepo = null; if (con != null) { RemoteIdentityRepository rrepo = new RemoteIdentityRepository(con); if (rrepo.getIdentities() != null && rrepo.getIdentities().size() > 0) { irepo = rrepo; jsch.setIdentityRepository(irepo); } } if (irepo == null) { String home = System.getProperty("user.home"); String sshDir = home + File.separator + ".ssh" + File.separator; String[] defaultKeys = new String[] { sshDir + "id_ecdsa", sshDir + "id_id_ed25519", sshDir + "id_rsa", sshDir + "id_dsa", sshDir + "identity" }; for (String nextKey : defaultKeys) { try { jsch.addIdentity(nextKey); log.fine("Key '" + nextKey + "' added"); } catch (JSchException e) { log.log(Level.FINE, "Key '" + nextKey + "' not valid", e); } } } Map<String, List<String>> parameterMap = session.getUpgradeRequest().getParameterMap(); String host = getStringParameter(parameterMap, "host", null); String connectHost = hostLookupService.getResolvableHostname(host); String user = getStringParameter(parameterMap, "user", null); if ("@admin".equals(user)) { user = hostLookupService.getAdminUserFor(host); } Resize resize = new Resize(); resize.cols = getIntParameter(parameterMap, "cols", 80); resize.rows = getIntParameter(parameterMap, "rows", 24); try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); jschSession = jsch.getSession(user, connectHost, hostLookupService.getSshPort(host)); jschSession.setConfig(config); jschSession.connect(60000); shell = (ChannelShell) jschSession.openChannel("shell"); shell.setAgentForwarding(true); shell.setPtyType("vt102"); shell.connect(); shell.setPtySize(resize.cols, resize.rows, resize.getPixelWidth(), resize.getPixelHeight()); } catch (JSchException e) { close(1, "Failed to create ssh session", e); } Runnable run; try { run = new RawSentOutputTask( session, new BufferedInputStream(shell.getInputStream(), BUFFER_LEN)); Thread thread = new Thread(run); thread.start(); } catch (IOException e) { close(2, "IOException while getting data from ssh", e); } try { inputToShell = new PrintStream(shell.getOutputStream(), true, "UTF-8"); } catch (IOException e) { close(3, "IOException while creating write stream to ssh", e); } }
public void openConnectionInternal() throws AuthenticationException { if (authenticationInfo == null) { authenticationInfo = new AuthenticationInfo(); } if (!interactive) { uIKeyboardInteractive = null; setInteractiveUserInfo(new NullInteractiveUserInfo()); } JSch sch = new JSch(); File privateKey; try { privateKey = ScpHelper.getPrivateKey(authenticationInfo); } catch (FileNotFoundException e) { throw new AuthenticationException(e.getMessage()); } try { Connector connector = ConnectorFactory.getDefault().createConnector(); if (connector != null) { IdentityRepository repo = new RemoteIdentityRepository(connector); sch.setIdentityRepository(repo); } } catch (AgentProxyException e) { fireSessionDebug("Unable to connect to agent: " + e.toString()); } if (privateKey != null && privateKey.exists()) { fireSessionDebug("Using private key: " + privateKey); try { sch.addIdentity(privateKey.getAbsolutePath(), authenticationInfo.getPassphrase()); } catch (JSchException e) { throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e); } } String host = getRepository().getHost(); int port = repository.getPort() == WagonConstants.UNKNOWN_PORT ? ScpHelper.DEFAULT_SSH_PORT : repository.getPort(); try { String userName = authenticationInfo.getUserName(); if (userName == null) { userName = System.getProperty("user.name"); } session = sch.getSession(userName, host, port); session.setTimeout(getTimeout()); } catch (JSchException e) { throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e); } Proxy proxy = null; ProxyInfo proxyInfo = getProxyInfo(ProxyInfo.PROXY_SOCKS5, getRepository().getHost()); if (proxyInfo != null && proxyInfo.getHost() != null) { proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort()); ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); } else { proxyInfo = getProxyInfo(ProxyInfo.PROXY_HTTP, getRepository().getHost()); if (proxyInfo != null && proxyInfo.getHost() != null) { proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort()); ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); } else { // Backwards compatibility proxyInfo = getProxyInfo(getRepository().getProtocol(), getRepository().getHost()); if (proxyInfo != null && proxyInfo.getHost() != null) { // if port == 1080 we will use SOCKS5 Proxy, otherwise will use HTTP Proxy if (proxyInfo.getPort() == SOCKS5_PROXY_PORT) { proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort()); ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); } else { proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort()); ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword()); } } } } session.setProxy(proxy); // username and password will be given via UserInfo interface. UserInfo ui = new WagonUserInfo(authenticationInfo, getInteractiveUserInfo()); if (uIKeyboardInteractive != null) { ui = new UserInfoUIKeyboardInteractiveProxy(ui, uIKeyboardInteractive); } Properties config = new Properties(); if (getKnownHostsProvider() != null) { try { String contents = getKnownHostsProvider().getContents(); if (contents != null) { sch.setKnownHosts(new StringInputStream(contents)); } } catch (JSchException e) { // continue without known_hosts } config.setProperty("StrictHostKeyChecking", getKnownHostsProvider().getHostKeyChecking()); } if (authenticationInfo.getPassword() != null) { config.setProperty( "PreferredAuthentications", "gssapi-with-mic,publickey,password,keyboard-interactive"); } config.setProperty("BatchMode", interactive ? "no" : "yes"); session.setConfig(config); session.setUserInfo(ui); StringWriter stringWriter = new StringWriter(); try { session.connect(); if (getKnownHostsProvider() != null) { PrintWriter w = new PrintWriter(stringWriter); HostKeyRepository hkr = sch.getHostKeyRepository(); HostKey[] keys = hkr.getHostKey(); for (int i = 0; keys != null && i < keys.length; i++) { HostKey key = keys[i]; w.println(key.getHost() + " " + key.getType() + " " + key.getKey()); } } } catch (JSchException e) { if (e.getMessage().startsWith("UnknownHostKey:") || e.getMessage().startsWith("reject HostKey:")) { throw new UnknownHostException(host, e); } else if (e.getMessage().contains("HostKey has been changed")) { throw new KnownHostChangedException(host, e); } else { throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e); } } try { getKnownHostsProvider().storeKnownHosts(stringWriter.toString()); } catch (IOException e) { closeConnection(); throw new AuthenticationException( "Connection aborted - failed to write to known_hosts. Reason: " + e.getMessage(), e); } }
protected Session createSession(final RemoteFileConfiguration configuration) throws JSchException { final JSch jsch = new JSch(); JSch.setLogger(new JSchLogger()); SftpConfiguration sftpConfig = (SftpConfiguration) configuration; if (isNotEmpty(sftpConfig.getCiphers())) { LOG.debug("Using ciphers: {}", sftpConfig.getCiphers()); Hashtable<String, String> ciphers = new Hashtable<String, String>(); ciphers.put("cipher.s2c", sftpConfig.getCiphers()); ciphers.put("cipher.c2s", sftpConfig.getCiphers()); JSch.setConfig(ciphers); } if (isNotEmpty(sftpConfig.getPrivateKeyFile())) { LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile()); if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) { jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase()); } else { jsch.addIdentity(sftpConfig.getPrivateKeyFile()); } } if (sftpConfig.getPrivateKey() != null) { LOG.debug("Using private key information from byte array"); byte[] passphrase = null; if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) { try { passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new JSchException("Cannot transform passphrase to byte[]", e); } } jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase); } if (sftpConfig.getPrivateKeyUri() != null) { LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri()); byte[] passphrase = null; if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) { try { passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new JSchException("Cannot transform passphrase to byte[]", e); } } try { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream( endpoint.getCamelContext().getClassResolver(), sftpConfig.getPrivateKeyUri()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, bos); jsch.addIdentity("ID", bos.toByteArray(), null, passphrase); } catch (IOException e) { throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e); } } if (sftpConfig.getKeyPair() != null) { LOG.debug("Using private key information from key pair"); KeyPair keyPair = sftpConfig.getKeyPair(); if (keyPair.getPrivate() != null && keyPair.getPublic() != null) { if (keyPair.getPrivate() instanceof RSAPrivateKey && keyPair.getPublic() instanceof RSAPublicKey) { jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null); } else if (keyPair.getPrivate() instanceof DSAPrivateKey && keyPair.getPublic() instanceof DSAPublicKey) { jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null); } else { LOG.warn("Only RSA and DSA key pairs are supported"); } } else { LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled"); } } if (isNotEmpty(sftpConfig.getKnownHostsFile())) { LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile()); jsch.setKnownHosts(sftpConfig.getKnownHostsFile()); } if (isNotEmpty(sftpConfig.getKnownHostsUri())) { LOG.debug("Using knownhosts uri: {}", sftpConfig.getKnownHostsUri()); try { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream( endpoint.getCamelContext().getClassResolver(), sftpConfig.getKnownHostsUri()); jsch.setKnownHosts(is); } catch (IOException e) { throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e); } } if (sftpConfig.getKnownHosts() != null) { LOG.debug("Using knownhosts information from byte array"); jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts())); } final Session session = jsch.getSession( configuration.getUsername(), configuration.getHost(), configuration.getPort()); if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) { LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking()); session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking()); } session.setServerAliveInterval(sftpConfig.getServerAliveInterval()); session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax()); // compression if (sftpConfig.getCompression() > 0) { LOG.debug("Using compression: {}", sftpConfig.getCompression()); session.setConfig("compression.s2c", "[email protected],zlib,none"); session.setConfig("compression.c2s", "[email protected],zlib,none"); session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression())); } // set the PreferredAuthentications if (sftpConfig.getPreferredAuthentications() != null) { LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications()); session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications()); } // set user information session.setUserInfo( new ExtendedUserInfo() { public String getPassphrase() { return null; } public String getPassword() { return configuration.getPassword(); } public boolean promptPassword(String s) { return true; } public boolean promptPassphrase(String s) { return true; } public boolean promptYesNo(String s) { LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no."); // Return 'false' indicating modification of the hosts file is disabled. return false; } public void showMessage(String s) { LOG.trace("Message received from Server: " + s); } public String[] promptKeyboardInteractive( String destination, String name, String instruction, String[] prompt, boolean[] echo) { // must return an empty array if password is null if (configuration.getPassword() == null) { return new String[0]; } else { return new String[] {configuration.getPassword()}; } } }); // set the SO_TIMEOUT for the time after the connect phase if (configuration.getSoTimeout() > 0) { session.setTimeout(configuration.getSoTimeout()); } // set proxy if configured if (proxy != null) { session.setProxy(proxy); } return session; }
/** {@inheritDoc} */ @Override public ClusterStartNodeResult call() { JSch ssh = new JSch(); Session ses = null; try { if (spec.key() != null) ssh.addIdentity(spec.key().getAbsolutePath()); ses = ssh.getSession(spec.username(), spec.host(), spec.port()); if (spec.password() != null) ses.setPassword(spec.password()); ses.setConfig("StrictHostKeyChecking", "no"); ses.connect(timeout); boolean win = isWindows(ses); char separator = win ? '\\' : '/'; spec.fixPaths(separator); String igniteHome = spec.igniteHome(); if (igniteHome == null) igniteHome = win ? DFLT_IGNITE_HOME_WIN : DFLT_IGNITE_HOME_LINUX; String script = spec.script(); if (script == null) script = DFLT_SCRIPT_LINUX; String cfg = spec.configuration(); if (cfg == null) cfg = ""; String startNodeCmd; String scriptOutputFileName = FILE_NAME_DATE_FORMAT.format(new Date()) + '-' + UUID.randomUUID().toString().substring(0, 8) + ".log"; if (win) throw new UnsupportedOperationException( "Apache Ignite cannot be auto-started on Windows from IgniteCluster.startNodes(…) API."); else { // Assume Unix. int spaceIdx = script.indexOf(' '); String scriptPath = spaceIdx > -1 ? script.substring(0, spaceIdx) : script; String scriptArgs = spaceIdx > -1 ? script.substring(spaceIdx + 1) : ""; String rmtLogArgs = buildRemoteLogArguments(spec.username(), spec.host()); String tmpDir = env(ses, "$TMPDIR", "/tmp/"); String scriptOutputDir = tmpDir + "ignite-startNodes"; shell(ses, "mkdir " + scriptOutputDir); // Mac os don't support ~ in double quotes. Trying get home path from remote system. if (igniteHome.startsWith("~")) { String homeDir = env(ses, "$HOME", "~"); igniteHome = igniteHome.replaceFirst("~", homeDir); } startNodeCmd = new SB() . // Console output is consumed, started nodes must use Ignite file appenders for log. a("nohup ") .a("\"") .a(igniteHome) .a('/') .a(scriptPath) .a("\"") .a(" ") .a(scriptArgs) .a(!cfg.isEmpty() ? " \"" : "") .a(cfg) .a(!cfg.isEmpty() ? "\"" : "") .a(rmtLogArgs) .a(" > ") .a(scriptOutputDir) .a("/") .a(scriptOutputFileName) .a(" 2>& 1 &") .toString(); } info("Starting remote node with SSH command: " + startNodeCmd, spec.logger(), log); shell(ses, startNodeCmd); return new ClusterStartNodeResultImpl(spec.host(), true, null); } catch (IgniteInterruptedCheckedException e) { return new ClusterStartNodeResultImpl(spec.host(), false, e.getMessage()); } catch (Exception e) { return new ClusterStartNodeResultImpl(spec.host(), false, X.getFullStackTrace(e)); } finally { if (ses != null && ses.isConnected()) ses.disconnect(); } }
/** * Creates a SSH Session with a remote machine and tries to login according to the details * specified by Contact An appropriate message is shown to the end user in case the login fails * * @param sshContact ID of SSH Contact * @throws JSchException if a JSch is unable to create a SSH Session with the remote machine * @throws InterruptedException if the thread is interrupted before session connected or is timed * out * @throws OperationFailedException if not of above reasons :-) */ public void createSSHSessionAndLogin(ContactSSH sshContact) throws JSchException, OperationFailedException, InterruptedException { logger.info("Creating a new SSH Session to " + sshContact.getHostName()); // creating a new JSch Stack identifier for contact JSch jsch = new JSch(); String knownHosts = (String) accountID.getAccountProperties().get("KNOWN_HOSTS_FILE"); if (!knownHosts.equals("Optional")) jsch.setKnownHosts(knownHosts); String identitiyKey = (String) accountID.getAccountProperties().get("IDENTITY_FILE"); String userName = sshContact.getUserName(); // use the name of system user if the contact has not supplied SSH // details if (userName.equals("")) userName = System.getProperty("user.name"); if (!identitiyKey.equals("Optional")) jsch.addIdentity(identitiyKey); // creating a new session for the contact Session session = jsch.getSession( userName, sshContact.getHostName(), sshContact.getSSHConfigurationForm().getPort()); /** * Creating and associating User Info with the session User Info passes authentication from * sshContact to SSH Stack */ SSHUserInfo sshUserInfo = new SSHUserInfo(sshContact); session.setUserInfo(sshUserInfo); /** initializing the session */ session.connect(connectionTimeout); int count = 0; // wait for session to get connected while (!session.isConnected() && count <= 30000) { Thread.sleep(1000); count += 1000; logger.trace("SSH:" + sshContact.getHostName() + ": Sleep zzz .. "); } // if timeout have exceeded if (count > 30000) { sshContact.setSSHSession(null); JOptionPane.showMessageDialog( null, "SSH Connection attempt to " + sshContact.getHostName() + " timed out"); // error codes are not defined yet throw new OperationFailedException( "SSH Connection attempt to " + sshContact.getHostName() + " timed out", 2); } sshContact.setJSch(jsch); sshContact.setSSHSession(session); logger.info("A new SSH Session to " + sshContact.getHostName() + " Created"); }
@Override public Session create() throws Exception { JSch jsch = new JSch(); session = jsch.getSession( loginCredentials.getUser(), hostAndPort.getHostText(), hostAndPort.getPortOrDefault(22)); if (sessionTimeout != 0) session.setTimeout(sessionTimeout); if (loginCredentials.getPrivateKey() == null) { session.setPassword(loginCredentials.getPassword()); } else { byte[] privateKey = loginCredentials.getPrivateKey().getBytes(); if (CredentialUtils.isPrivateKeyEncrypted(privateKey)) { throw new IllegalArgumentException( "JschSshClientModule does not support private keys that require a passphrase"); } jsch.addIdentity( loginCredentials.getUser(), Arrays.copyOf(privateKey, privateKey.length), null, emptyPassPhrase); } java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(connectTimeout); return session; }
private Session connectToInstance(String publicDNS) throws Exception { JSch jsch = new JSch(); jsch.addIdentity("rtp.pem"); Session session = jsch.getSession("ubuntu", publicDNS); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); return session; }
public void openSshConnection() throws JSchException { JSch jSch = new JSch(); if (privateKeyLocation != null) { session = jSch.getSession(username, destinationHost, connectionPort); jSch.addIdentity(privateKeyLocation); } else { session = jSch.getSession(username, destinationHost, connectionPort); session.setPassword(password); } session.setConfig("StrictHostKeyChecking", "no"); session.setConfig( "PreferredAuthentications", "publickey,keyboard-interactive,password"); // Skipping kerberos authentication session.connect(SLEEP_MILLISECONDS); }
/** * method for establishing connection while authentication * * @param username * @param namenodeIP * @param nnpwd * @param privateKeyPath * @return * @throws JSchException * @throws IOException * @throws InterruptedException */ public static Session establishConnection( String username, String namenodeIP, String nnpwd, String privateKeyPath) throws JSchException, IOException, InterruptedException { JSch jsch = new JSch(); Session session = jsch.getSession(username, namenodeIP, Constants.TWENTY_TWO); session.setPassword(nnpwd); UserInfo info = new JumbuneUserInfo(); jsch.addIdentity(privateKeyPath, nnpwd); session.setUserInfo(info); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); return session; }
public static void main(String[] arg) { try { JSch jsch = new JSch(); String user = "******"; String host = "hddev-c01-edge-01"; int port = 22; String privateKey = "src/main/resources/id_rsa"; jsch.addIdentity(privateKey); System.out.println("identity added "); Session session = jsch.getSession(user, host, port); System.out.println("session created."); // disabling StrictHostKeyChecking may help to make connection but makes it insecure // see // http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no // java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); System.out.println("session connected....."); Channel channel = session.openChannel("sftp"); channel.setInputStream(System.in); channel.setOutputStream(System.out); channel.connect(); System.out.println("shell channel connected...."); ChannelSftp c = (ChannelSftp) channel; String fileName = "src/main/resources/test.txt"; c.put(fileName, "./in/"); c.exit(); System.out.println("done"); } catch (Exception e) { System.err.println(e); } }
/** * Retrieves the session for the specified Job. * * @param job * @return * @throws PortalServiceException */ public Session getSession(CloudFileOwner job) throws PortalServiceException { try { JSch jsch = new JSch(); String prvkey = job.getProperty(NCIDetails.PROPERTY_NCI_KEY); jsch.addIdentity(new IdentityString(jsch, prvkey), null); String userName = job.getProperty(NCIDetails.PROPERTY_NCI_USER); Session session = jsch.getSession(userName, endPoint, 22); session.setConfig("StrictHostKeyChecking", "no"); if (!session.isConnected()) { session.connect(); } return session; } catch (JSchException ex) { logger.error("Unable to retrieve SSH session for job " + job.getId() + ":" + ex.getMessage()); logger.debug("Exception:", ex); throw new PortalServiceException("Unable to retrieve SSH session for job " + job.getId(), ex); } }
// @checkstyle ProtectedMethodInFinalClassCheck (10 lines) @Override @RetryOnFailure( attempts = Tv.SEVEN, delay = 1, unit = TimeUnit.MINUTES, verbose = false, randomize = true, types = IOException.class) protected Session session() throws IOException { try { JSch.setConfig("StrictHostKeyChecking", "no"); JSch.setLogger(new JschLogger()); final JSch jsch = new JSch(); final File file = File.createTempFile("jcabi-ssh", ".key"); FileUtils.forceDeleteOnExit(file); FileUtils.write( file, this.key.replaceAll("\r", "").replaceAll("\n\\s+|\n{2,}", "\n").trim(), CharEncoding.UTF_8); jsch.setHostKeyRepository(new EasyRepo()); jsch.addIdentity(file.getAbsolutePath()); Logger.debug( this, "Opening SSH session to %s@%s:%s (%d bytes in RSA key)...", this.getLogin(), this.getAddr(), this.getPort(), file.length()); final Session session = jsch.getSession(this.getLogin(), this.getAddr(), this.getPort()); session.setServerAliveInterval((int) TimeUnit.SECONDS.toMillis(Tv.TEN)); session.setServerAliveCountMax(Tv.MILLION); session.connect(); FileUtils.deleteQuietly(file); return session; } catch (final JSchException ex) { throw new IOException(ex); } }
private void newSession() throws JSchException { JSch jsch = new JSch(); session = null; try { session = jsch.getSession(username, host, port); if (timeout != 0) session.setTimeout(timeout); logger.debug("%s@%s:%d: Session created.", username, host, port); if (password != null) { session.setPassword(password); } else { // jsch wipes out your private key jsch.addIdentity( username, Arrays.copyOf(privateKey, privateKey.length), null, emptyPassPhrase); } } catch (JSchException e) { throw new SshException( String.format("%s@%s:%d: Error creating session.", username, host, port), e); } java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); logger.debug("%s@%s:%d: Session connected.", username, host, port); }