public static void fileFetch(String host, String user, String keyLocation, String sourceDir, String destDir) { JSch jsch = new JSch(); Session session = null; try { // set up session session = jsch.getSession(user,host); // use private key instead of username/password session.setConfig( "PreferredAuthentications", "publickey,gssapi-with-mic,keyboard-interactive,password"); jsch.addIdentity(keyLocation); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); // copy remote log file to localhost. ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); channelSftp.get(sourceDir, destDir); channelSftp.exit(); } catch (Exception e) { e.printStackTrace(); } finally { session.disconnect(); } }
/** * Executes a given command. It opens exec channel for the command and closes * the channel when it's done. * * @param session ssh connection to a remote server * @param command command to execute * @return command output string if the command succeeds, or null */ private static String executeCommand(Session session, String command) { if (session == null || !session.isConnected()) { return null; } log.trace("Execute command {} to {}", command, session.getHost()); try { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream output = channel.getInputStream(); channel.connect(); String result = CharStreams.toString(new InputStreamReader(output)); channel.disconnect(); log.trace("Result of command {} on {}: {}", command, session.getHost(), result); return result; } catch (JSchException | IOException e) { log.error("Failed to execute command {} on {} due to {}", command, session.getHost(), e.toString()); return null; } }
public static String connectAndExecute(String user, String host, String password, String command1) { String CommandOutput = null; try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig(config); session.connect(); // System.out.println("Connected"); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command1); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; // System.out.print(new String(tmp, 0, i)); CommandOutput = new String(tmp, 0, i); } if (channel.isClosed()) { // System.out.println("exit-status: " + // channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); // System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); } return CommandOutput; }
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; }
private Session createSession(String host, Args args) throws JSchException { JSch jsch = new JSch(); for (String keyFile : getKeyFiles()) { jsch.addIdentity(keyFile); } JSch.setLogger(new LogAdapter()); Session session = jsch.getSession(args.user, host, args.sshPort); session.setConfig("StrictHostKeyChecking", "no"); return session; }
public static Session establishWithKey(String sshHost, int sshPort, String user, String keyFilePath) throws JSchException { File keyFile = new File(keyFilePath); if (!keyFile.exists()) { String errorMsg = "Could not find SSH public key file in path: " + keyFilePath; logger.info(errorMsg); throw new JSchException(errorMsg); } Session session; JSch jsch = new JSch(); try { jsch.addIdentity(keyFile.getAbsolutePath()); session = jsch.getSession(user, sshHost, sshPort); } catch (JSchException e) { logger.error("SSH connection attempt to host: " + sshHost + ":" + sshPort + " failed"); throw e; } return connect(session, sshHost, sshPort); }
@Test public void testJschConnection() throws InterruptedException, SftpException, JSchException, IOException { JSch jsch = new JSch(); String passphrase = ""; jsch.addIdentity(privateKey, StringUtil.isEmpty(passphrase) ? null : passphrase); Session session = jsch.getSession(user, host, port); System.out.println("session created."); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); config.put("PreferredAuthentications", "publickey,keyboard-interactive,password"); session.setConfig(config); session.connect(); Thread.sleep(500); session.disconnect(); }
public synchronized void close() throws IOException { if (closed) { return; } super.close(); closed = true; if (!channel.isConnected()) { throw new IOException(E_CLIENT_NOTCONNECTED); } try { Session session = channel.getSession(); channel.disconnect(); session.disconnect(); } catch (JSchException e) { throw new IOException(StringUtils.stringifyException(e)); } }
private synchronized void keepSessionConnected(Channel channel){ try { Session session = channel.getSession(); boolean contains = false; for(Entry<Session, Integer> e2 : usedSessions.entrySet()){ if (e2.getKey() == session) { contains = true; break; } } if(contains){ usedSessions.put(session,usedSessions.get(session)+1); } else { usedSessions.put(session, 1); } } catch (JSchException e) { e.printStackTrace(); } }
public synchronized void releaseSession(Channel channel) { try { Session session = channel.getSession(); boolean contains = false; for(Entry<Session, Integer> e2 : usedSessions.entrySet()){ if (e2.getKey() == session) { contains = true; break; } } if(contains){ if(usedSessions.get(session)<=1){ usedSessions.remove(session); if(!sessions.values().contains(session)) channel.getSession().disconnect(); } else{ usedSessions.put(session, usedSessions.get(session) - 1); } } } catch (JSchException e) { e.printStackTrace(); } }
public synchronized void removeSession(Uri cred){ for(Entry<Credential, Session> e : sessions.entrySet()){ Uri uri = Uri.parse(e.getKey().getUriString()); if(uri.getHost().equals(cred.getHost())&&uri.getPort()==cred.getPort()){ boolean doNotDisconnect = false; for(Entry<Session, Integer> e2 : usedSessions.entrySet()){ if (e2.getKey() == e.getValue()) { doNotDisconnect = true; break; } } if(!doNotDisconnect) { e.getValue().disconnect(); } sessions.remove(e.getKey()); } } }
@Override public Session create(ConnectionDetails connectionDetails) throws Exception { log.debug("Creating session for "+connectionDetails); Session session = null; try { byte[] privateKey = connectionDetails.getPrivateKey(); if (privateKey != null) { jsch.addIdentity(connectionDetails.getUsername(), privateKey, null, connectionDetails.getPassword().getBytes()); } session = jsch.getSession(connectionDetails.getUsername(), connectionDetails.getHost(), connectionDetails.getPort()); session.setPassword(connectionDetails.getPassword()); if (!hostKeyValidation) { session.setConfig("StrictHostKeyChecking", "no"); } session.setDaemonThread(true); session.connect(); } catch (Exception e) { log.error("Failed to connect to "+connectionDetails); throw e; } return session; }
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; }
public void filenameChange(String filename) { String cmdchange = "cd " + remoteEnvPath + "; mv spark-env " + filename; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdchange); System.out.println("Here is SUT start information:"); System.out.println("Succeed in changing filename of spark-env!"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to change filename of spark-env!"); } }
public void removeRemoteConfigFile(String filename) { String cmdRemove = "cd " + remotePath + "; rm -f " + filename; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdRemove); System.out.println("Here is SUT start information:"); System.out.println("Succeed in removing configuration file!"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to remove configuration file!"); } }
public void removeRemoteEnvConfigFile(String filename) { String cmdRemove = "cd " + remoteEnvPath + "; rm -f " + filename; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdRemove); System.out.println("Here is SUT start information:"); System.out.println("Succeed in removing configuration file of env!"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to remove configuration file of env!"); } }
private void removeRemoteConfigFile(String filename) { String cmdRemove = "cd " + remotePath + "; rm -f " + filename; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdRemove); System.out.println("Here is SUT start information:"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to remove config file!"); } }
public void changeRemoteConfFileName(String filename) { String cmdChangeName = "cd " + remotePath + "; mv " + filename + " cassandra.yaml"; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdChangeName); System.out.println("Here is SUT start information:"); System.out.println("Remote config filename had been successfully changed!"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to change remote config filename!"); } }
public void removeRemoteConfigFile(String filename) { String cmdRemove = "cd " + remotePath + "; rm -f " + filename; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdRemove); System.out.println("Here is SUT start information:"); System.out.println("Config file had been removed successfully!"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to remove config file!"); } }
public void removeRemoteConfigFile(String filename) { String cmdRemove = "cd " + remotePath + "; rm -f " + filename; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdRemove); System.out.println("Here is SUT start information:"); System.out.println("Config file had been successfully removed!"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to remove config file!"); } }
public void removeRemoteConfigFile(String filename) { String cmdRemove = "cd " + remotePath + "; rm -f " + filename; try { ch.ethz.ssh2.Session session = this.getConnection().openSession(); session.execCommand(cmdRemove); System.out.println("Here is SUT start information:"); System.out.println("Configuration file had been successfully removed!"); if (session != null) session.close(); closeConnection(); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to remove configuration file!"); } }
public Message validateCredentials(String host, String user, String password) { JSch jsch = new JSch(); Session session; try { session = jsch.getSession(user, host, SSH_PORT); session.setPassword(password); java.util.Properties config = new java.util.Properties(); config.put(STRICT_HOST_KEY_CHECKING, STRICT_HOST_KEY_CHECKING_DEFAULT_VALUE); session.setConfig(config); session.setConfig(PREFERRED_AUTHENTICATIONS, PREFERRED_AUTHENTICATIONS_DEFAULT_VALUES); session.connect(); session.disconnect(); } catch (Exception e) { return getErrorMessage(e); } return new Message(MessageType.SUCCESS, GENERAL_SUCCESS_MESSAGE); }
/** * * 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(); }
/** * @param host * @param user * @param pwd * @param remoteFile */ public void deleteFile(String host, String user, String pwd, String remoteFile) { try { JSch ssh = new JSch(); Session session = ssh.getSession(user, host, 22); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(pwd); session.connect(); Channel channel = session.openChannel("exec"); channel.connect(); String command = "rm -rf " + remoteFile; System.out.println("command: " + command); // ((ChannelExec) channel).setCommand(command); channel.disconnect(); session.disconnect(); } catch (JSchException e) { System.out.println(e.getMessage().toString()); e.printStackTrace(); } }
private void initSessionFactory() { JschConfigSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(Host host, Session session) { session.setConfig("StrictHostKeyChecking", "no"); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { JSch jSch = super.createDefaultJSch(fs); // apply customized private key if (privateKeyPath != null) { jSch.removeAllIdentity(); jSch.addIdentity(privateKeyPath.toString()); } return jSch; } }; transportConfigCallback = transport -> { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(sshSessionFactory); }; }
@Test public void testSecureCopyFile() throws JSchException, IOException { final JschBuilder mockJschBuilder = mock(JschBuilder.class); final JSch mockJsch = mock(JSch.class); final Session mockSession = mock(Session.class); final ChannelExec mockChannelExec = mock(ChannelExec.class); final byte [] bytes = {0}; final ByteArrayOutputStream out = new ByteArrayOutputStream(); when(mockChannelExec.getInputStream()).thenReturn(new TestInputStream()); when(mockChannelExec.getOutputStream()).thenReturn(out); when(mockSession.openChannel(eq("exec"))).thenReturn(mockChannelExec); when(mockJsch.getSession(anyString(), anyString(), anyInt())).thenReturn(mockSession); when(mockJschBuilder.build()).thenReturn(mockJsch); when(Config.mockSshConfig.getJschBuilder()).thenReturn(mockJschBuilder); when(Config.mockRemoteCommandExecutorService.executeCommand(any(RemoteExecCommand.class))).thenReturn(mock(RemoteCommandReturnInfo.class)); final String source = BinaryDistributionControlServiceImplTest.class.getClassLoader().getResource("binarydistribution/copy.txt").getPath(); binaryDistributionControlService.secureCopyFile("someHost", source, "./build/tmp"); verify(Config.mockSshConfig).getJschBuilder(); assertEquals("C0644 12 copy.txt\nsome content\0", out.toString(StandardCharsets.UTF_8)); }
@Test public void testTestCommand() throws JSchException, IOException { JSch jsch = new JSch(); Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort()); jsch.addIdentity("src/test/resources/id_rsa"); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); ChannelShell channel = (ChannelShell) session.openChannel("shell"); PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(); channel.setInputStream(new PipedInputStream(pos)); channel.setOutputStream(new PipedOutputStream(pis)); channel.connect(); pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8)); pos.flush(); verifyResponse(pis, "test run bob"); pis.close(); pos.close(); channel.disconnect(); session.disconnect(); }
protected void sshCall(String username, String password, SshExecutor executor, String channelType) { try { JSch jsch = new JSch(); Session session = jsch.getSession(username, props.getShell().getHost(), props.getShell().getPort()); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel(channelType); PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(); channel.setInputStream(new PipedInputStream(pos)); channel.setOutputStream(new PipedOutputStream(pis)); channel.connect(); try { executor.execute(pis, pos); } finally { pis.close(); pos.close(); channel.disconnect(); session.disconnect(); } } catch(JSchException | IOException ex) { fail(ex.toString()); } }
public static TransportConfigCallback getTransportConfigCallback() { final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host host, Session session) { //session.setPassword(password); } }; return new TransportConfigCallback() { public void configure(Transport transport) { if (transport instanceof TransportHttp) return; SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(sshSessionFactory); } }; }