ChannelSftp init(String filename) throws JSchException, UnsupportedEncodingException { jsch = new JSch(); ConnectionInfo ci = splitStringToConnectionInfo(filename); Session session = jsch.getSession(ci.username, ci.host, ci.port); UserInfo ui = new SftpUserInfo(ci.password); session.setUserInfo(ui); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp c = (ChannelSftp) channel; logDebug("success: init Sftp"); return c; }
/** * * Scp file from remote server * * @param host * @param user * @param password * @param remoteFile * @param localFile * @throws JSchException * @throws IOException */ public void scpFileFromRemoteServer(String host, String user, String password, String remoteFile, String localFile) throws JSchException, IOException { String prefix = null; if (new File(localFile).isDirectory()) { prefix = localFile + File.separator; } JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo userInfo = new UserInformation(password); session.setUserInfo(userInfo); session.connect(); // exec 'scp -f remoteFile' remotely String command = "scp -f " + remoteFile; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); channel.connect(); byte[] buf = new byte[1024]; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); readRemoteFileAndWriteToLocalFile(localFile, prefix, out, in, buf); session.disconnect(); }
@Override public Session create(ServerDetails serverDetails) throws Exception { Session session = null; try { JSch jsch = new JSch(); if (serverDetails.getPrivateKeyLocation() != null) { jsch.addIdentity(serverDetails.getPrivateKeyLocation()); } session = jsch.getSession(serverDetails.getUser(), serverDetails.getHost(), serverDetails.getPort()); session.setConfig("StrictHostKeyChecking", "no"); // UserInfo userInfo = new JschUserInfo(serverDetails.getUser(), serverDetails.getPassword()); session.setUserInfo(userInfo); session.setTimeout(60000); session.setPassword(serverDetails.getPassword()); session.connect(); } catch (Exception e) { throw new RuntimeException( "ERROR: Unrecoverable error when trying to connect to serverDetails : " + serverDetails, e); } return session; }
/** * Gets SSH Client * * @return */ @SneakyThrows(JSchException.class) public Session get() { JSch jsch = new JSch(); UserInfo userInfo; Session session = jsch.getSession(username, hostname, port); if (useKey) { jsch.addIdentity(key); userInfo = new EmbeddedUserInfoInteractive(); } else { session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); userInfo = EmbeddedUserInfo.builder().password(password).build(); } session.setUserInfo(userInfo); session.setConfig("HashKnownHosts", "yes"); session.setTimeout(10000); session.connect(); return session; }
public ChannelSftp connectAndGetSftpChannel() throws JSchException { JSch jsch = new JSch(); jsch.setKnownHosts(context.getFilesDir().getAbsolutePath() + File.separator + "jsch_known_hosts"); String username = prefs.sshUserName().getOr(null); String host = prefs.sshServerAddress().getOr(null); String port = prefs.sshServerPort().getOr(null); if (username == null || host == null || port == null) throw new IllegalStateException("Please enter your server settings first"); Session session = jsch.getSession(username, host, Integer.parseInt(port)); UserInfo info = storedOrAskedUserInfo; session.setUserInfo(info); try { session.connect(5000); storedOrAskedUserInfo.confirmPasswordRight(); } catch (JSchException je) { if ("auth fail".equals(je.getMessage().toLowerCase())) { // undocumented! storedOrAskedUserInfo.clearPassword(); } throw je; } ChannelSftp channel = (ChannelSftp)session.openChannel("sftp"); channel.connect(5000); return channel; }
public SshXpraConnector(XpraClient client, String host, String username, int port, UserInfo userInfo) { super(client); this.host = host; this.username = username; this.port = port; this.userInfo = userInfo; JSch.setConfig("compression_level", "0"); }
void wrapAuthentication(TransportCommand command, UsernamePasswordCredentialsProvider ownerAuth, String sshPassword, File credentialsFile, List<String> credentialsList, UserInfo userInfo) { if (ownerAuth != null) command.setCredentialsProvider(ownerAuth); else command.setCredentialsProvider(new ElegitCredentialsProvider(credentialsList)); command.setTransportConfigCallback( new TransportConfigCallback() { @Override public void configure(Transport transport) { if (transport instanceof TransportGitSsh) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(sshSessionFactory); } } }); }
@Override public void connect() throws SocketException, IOException { try { session = jsch.getSession(username,host.getHostAddress() , port); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); UserInfo ui=new UserInfoImpl(password,null); session.setUserInfo(ui); if(timeout>0) session.setTimeout(timeout); session.connect(); Channel channel=session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp)channel; // check fingerprint if(!StringUtil.isEmpty(fingerprint)) { if(!fingerprint.equalsIgnoreCase(fingerprint())) { disconnect(); throw new IOException("given fingerprint is not a match."); } } handleSucess(); } catch(JSchException e){ handleFail(e, stopOnError); } }
/** * Gets the information related to memory utilization for each node. * * @param config * the config * @param nodeIp * the node ip * @return list of pojos containing memory utilization info for each node * @throws JSchException * the j sch exception * @throws IOException * Signals that an I/O exception has occurred. */ public Map<String, String> getMemoryUtilisation(Config config, String nodeIp) throws JSchException, IOException { JobConfig jobConfig = (JobConfig)config; Slave slave = RemoteFileUtil.findSlave(nodeIp, jobConfig.getSlaves()); String user = slave.getUser(); String rsaFilePath = jobConfig.getMaster().getRsaFile(); String dsaFilePath = jobConfig.getMaster().getDsaFile(); Session session = null; Map<String, String> vmStats = null; try { session = createSession(user, nodeIp, rsaFilePath, dsaFilePath); UserInfo ui = new JumbuneUserInfo(); session.setUserInfo(ui); session.connect(); vmStats = getVmStats(session); } finally { session.disconnect(); } return vmStats; }
/** * For creating a JSCH session. * * @param user * the user * @param host * the host * @param rsaFilePath * the rsa file path * @param dsaFilePath * the dsa file path * @return a JSCH session * @throws JSchException * the j sch exception */ public static Session createSession(String user, String host, String rsaFilePath, String dsaFilePath, CommandType commandType) throws JSchException { JSch jsch = new JSch(); Session session = null; SwitchedIdentity switchedIdentity = changeIdentityAsPerCommand(user, rsaFilePath, dsaFilePath, commandType); if(commandType.equals(CommandType.FS)){ jsch.addIdentity(switchedIdentity.getPrivatePath()); } java.util.Properties conf = new java.util.Properties(); session = jsch.getSession(switchedIdentity.getUser(), host, RemotingConstants.TWENTY_TWO); UserInfo info = getSwitchedUser(commandType, switchedIdentity); session.setUserInfo(info); conf.put(STRICT_HOST_KEY_CHECKING, "no"); session.setConfig(conf); LOGGER.debug("Session Established, for user ["+switchedIdentity.getUser()+"]"); return session; }
public static boolean verifyPassword(String user, String encryptedPasswrd) throws JSchException { 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; }
/** * Execute command * @param host * @param user * @param passwd * @param cmd * @return String the reply of remote session */ public String execCmd (String host, String user, String passwd, String cmd){ String replyy = ""; String reply = null; try{ JSch jsch=new JSch(); Session session=jsch.getSession(user, host, 22); UserInfo ui = new MyUserInfo(passwd); session.setUserInfo(ui); session.setTimeout(600000); session.connect(); Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand(cmd); channel.setInputStream(null); InputStreamReader in = new InputStreamReader(channel.getInputStream()); OutputStreamWriter out = new OutputStreamWriter(channel.getOutputStream()); BufferedWriter bw = new BufferedWriter(out); BufferedReader br = new BufferedReader(in); channel.connect(); while ((reply = br.readLine()) != null) { bw.write(reply); replyy=replyy+"\n"+reply; bw.flush(); Thread.sleep(100); } while(true){ if(channel.isClosed()){ break; } try{ Thread.sleep(1500); } catch(Exception ee){ } } in.close(); out.close(); br.close(); bw.close(); channel.disconnect(); session.disconnect(); } catch(Exception e){ log.error("ERROR , Possible no connection with : "+user+" "+passwd+ " "+host+"\n\t\t please check LAN and vpn connection or host"); } return replyy; }
/** * Execute SSH command and return output * @param username The ssh user * @param host The host to connect * @param key The ssh key * @param commandssh The command to launch * @return the output of the command */ public String outputCommandSSH(String username, String host, String key, String commandssh){ String res = ""; try{ JSch jsch=new JSch(); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); //avoid host key checking int SSH_port = 22; jsch.addIdentity(key , "passphrase"); Session session=jsch.getSession(username, host, SSH_port); //SSH connection if(new Configuration().Debug){ System.out.println("Connection to "+host+" on the port "+SSH_port+" with key: "+key+" and username: "+username); } // username and passphrase will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.setConfig(config); session.connect(); Channel channel=session.openChannel("exec"); // open channel for exec command ((ChannelExec)channel).setCommand(commandssh); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in=channel.getInputStream(); channel.connect(); /* * get output ssh command launched */ byte[] tmp=new byte[1024]; while(true){ while(in.available()>0){ int i=in.read(tmp, 0, 1024); if(i<0)break; res += new String(tmp, 0, i); //System.out.print(new String(tmp, 0, i)); } if(channel.isClosed()){ if(in.available()>0) continue; if(new Configuration().Debug){ System.out.println("exit-status: "+channel.getExitStatus()); } break; } try{Thread.sleep(1000);}catch(Exception ee){} } channel.disconnect(); session.disconnect(); } catch(Exception e){ System.out.println(e); } return res; }
public void connect() { try { session = jsch.getSession(username, server, port); if (logger.isDebugEnabled()) logger.debug(String.format( "login ssh to server %s:%d as user %s password %s", server, port, username, password)); UserInfo ui = new MyUserInfo(password); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(password); // session.setUserInfo(ui); session.connect(); } catch (JSchException e) { throw new RuntimeException(e); } }
public Session createSession(PrintStream logger) { JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession(username, ip, port); session.setPassword(password); UserInfo ui = new GsshUserInfo(password); session.setUserInfo(ui); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setDaemonThread(false); session.connect(); logger.println("create ssh session success with ip=[" + ip + "],port=[" + port + "],username=[" + username + "],password=[*******]"); } catch (Exception e) { logger.println("create ssh session failed with ip=[" + ip + "],port=[" + port + "],username=[" + username + "],password=[*******]"); e.printStackTrace(logger); throw new GsshPluginException(e); } return session; }
/** * Opens up a connection to specified host using the username. Connects to the source using a private key without * prompting for a password. This method does not support connecting to a source using a password, only by private * key * @throws gobblin.source.extractor.filebased.FileBasedHelperException */ @Override public void connect() throws FileBasedHelperException { String privateKey = PasswordManager.getInstance(state).readPassword(state.getProp(ConfigurationKeys.SOURCE_CONN_PRIVATE_KEY)); String knownHosts = state.getProp(ConfigurationKeys.SOURCE_CONN_KNOWN_HOSTS); String userName = state.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME); String hostName = state.getProp(ConfigurationKeys.SOURCE_CONN_HOST_NAME); int port = state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_PORT, ConfigurationKeys.SOURCE_CONN_DEFAULT_PORT); String proxyHost = state.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL); int proxyPort = state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT, -1); JSch.setLogger(new JSchLogger()); JSch jsch = new JSch(); log.info( "Attempting to connect to source via SFTP with" + " privateKey: " + privateKey + " knownHosts: " + knownHosts + " userName: " + userName + " hostName: " + hostName + " port: " + port + " proxyHost: " + proxyHost + " proxyPort: " + proxyPort); try { jsch.addIdentity(privateKey); jsch.setKnownHosts(knownHosts); session = jsch.getSession(userName, hostName, port); if (proxyHost != null && proxyPort >= 0) { session.setProxy(new ProxyHTTP(proxyHost, proxyPort)); } UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); session.connect(); log.info("Finished connecting to source"); } catch (JSchException e) { if (session != null) { session.disconnect(); } log.error(e.getMessage(), e); throw new FileBasedHelperException("Cannot connect to SFTP source", e); } }
/** * Configures the transport of the command to deal with things like SSH */ public static <C extends GitCommand> void configureCommand(TransportCommand<C, ?> command, CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey) { if (sshPrivateKey != null) { final CredentialsProvider provider = credentialsProvider; command.setTransportConfigCallback(new TransportConfigCallback() { @Override public void configure(Transport transport) { if (transport instanceof SshTransport) { SshTransport sshTransport = (SshTransport) transport; SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host host, Session session) { session.setConfig("StrictHostKeyChecking", "no"); UserInfo userInfo = new CredentialsProviderUserInfo(session, provider); session.setUserInfo(userInfo); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { JSch jsch = super.createDefaultJSch(fs); jsch.removeAllIdentity(); String absolutePath = sshPrivateKey.getAbsolutePath(); if (LOG.isDebugEnabled()) { LOG.debug("Adding identity privateKey: " + sshPrivateKey + " publicKey: " + sshPublicKey); } if (sshPublicKey != null) { jsch.addIdentity(absolutePath, sshPublicKey.getAbsolutePath(), null); } else { jsch.addIdentity(absolutePath); } return jsch; } }; sshTransport.setSshSessionFactory(sshSessionFactory); } } }); } }
public RepoHelper(Path directoryPath, UserInfo userInfo) throws GitAPIException, IOException, CancelledAuthorizationException { this.localPath = directoryPath; this.ownerAuth = null; this.password = null; this.credentialsFile = null; this.userInfo = userInfo; setupSshSessionFactory(); }
public RepoHelper(Path directoryPath, String sshPassword, UserInfo userInfo) throws GitAPIException, IOException, CancelledAuthorizationException { this.localPath = directoryPath; this.ownerAuth = null; this.password = sshPassword; this.credentialsFile = null; this.userInfo = userInfo; setupSshSessionFactory(); }
/** * Enforce server reconnection (closes the current connection if it is still alive) */ public synchronized void connect() throws SFTPConnectionException { //checkLocked(); try { // Try to disconnect this.disconnect(); // Open new connection Logger.defaultLogger().info("Trying to connect to server : " + this.remoteServer + " ..."); debug("connect : connect", remoteServer); JSch jsch = new JSch(); if (checkHostKey) { HostKeyRepository hkr = jsch.getHostKeyRepository(); byte[] keybytes = this.getHostKeyAsByteArray(); if (keybytes == null) { throw new SFTPConnectionException("Incorrect hostkey : " + this.getHostKeyAsString()); } HostKey key = new HostKey(remoteServer, keybytes); hkr.add(key, null); jsch.setHostKeyRepository(hkr); } if (useCertificateAuth) { if (certificateFileName == null || certificateFileName.trim().length() == 0 || ! FileSystemManager.exists(new File(certificateFileName))) { throw new SFTPConnectionException("Certificate file not set or not found : " + certificateFileName); } else { Logger.defaultLogger().info("Using private key file : " + certificateFileName); if (certificateFileName.toLowerCase().endsWith(".ppk")) { Logger.defaultLogger().warn("Your private key file seems to be in PuTTY's \"ppk\" file format. Please convert it to the standard OpenSSH format (this can be done by using the \"puttygen.exe\" utility - see \"Convertions\" menu.)"); } jsch.addIdentity(certificateFileName); } } session = jsch.getSession(login, remoteServer, remotePort); UserInfo ui = new DefaultUserInfo(this.password, certPassPhrase, certificateFileName); session.setUserInfo(ui); session.setDaemonThread(true); session.setConfig("StrictHostKeyChecking", checkHostKey ? "yes":"no"); String preferredAuth; String configuredPAuth = FrameworkConfiguration.getInstance().getSftpPreferredAuthOverride(); if (configuredPAuth != null && configuredPAuth.trim().length() != 0) { preferredAuth = configuredPAuth; } else { preferredAuth = useCertificateAuth ? "publickey,password" : "password,publickey"; } Logger.defaultLogger().fine("Authentication methods: " + preferredAuth); session.setConfig("PreferredAuthentications", preferredAuth); session.setTimeout(FrameworkConfiguration.getInstance().getSFTPTimeout()); Logger.defaultLogger().info("Trying to log in with user : " + this.login + " (" + (useCertificateAuth ? "certificate":"password") + ") ..."); debug("connect : login", login); session.connect(); client = (ChannelSftp)session.openChannel("sftp"); client.connect(); this.connectionId = Util.getRndLong(); this.updateOpTime(); Logger.defaultLogger().info("Connected to server : " + this.remoteServer); } catch (JSchException e) { resetClient(e); throw new SFTPConnectionException("Unable to connect to server : " + this.remoteServer + " (" + e.getMessage() + ")"); } finally { clearCache(); } }
/** * <<<<<<< Updated upstream Returns CPU stats(usage,num of cores,threads per core) for each node of the cluster. ======= Returns CPU * stats(usage,num of cores,threads per core) for each node of the cluster. >>>>>>> Stashed changes * * @param config * the config * @param nodeIp * the node ip * @return the list of pojos for CPU stats for each node * @throws AttributeNotFoundException * the attribute not found exception * @throws InstanceNotFoundException * the instance not found exception * @throws IntrospectionException * the introspection exception * @throws MBeanException * the m bean exception * @throws ReflectionException * the reflection exception * @throws IOException * Signals that an I/O exception has occurred. * @throws JSchException * the j sch exception */ public Map<String, String> getCPUStats(Config config, String nodeIp) throws AttributeNotFoundException, InstanceNotFoundException, IntrospectionException, MBeanException, ReflectionException, IOException, JSchException { JobConfig jobConfig = (JobConfig)config; Slave slave = RemoteFileUtil.findSlave(nodeIp, jobConfig.getSlaves()); String user = slave.getUser(); String rsaFilePath = jobConfig.getMaster().getRsaFile(); String dsaFilePath = jobConfig.getMaster().getDsaFile(); Session session = null; Map<String, String> cpuStats = new HashMap<String, String>(); try { session = createSession(user, nodeIp, rsaFilePath, dsaFilePath); UserInfo ui = new JumbuneUserInfo(); session.setUserInfo(ui); session.connect(); cpuStats.put("cpuUsage", String.valueOf(getCPUUsage(session))); List<Integer> cpuDetails = getCPUDetails(session); cpuStats.put("numberOfCores", String.valueOf(cpuDetails.get(1))); cpuStats.put("threadsPerCore", String.valueOf(cpuDetails.get(0))); } finally { if (session != null) { session.disconnect(); } } return cpuStats; }
private static UserInfo getSwitchedUser(CommandType commandType, SwitchedIdentity switchedIdentity){ UserInfo info; if(commandType.equals(CommandType.HADOOP_FS)){ info = new JumbuneUserInfo(StringUtil.getPlain(switchedIdentity.getPasswd())); }else if(commandType.equals(CommandType.HADOOP_JOB)){ info = new JumbuneUserInfo(StringUtil.getPlain(switchedIdentity.getPasswd())); }else if(commandType.equals(CommandType.MAPRED)){ info = new JumbuneUserInfo(StringUtil.getPlain(switchedIdentity.getPasswd())); }else{ info = new JumbuneUserInfo(); } return info; }
@Override protected void configure() { install(RepositoryScope.module()); install(OperationScope.module()); bind(UserInfo.class).to(GUIUserInfo.class); bind(ImageSession.class).toProvider(ImageSessionProvider.class).in(ContextSingleton.class); bind(Repository.class).toProvider(RepositoryProvider.class); bind(Ref.class).annotatedWith(named("branch")).toProvider(BranchRefProvider.class); bind(AndroidAuthAgent.class).toProvider(AndroidAuthAgentProvider.class); bind(GitAsyncTaskFactory.class).toProvider(newFactory(GitAsyncTaskFactory.class, GitAsyncTask.class)); bind(ContextScopedViewInflatorFactory.class).toProvider(newFactory(ContextScopedViewInflatorFactory.class, ContextScopedViewInflator.class)); bind(SyncCampaignFactory.class).toProvider(newFactory(SyncCampaignFactory.class, SyncCampaign.class)); bind(TransportConfigCallback.class).to(AgitTransportConfig.class); bind(CredentialsProvider.class).to(GUICredentialsProvider.class); bind(SshSessionFactory.class).to(AndroidSshSessionFactory.class); bind(PromptUIRegistry.class); bind(HostKeyRepository.class).to(CuriousHostKeyRepository.class); bind(PromptUI.class).annotatedWith(named("status-bar")).to(StatusBarPromptUI.class); bind(RepoDomainType.class).annotatedWith(named("branch")).to(RDTBranch.class); bind(RepoDomainType.class).annotatedWith(named("remote")).to(RDTRemote.class); bind(RepoDomainType.class).annotatedWith(named("tag")).to(RDTTag.class); bind(CommitViewHolderFactory.class).toProvider(newFactory(CommitViewHolderFactory.class, CommitViewHolder.class)); bind(BranchViewHolderFactory.class).toProvider(newFactory(BranchViewHolderFactory.class, BranchViewHolder.class)); }
@Inject public AndroidSshSessionFactory(Provider<AndroidAuthAgent> androidAuthAgentProvider, UserInfo userInfo, HostKeyRepository hostKeyRepository) { this.androidAuthAgentProvider = androidAuthAgentProvider; this.userInfo = userInfo; this.hostKeyRepository = hostKeyRepository; }
/** * Opens up a connection to specified host using the username. Connects to the source using a private key without * prompting for a password. This method does not support connecting to a source using a password, only by private * key * @throws org.apache.gobblin.source.extractor.filebased.FileBasedHelperException */ @Override public void connect() throws FileBasedHelperException { String privateKey = PasswordManager.getInstance(this.state) .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PRIVATE_KEY)); String password = PasswordManager.getInstance(this.state) .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD)); String knownHosts = this.state.getProp(ConfigurationKeys.SOURCE_CONN_KNOWN_HOSTS); String userName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME); String hostName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_HOST_NAME); int port = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_PORT, ConfigurationKeys.SOURCE_CONN_DEFAULT_PORT); String proxyHost = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL); int proxyPort = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT, -1); JSch.setLogger(new JSchLogger()); JSch jsch = new JSch(); log.info("Attempting to connect to source via SFTP with" + " privateKey: " + privateKey + " knownHosts: " + knownHosts + " userName: " + userName + " hostName: " + hostName + " port: " + port + " proxyHost: " + proxyHost + " proxyPort: " + proxyPort); try { if (!Strings.isNullOrEmpty(privateKey)) { List<IdentityStrategy> identityStrategies = ImmutableList.of(new LocalFileIdentityStrategy(), new DistributedCacheIdentityStrategy(), new HDFSIdentityStrategy()); for (IdentityStrategy identityStrategy : identityStrategies) { if (identityStrategy.setIdentity(privateKey, jsch)) { break; } } } this.session = jsch.getSession(userName, hostName, port); this.session.setConfig("PreferredAuthentications", "publickey,password"); if (Strings.isNullOrEmpty(knownHosts)) { log.info("Known hosts path is not set, StrictHostKeyChecking will be turned off"); this.session.setConfig("StrictHostKeyChecking", "no"); } else { jsch.setKnownHosts(knownHosts); } if (!Strings.isNullOrEmpty(password)) { this.session.setPassword(password); } if (proxyHost != null && proxyPort >= 0) { this.session.setProxy(new ProxyHTTP(proxyHost, proxyPort)); } UserInfo ui = new MyUserInfo(); this.session.setUserInfo(ui); this.session.setDaemonThread(true); this.session.connect(); log.info("Finished connecting to source"); } catch (JSchException e) { if (this.session != null) { this.session.disconnect(); } log.error(e.getMessage(), e); throw new FileBasedHelperException("Cannot connect to SFTP source", e); } }
public boolean openSession() { if (session == null || !session.isConnected()) { try { session = jsch.getSession(sshUser, sshHost, sshPort); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); UserInfo ui = new SSHUserInfo(); session.setUserInfo(ui); if (!"".equals(sshPass)) session.setPassword(sshPass); if (!session.isConnected()) session.connect(); if (session.isConnected()) return true; } catch (Exception e) { e.printStackTrace(); } } return false; // if(session != null && session.isConnected()) // System.out.println("Open Session"); }
private SSHSocketImplFactory(String host) throws JSchException, IOException { JSch jsch = new JSch(); jsch.setLogger(this); String passphrase = ""; String defaultSSHDir = System.getProperty("user.home") + "/.ssh"; String identityFile = defaultSSHDir + "/openid"; String user = System.getProperty("user.name"); user = System.getProperty("ssh.user", user); if (host == null) { throw new RuntimeException( "ssh.gateway system property must be set"); } String knownHosts = defaultSSHDir + "/known_hosts"; knownHosts = System.getProperty("ssh.knownhosts", knownHosts); jsch.setKnownHosts(knownHosts); identityFile = System.getProperty("ssh.identity", identityFile); jsch.addIdentity(identityFile, passphrase.getBytes()); session = jsch.getSession(user, host); Properties props = new Properties(); props.put("compression.s2c", "none"); props.put("compression.c2s", "none"); props.put("cipher.s2c", "blowfish-cbc,3des-cbc"); props.put("cipher.c2s", "blowfish-cbc,3des-cbc"); if (jsch.getHostKeyRepository().getHostKey(host, null) == null) { // We don't have a way to prompt, so if it isn't there we want // it automatically added. props.put("StrictHostKeyChecking", "no"); } session.setConfig(props); session.setDaemonThread(true); // We have to make sure that SSH uses it's own socket factory so // that we don't get recursion SocketFactory sfactory = new SSHSocketFactory(); session.setSocketFactory(sfactory); UserInfo userinfo = null; session.setUserInfo(userinfo); session.connect(); if (!session.isConnected()) { throw new IOException("Session not connected"); } }
public static void main(String[] args) throws JSchException, SftpException{ String host = "221.211.14.5"; String user="transfer"; String pass="pt25VC%"; Integer port=59830; JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); UserInfo ui = new SUserInfo(pass, null); session.setUserInfo(ui); session.setPassword(pass); session.connect(); ChannelSftp sftp = (ChannelSftp)session.openChannel("sftp"); sftp.connect(); System.out.println("Directorio Actual: " + sftp.pwd() ); // /emc2z/expunico/L0000155/U0074353879 sftp.cd("/emc2z/expunico/L0000155/U0074353879"); System.out.println("Directorio Actual: " + sftp.pwd() ); sftp.exit(); sftp.disconnect(); session.disconnect(); System.out.println("----------------- FIN"); //// FTPClient ftpCliente = new FTPClient(); //// String ip = "221.211.14.5"; //// String user="transfer"; //// String pass="pt25VC%"; //// Integer port=59830; //// Boolean login; //// //// ftpCliente.connect( ip, port); //// login = ftpCliente.login( user , pass); //// System.out.println("login: " + login); }
public void connect() throws BaseException { JSch jsch = new JSch(); count = 0; try { sess = jsch.getSession(user, host, 22); sess.setPassword(passwd); UserInfo ui = new MyUserInfo(); sess.setUserInfo(ui); sess.connect(); } catch (Exception e) { throw new BaseException("JSch create session error.", e); } }
@Override public void add(HostKey hostkey, UserInfo ui) {}
@Override public void add(HostKey hostkey, UserInfo ui) { // nothing to do }
public RepoHelper(UserInfo userInfo) { this.userInfo = userInfo; setupSshSessionFactory(); }
void wrapAuthentication(TransportCommand command, UserInfo userInfo) { wrapAuthentication(command, null, null, null, null, userInfo); }
ExistingRepoHelper(Path directoryPath, UserInfo userInfo) throws IOException, GitAPIException, CancelledAuthorizationException{ super(directoryPath, userInfo); repo = obtainRepository(); setup(); }