public JSch build() throws JSchException { LOGGER.debug("Initializing JSch Logger"); JSch.setLogger(new JschLogger()); final JSch jsch = new JSch(); try { if (null != knownHostsFileName && new File(knownHostsFileName).exists()) { jsch.setKnownHosts(knownHostsFileName); } if (null != privateKeyFileName && new File(privateKeyFileName).exists()) { jsch.addIdentity(privateKeyFileName); } } catch (JSchException e) { LOGGER.error("Could not access known hosts or private key file.", e); if (!(e.getCause() instanceof FileNotFoundException)) { throw new JSchException(); } } return jsch; }
/** * Creates SSHShell. * * @param host the host name * @param port the ssh port * @param userName the ssh user name * @param sshPrivateKey the ssh password * @return the shell * @throws JSchException * @throws IOException */ private SSHShell(String host, int port, String userName, byte[] sshPrivateKey) throws JSchException, IOException { Closure expectClosure = getExpectClosure(); for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) { try { Match match = new RegExpMatch(linuxPromptPattern, expectClosure); linuxPromptMatches.add(match); } catch (MalformedPatternException malformedEx) { throw new RuntimeException(malformedEx); } } JSch jsch = new JSch(); jsch.setKnownHosts(System.getProperty("user.home") + "/.ssh/known_hosts"); jsch.addIdentity(host, sshPrivateKey, (byte[]) null, (byte[]) null); this.session = jsch.getSession(userName, host, port); this.session.setConfig("StrictHostKeyChecking", "no"); this.session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); session.connect(60000); this.channel = (ChannelShell) session.openChannel("shell"); this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()); channel.connect(); }
protected void work() throws IOException, CancellationException, JSchException, SftpException, ExecutionException, InterruptedException { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} started", getTraceName()); } ChannelSftp cftp = getChannel(); RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("download", srcFileName); // NOI18N try { cftp.get(srcFileName, dstFileName); } catch (SftpException e) { if (MiscUtils.mightBrokeSftpChannel(e)) { cftp.quit(); } throw decorateSftpException(e, srcFileName); } finally { releaseChannel(cftp); RemoteStatistics.stopChannelActivity(activityID, new File(dstFileName).length()); } }
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; }
/** * Creates SSHShell. * * @param host the host name * @param port the ssh port * @param userName the ssh user name * @param password the ssh password * @return the shell * @throws JSchException * @throws IOException */ private SSHShell(String host, int port, String userName, String password) throws JSchException, IOException { Closure expectClosure = getExpectClosure(); for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) { try { Match match = new RegExpMatch(linuxPromptPattern, expectClosure); linuxPromptMatches.add(match); } catch (MalformedPatternException malformedEx) { throw new RuntimeException(malformedEx); } } JSch jsch = new JSch(); this.session = jsch.getSession(userName, host, port); session.setPassword(password); Hashtable<String, String> config = new Hashtable<>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(60000); this.channel = (ChannelShell) session.openChannel("shell"); this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()); channel.connect(); }
@Override public SessionFactory get() { if (sessionFactory == null) { try { synchronized (this) { System.setProperty(DefaultSessionFactory.PROPERTY_JSCH_KNOWN_HOSTS_FILE, knownHosts); sessionFactory = new DefaultSessionFactory(); sessionFactory.setPort(sshPort); LOG.debug("Session factory created for {}@{}:{}", sessionFactory.getUsername(), sessionFactory.getHostname(), sessionFactory.getPort()); } sessionFactory.setIdentitiesFromPrivateKeys(identityKeys); } catch (JSchException | RuntimeException e) { throw new WaggleDanceException( "Unable to create factory with knownHosts=" + knownHosts + " and identityKeys=" + identityKeys, e); } } return sessionFactory; }
private boolean setupJSchIdentityRepository (JSch jsch, String identityFile, boolean preferAgent) throws JSchException { boolean agentUsed = false; if (preferAgent) { Connector con = ConnectorFactory.getInstance().createConnector(ConnectorFactory.ConnectorKind.ANY); if (con != null) { IdentityRepository irepo = new IdentityRepositoryImpl(con); if (irepo.getStatus() == IdentityRepository.RUNNING) { jsch.setIdentityRepository(irepo); agentUsed = true; } } } if (!agentUsed) { jsch.setIdentityRepository(null); // remove all identity files jsch.removeAllIdentity(); // and add the one specified by CredentialsProvider jsch.addIdentity(identityFile); } return agentUsed; }
@Override public ExecResults call() throws Exception { int rc; List<String> error = new LinkedList<>(); try { channel.connect(); channel.get(remoteLoc, file.getAbsolutePath()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Completed downloading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]"); } } catch (JSchException | SftpException e) { String msg = "Encountered problems when downloading [" + remoteLoc + "]. Root cause : " + e.getMessage(); error.add(msg); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Failed downloading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]", e); } } finally { rc = channel.getExitStatus(); channel.disconnect(); } return new ExecResults(new LinkedList<>(), error, rc); }
public static boolean isValidSSHKeyFile(String filename) { JSch test = new JSch(); try { test.addIdentity(filename); } catch (JSchException ex) { return false; } return true; }
@Override public ExecResults call() throws Exception { int rc; List<String> error = new LinkedList<>(); try (InputStream stream = new FileInputStream(file)) { channel.connect(); channel.put(stream, remoteLoc + "/" + file.getName()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Completed uploading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]"); } } catch (JSchException | SftpException e) { String msg = "Encountered problems when uploading [" + remoteLoc + "]. Root cause : " + e.getMessage(); error.add(msg); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Failed uploading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]", e); } } finally { rc = channel.getExitStatus(); channel.disconnect(); } return new ExecResults(new LinkedList<>(), error, rc); }
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; }
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); }; }
/** * Orchestrates ZIP upload and sends commands through SSH. * Depending on the artifact type the method will use create or start scripts. * * @param type The artifact type which determines the nature of the method */ private void helpCreateStart(ArtifactType type) throws JSchException { for(ArrayList<Node> currentBranch : allBranches){ MachineNode mNode = (MachineNode) currentBranch.get(0); makeSSHConnection(mNode); if (type == ArtifactType.CREATE){ ssh.uploadAndUnzipZip(zip); } for(int i=1; i<currentBranch.size();i++){ ServiceNode currentNode = (ServiceNode) currentBranch.get(i); ArtifactPath createPath = currentNode.getImplementationArtifact(ArtifactType.CREATE); ArtifactPath startPath = currentNode.getImplementationArtifact(ArtifactType.START); if(type==ArtifactType.CREATE){ executeScript(createPath); executeScript(startPath); } else { executeScript(startPath); } } ssh.close(); } }
@Override public CommandOutput controlApplication(ControlApplicationRequest applicationRequest, Application app, String... params) throws CommandFailureException { RemoteSystemConnection remoteConnection = new RemoteSystemConnection( sshConfig.getUserName(), sshConfig.getEncryptedPassword(), params[0], sshConfig.getPort()); ExecCommand execCommand = new ExecCommand("secure-copy", params[1], params[2]); RemoteExecCommand remoteCommand = new RemoteExecCommand(remoteConnection, execCommand); try { final JschScpCommandProcessorImpl jschScpCommandProcessor = new JschScpCommandProcessorImpl(jschBuilder.build(), remoteCommand); jschScpCommandProcessor.processCommand(); // if processCommand fails it throws an exception before completing return new CommandOutput(new ExecReturnCode(0), "", ""); } catch (JSchException e) { throw new CommandFailureException(execCommand, new Throwable(e)); } }
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(); } }
@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(); }
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { case "close": try { return invoke(method, args); } finally { tunnelConnectionManager.close(); } case "reconnect": try { tunnelConnectionManager.ensureOpen(); } catch (JSchException e) { throw new RuntimeException("Unable to reopen tunnel connections", e); } default: return invoke(method, args); } }
@Override public Boolean invoke(File file, VirtualChannel channel) { try { FolderZipUtils.zipFolder(uploadFolder, uploadFile); if(uploadType.equals("ftp")){ FileTransferUtils.ftpOpenConnUpload(ipAddr, username, password, destDir, uploadFile); }else if(uploadType.equals("sftp")){ FileTransferUtils.sftpJSchUpload(ipAddr, username, password, destDir, uploadFile); }else if(uploadType.equals("scp")){ FileTransferUtils.scpJschUpload(ipAddr, username, password, destDir, uploadFile); } } catch (JSchException | SftpException | IOException | InterruptedException e){ status = false; e.printStackTrace(listener.getLogger()); } return status; }
protected void deprovisionAgentInLinuxVM(String host, int port, String userName, String password) { if (isPlaybackMode()) { return; } SshShell shell = null; try { System.out.println("Trying to de-provision"); shell = SshShell.open(host, port, userName, password); List<String> deprovisionCommand = new ArrayList<>(); deprovisionCommand.add("sudo waagent -deprovision+user --force"); String output = shell.runCommands(deprovisionCommand); System.out.println(output); } catch (JSchException jSchException) { Assert.assertNull(jSchException.getMessage(), jSchException); } catch (IOException ioException) { Assert.assertNull(ioException.getMessage(), ioException); } catch (Exception exception) { Assert.assertNull(exception.getMessage(), exception); } finally { if (shell != null) { shell.close(); } } }
/** * De-provision an Azure linux virtual machine. * * @param host the public host name * @param port the ssh port * @param userName the ssh user name * @param password the ssh user password */ protected static void deprovisionAgentInLinuxVM(String host, int port, String userName, String password) { SSHShell shell = null; try { System.out.println("Trying to de-provision: " + host); shell = SSHShell.open(host, port, userName, password); List<String> deprovisionCommand = new ArrayList<>(); deprovisionCommand.add("sudo waagent -deprovision+user --force"); String output = shell.runCommands(deprovisionCommand); System.out.println(output); } catch (JSchException jSchException) { System.out.println(jSchException.getMessage()); } catch (IOException ioException) { System.out.println(ioException.getMessage()); } catch (Exception exception) { System.out.println(exception.getMessage()); } finally { if (shell != null) { shell.close(); } } }
/** * * 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 protected Session createSession (Host hc, String user, String host, int port, FS fs) throws JSchException { Session session = super.createSession(hc, user, host, port, fs); try { List<Proxy> proxies = ProxySelector.getDefault().select(new URI("socket", null, host, port == -1 ? 22 : port, null, null, null)); if (proxies.size() > 0) { Proxy p = proxies.iterator().next(); if (p.type() == Proxy.Type.DIRECT) { session.setProxy(null); } else { SocketAddress addr = p.address(); if (addr instanceof InetSocketAddress) { InetSocketAddress inetAddr = (InetSocketAddress) addr; String proxyHost = inetAddr.getHostName(); int proxyPort = inetAddr.getPort(); session.setProxy(createProxy(proxyHost, proxyPort)); } } } } catch (URISyntaxException ex) { Logger.getLogger(JGitSshSessionFactory.class.getName()).log(Level.INFO, "Invalid URI: " + host + ":" + port, ex); } return session; }
private boolean setupJSch (FS fs, String host, CredentialItem.StringType identityFile, URIish uri, boolean preferAgent) throws TransportException { boolean agentUsed; if (sshConfig == null) { sshConfig = OpenSshConfig.get(fs); } final OpenSshConfig.Host hc = sshConfig.lookup(host); try { JSch jsch = getJSch(hc, fs); agentUsed = setupJSchIdentityRepository(jsch, identityFile.getValue(), preferAgent); } catch (JSchException ex) { throw new TransportException(uri, ex.getMessage(), ex); } return agentUsed; }
/** * 连接到服务器 */ private static Session connect(String host,String user,String pass) throws JSchException{ JSch sch = new JSch(); Session session = sch.getSession(user, host, 22); session.setPassword(pass); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setTimeout(60000); session.connect(); return session; }
private void reconnect(ExecutionEnvironment env) throws IOException, InterruptedException { synchronized (channelsSupportLock) { if (channelsSupport.containsKey(env)) { try { channelsSupport.get(env).reconnect(env); if (connectionWatcher != null) { connectionWatcher.connected(env); } } catch (JSchException ex) { throw new IOException(ex); } } } }
@Override public Channel openAndAcquireChannel(ExecutionEnvironment env, String type, boolean waitIfNoAvailable) throws InterruptedException, JSchException, IOException { synchronized (channelsSupportLock) { if (channelsSupport.containsKey(env)) { JSchChannelsSupport cs = channelsSupport.get(env); return cs.acquireChannel(type, waitIfNoAvailable); } } return null; }
@Override public void closeAndReleaseChannel(final ExecutionEnvironment env, final Channel channel) throws JSchException { JSchChannelsSupport cs = null; synchronized (channelsSupportLock) { if (channelsSupport.containsKey(env)) { cs = channelsSupport.get(env); } } if (cs != null && channel != null) { cs.releaseChannel(channel); } }
@Override public String getServerVersion() throws JSchException { synchronized (channelsSupportLock) { if (channelsSupport.containsKey(env)) { JSchChannelsSupport cs = channelsSupport.get(env); return cs.getServerVersion(); } } return null; }
@Override public void setPortForwardingR(String bind_address, int rport, String host, int lport) throws JSchException { synchronized (channelsSupportLock) { if (channelsSupport.containsKey(env)) { JSchChannelsSupport cs = channelsSupport.get(env); cs.setPortForwardingR(bind_address, rport, host, lport); } } }
@Override public int setPortForwardingL(int lport, String host, int rport) throws JSchException { synchronized (channelsSupportLock) { if (channelsSupport.containsKey(env)) { JSchChannelsSupport cs = channelsSupport.get(env); return cs.setPortForwardingL(lport, host, rport); } } return -1; }
@Override public void delPortForwardingR(int rport) throws JSchException { synchronized (channelsSupportLock) { if (channelsSupport.containsKey(env)) { JSchChannelsSupport cs = channelsSupport.get(env); cs.delPortForwardingR(rport); } } }