Java Code Examples for com.jcraft.jsch.Session#setPassword()
The following examples show how to use
com.jcraft.jsch.Session#setPassword() .
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: MultiUserSshSessionFactory.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 7 votes |
private Session createSession(CredentialsProvider credentialsProvider, FS fs, String user, final String pass, String host, int port, final OpenSshConfig.Host hc) throws JSchException { final Session session = createSession(credentialsProvider, hc, user, host, port, fs); // We retry already in getSession() method. JSch must not retry // on its own. session.setConfig("MaxAuthTries", "1"); //$NON-NLS-1$ //$NON-NLS-2$ if (pass != null) session.setPassword(pass); final String strictHostKeyCheckingPolicy = hc .getStrictHostKeyChecking(); if (strictHostKeyCheckingPolicy != null) session.setConfig("StrictHostKeyChecking", //$NON-NLS-1$ strictHostKeyCheckingPolicy); final String pauth = hc.getPreferredAuthentications(); if (pauth != null) session.setConfig("PreferredAuthentications", pauth); //$NON-NLS-1$ if (credentialsProvider != null && !(credentialsProvider instanceof PrivateKeyCredentialsProvider) && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) { session.setUserInfo(new CredentialsProviderUserInfo(session, credentialsProvider)); } configure(hc, session); return session; }
Example 2
Source File: SftpVerifierExtension.java From syndesis with Apache License 2.0 | 6 votes |
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 3
Source File: JschUtil.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * For creating a JSCH session. * * @param host * the host * @return a JSCH session * @throws JSchException * the jsch exception */ public static Session createSession(CommandWritable.Command.SwitchedIdentity switchedIdentity, String host, CommandType commandType) throws JSchException { JSch jsch = new JSch(); Session session = null; if(switchedIdentity.getPrivatePath() != null && !switchedIdentity.getPrivatePath().isEmpty()){ jsch.addIdentity(switchedIdentity.getPrivatePath()); } java.util.Properties conf = new java.util.Properties(); session = jsch.getSession(switchedIdentity.getUser(), host, RemotingConstants.TWENTY_TWO); conf.put(STRICT_HOST_KEY_CHECKING, "no"); if(switchedIdentity.getPasswd()!=null){ try { session.setPassword(StringUtil.getPlain(switchedIdentity.getPasswd())); } catch (Exception e) { LOGGER.error("Unable to get decrypted Password", e); } } session.setConfig(conf); return session; }
Example 4
Source File: SshTunnelHandler.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
/** * Open a tunnel to the remote host. * * @param remoteHost the host to connect to (where ssh will login). * @param remoteSshUser the ssh user. * @param remoteSshPwd the ssh password. * @param localPort the local port to use for the port forwarding (usually the same as the remote). * @param remotePort the remote port to use. * @return the tunnel manager, used also to disconnect when necessary. * @throws JSchException */ public static SshTunnelHandler openTunnel( String remoteHost, String remoteSshUser, String remoteSshPwd, int localPort, int remotePort ) throws JSchException { int port = 22; JSch jsch = new JSch(); Session tunnelingSession = jsch.getSession(remoteSshUser, remoteHost, port); tunnelingSession.setPassword(remoteSshPwd); HMUserInfo lui = new HMUserInfo(""); tunnelingSession.setUserInfo(lui); tunnelingSession.setConfig("StrictHostKeyChecking", "no"); tunnelingSession.setPortForwardingL(localPort, "localhost", remotePort); tunnelingSession.connect(); tunnelingSession.openChannel("direct-tcpip"); return new SshTunnelHandler(tunnelingSession); }
Example 5
Source File: DeploymentEngine.java From Spring-Microservices with MIT License | 5 votes |
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 6
Source File: DeploymentEngine.java From Microservices-Building-Scalable-Software with MIT License | 5 votes |
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 7
Source File: SshdShellAutoConfigurationAuthProviderTest.java From sshd-shell-spring-boot with Apache License 2.0 | 5 votes |
@Test(expected = JSchException.class) public void testDaoFailedAuth() throws JSchException { JSch jsch = new JSch(); Session session = jsch.getSession(props.getShell().getUsername(), props.getShell().getHost(), props.getShell().getPort()); session.setPassword("wrong"); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); }
Example 8
Source File: JSchUtils.java From primecloud-controller with GNU General Public License v2.0 | 5 votes |
/** * TODO: メソッドコメントを記述 * * @param username * @param password * @param host * @param port * @return */ public static Session createSession(String username, String password, String host, int port) { try { JSch jsch = new JSch(); Session session = jsch.getSession(username, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); return session; } catch (JSchException e) { throw new AutoException("ECOMMON-000302", username, host, port); } }
Example 9
Source File: JschServiceImpl.java From jwala with Apache License 2.0 | 5 votes |
/** * Prepare the session by setting session properties * * @param remoteSystemConnection {@link RemoteSystemConnection} * @return {@link Session} * @throws JSchException */ private Session prepareSession(final RemoteSystemConnection remoteSystemConnection) throws JSchException { final Session session = jsch.getSession(remoteSystemConnection.getUser(), remoteSystemConnection.getHost(), remoteSystemConnection.getPort()); final char[] encryptedPassword = remoteSystemConnection.getEncryptedPassword(); if (encryptedPassword != null) { session.setPassword(new DecryptPassword().decrypt(encryptedPassword)); session.setConfig("StrictHostKeyChecking", "no"); session.setConfig("PreferredAuthentications", "password,gssapi-with-mic,publickey,keyboard-interactive"); } return session; }
Example 10
Source File: RemoteCredentialsSupport.java From kork with Apache License 2.0 | 5 votes |
static RemoteCredentials getRemoteCredentials( String command, String user, String host, int port) { RemoteCredentials remoteCredentials = new RemoteCredentials(); try { Session session = jsch.getSession(user, host, port); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); config.put("PreferredAuthentications", "publickey"); config.put("HashKnownHosts", "yes"); session.setConfig(config); session.setPassword(""); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); InputStream is = channel.getInputStream(); channel.setCommand(command); channel.connect(); String output = IOUtils.toString(is); log.debug("Remote credentials: {}", output); channel.disconnect(); session.disconnect(); output = output.replace("\n", ""); remoteCredentials = objectMapper.readValue(output, RemoteCredentials.class); } catch (Exception e) { log.error("Remote SSH execution failed.", e); } return remoteCredentials; }
Example 11
Source File: SFtpClientUtils.java From bamboobsc with Apache License 2.0 | 5 votes |
private static Session getSession(String user, String password, String addr, int port) throws JSchException { Session session = jsch.getSession(user, addr, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); return session; }
Example 12
Source File: SSHClient.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
private Session newJSchSession() throws JSchException { JSch jsch = new JSch(); if (identityPath != null) { jsch.addIdentity(identityPath); } Session session = jsch.getSession(username, hostname, port); if (password != null) { session.setPassword(password); } session.setConfig("StrictHostKeyChecking", "no"); return session; }
Example 13
Source File: SftpClient.java From netbeans with Apache License 2.0 | 5 votes |
private Session createSftpSession(JSch jsch, boolean withUserInfo) throws JSchException { LOGGER.fine("Creating new SFTP session..."); String host = configuration.getHost(); int port = configuration.getPort(); int timeout = configuration.getTimeout() * 1000; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Will connect to {0} [timeout: {1} ms]", new Object[] {host, timeout}); } int keepAliveInterval = configuration.getKeepAliveInterval() * 1000; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Keep-alive interval is {0} ms", keepAliveInterval); } String username = configuration.getUserName(); String password = configuration.getPassword(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Login as {0}", username); } Session session = jsch.getSession(username, host, port); if (StringUtils.hasText(password)) { session.setPassword(password); } // proxy setProxy(session, host); if (withUserInfo) { LOGGER.fine("Setting user info..."); session.setUserInfo(new SftpUserInfo(configuration)); } session.setTimeout(timeout); // keep-alive if (keepAliveInterval > 0) { session.setServerAliveInterval(keepAliveInterval); } return session; }
Example 14
Source File: SshProvider.java From parallec with Apache License 2.0 | 5 votes |
/** * Start ssh session and obtain session. * * @return the session */ public Session startSshSessionAndObtainSession() { Session session = null; try { JSch jsch = new JSch(); if (sshMeta.getSshLoginType() == SshLoginType.KEY) { String workingDir = System.getProperty("user.dir"); String privKeyAbsPath = workingDir + "/" + sshMeta.getPrivKeyRelativePath(); logger.debug("use privkey: path: " + privKeyAbsPath); if (!PcFileNetworkIoUtils.isFileExist(privKeyAbsPath)) { throw new RuntimeException("file not found at " + privKeyAbsPath); } if (sshMeta.isPrivKeyUsePassphrase() && sshMeta.getPassphrase() != null) { jsch.addIdentity(privKeyAbsPath, sshMeta.getPassphrase()); } else { jsch.addIdentity(privKeyAbsPath); } } session = jsch.getSession(sshMeta.getUserName(), targetHost, sshMeta.getSshPort()); if (sshMeta.getSshLoginType() == SshLoginType.PASSWORD) { session.setPassword(sshMeta.getPassword()); } session.setConfig("StrictHostKeyChecking", "no"); } catch (Exception t) { throw new RuntimeException(t); } return session; }
Example 15
Source File: JSchSshSession.java From nomulus with Apache License 2.0 | 5 votes |
/** * Connect to remote SSH endpoint specified by {@code url}. * * @throws JSchException if we fail to open the connection. */ JSchSshSession create(JSch jsch, URI uri) throws JSchException { RdeUploadUrl url = RdeUploadUrl.create(uri); logger.atInfo().log("Connecting to SSH endpoint: %s", url); Session session = jsch.getSession( url.getUser().orElse("domain-registry"), url.getHost(), url.getPort()); if (url.getPass().isPresent()) { session.setPassword(url.getPass().get()); } session.setTimeout((int) sshTimeout.getMillis()); session.connect((int) sshTimeout.getMillis()); return new JSchSshSession(session, url, (int) sshTimeout.getMillis()); }
Example 16
Source File: SftpFileTransferLiveTest.java From tutorials with MIT License | 5 votes |
private ChannelSftp setupJsch() throws JSchException { JSch jsch = new JSch(); jsch.setKnownHosts(knownHostsFileLoc); Session jschSession = jsch.getSession(username, remoteHost); jschSession.setPassword(password); //jschSession.setConfig("StrictHostKeyChecking", "no"); jschSession.connect(); return (ChannelSftp) jschSession.openChannel("sftp"); }
Example 17
Source File: SshRequestHandler.java From trigger with GNU General Public License v2.0 | 4 votes |
public void run() { if (setup.getId() < 0) { this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Internal Error"); return; } if (setup.require_wifi && !WifiTools.isConnected()) { this.listener.onTaskResult(setup.getId(), ReplyCode.DISABLED, "Wifi Disabled."); return; } String command = ""; switch (action) { case open_door: command = setup.open_command; break; case close_door: command = setup.close_command; break; case ring_door: command = setup.ring_command; break; case fetch_state: command = setup.state_command; break; } String user = setup.user; String password = setup.password; String host = setup.host; KeyPair keypair = setup.keypair; int port = setup.port; try { if (command.isEmpty()) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, ""); return; } if (host.isEmpty()) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Host is empty."); return; } // fallback if (setup.user.isEmpty()) { user = "root"; } JSch jsch = new JSch(); if (keypair != null) { SshTools.KeyPairData data = SshTools.keypairToBytes(keypair); byte passphrase[] = new byte[0]; jsch.addIdentity("authkey", data.prvkey, data.pubkey, passphrase); } Session session = jsch.getSession(user, host, port); if (password.length() > 0) { session.setPassword(password); } session.setConfig("StrictHostKeyChecking", "no"); StringBuilder outputBuffer = new StringBuilder(); try { session.connect(5000); // 5sec timeout Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); InputStream commandOutput = channel.getInputStream(); channel.connect(); int readByte = commandOutput.read(); while (readByte != 0xffffffff) { outputBuffer.append((char)readByte); readByte = commandOutput.read(); } channel.disconnect(); session.disconnect(); } catch (IOException ioe) { listener.onTaskResult(setup.getId(), ReplyCode.REMOTE_ERROR, ioe.getMessage()); } catch (JSchException jse) { listener.onTaskResult(setup.getId(), ReplyCode.REMOTE_ERROR, jse.getMessage()); } listener.onTaskResult(setup.getId(), ReplyCode.SUCCESS, outputBuffer.toString()); } catch (Exception e) { this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, e.toString()); } }
Example 18
Source File: JavaConnect.java From ssh-shell-spring-boot with Apache License 2.0 | 4 votes |
public static void main(String[] args) { String host = "localhost"; String user = "user"; int port = 2222; String password = "password"; String command = "help"; try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setPassword(password); session.setConfig(config); session.connect(); System.out.println("Connected"); Channel channel = session.openChannel("shell"); channel.connect(); channel.getOutputStream().write((command + "\r").getBytes(StandardCharsets.UTF_8)); channel.getOutputStream().flush(); channel.setInputStream(null); InputStream in = channel.getInputStream(); 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)); } if (channel.isClosed()) { System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(3000); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); } }
Example 19
Source File: SSHCommandExecutor.java From journaldev with MIT License | 4 votes |
/** * @param args */ public static void main(String[] args) { String host="test.journaldev.com"; String user="my_user"; String password="my_pwd"; String command1="cd Apps;ls -ltr"; 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)); } 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(); } }
Example 20
Source File: RmtShellExecutor.java From LuckyFrameClient with GNU Affero General Public License v3.0 | 4 votes |
/** * ����JSch��ʵ��Զ������SHELL����ִ�� * * @param ip ����IP * @param user ������½�û��� * @param psw ������½���� * @param port ����ssh2��½�˿ڣ����ȡĬ��ֵ����-1 * @param command Shell���� cd /home/pospsettle/tomcat-7.0-7080/bin&&./restart.sh */ public static String sshShell(String ip, String user, String psw , int port, String command) { Session session = null; Channel channel = null; String result = "Status:true" + " ��������ִ�гɹ���"; try { JSch jsch = new JSch(); LogUtil.APP.info("���뵽����TOMCAT����..."); if (port <= 0) { //���ӷ�����������Ĭ�϶˿� LogUtil.APP.info("��������TOMCAT������IP��Ĭ�϶˿�..."); session = jsch.getSession(user, ip); } else { //����ָ���Ķ˿����ӷ����� LogUtil.APP.info("��������TOMCAT������IP���˿�..."); session = jsch.getSession(user, ip, port); LogUtil.APP.info("��������TOMCAT������IP���˿����!"); } //������������Ӳ��ϣ����׳��쳣 if (session == null) { LogUtil.APP.warn("����TOMCAT�����У����ӷ�����session is null"); throw new Exception("session is null"); } //���õ�½���������� session.setPassword(psw); //���õ�һ�ε�½��ʱ����ʾ����ѡֵ��(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); //���õ�½��ʱʱ�� session.connect(30000); //����sftpͨ��ͨ�� channel = session.openChannel("shell"); channel.connect(1000); //��ȡ������������� InputStream instream = channel.getInputStream(); OutputStream outstream = channel.getOutputStream(); //������Ҫִ�е�SHELL�����Ҫ��\n��β����ʾ�س� LogUtil.APP.info("��������TOMCAT��������������!"); String shellCommand = command + " \n"; outstream.write(shellCommand.getBytes()); outstream.flush(); Thread.sleep(10000); //��ȡ����ִ�еĽ�� if (instream.available() > 0) { byte[] data = new byte[instream.available()]; int nLen = instream.read(data); if (nLen < 0) { LogUtil.APP.warn("����TOMCAT�����У���ȡ����ִ�н�������쳣��"); } //ת������������ӡ���� String temp = new String(data, 0, nLen, "iso8859-1"); LogUtil.APP.info("��ʼ��ӡ����TOMCAT����ִ�н��...{}", temp); } outstream.close(); instream.close(); } catch (Exception e) { result = "����TOMCAT�����У������쳣��"; LogUtil.APP.error("����TOMCAT�����У������쳣��", e); return result; } finally { if (null != session) { session.disconnect(); } if (null != channel) { channel.disconnect(); } } return result; }