com.jcraft.jsch.JSchException Java Examples

The following examples show how to use com.jcraft.jsch.JSchException. 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: JSchExecutor.java    From vividus with Apache License 2.0 11 votes vote down vote up
private JSch createJSchInstance(ServerConfiguration server) throws AgentProxyException, JSchException
{
    JSch jSch = new JSch();
    if (server.isAgentForwarding())
    {
        Connector connector = ConnectorFactory.getDefault().createConnector();
        jSch.setIdentityRepository(new RemoteIdentityRepository(connector));
    }
    else if (server.getPrivateKey() != null && server.getPublicKey() != null)
    {
        String passphrase = server.getPassphrase();
        jSch.addIdentity("default", getBytes(server.getPrivateKey()), getBytes(server.getPublicKey()),
                passphrase != null ? getBytes(passphrase) : null);
    }
    return jSch;
}
 
Example #2
Source File: XpraActivity.java    From xpra-client with GNU General Public License v3.0 6 votes vote down vote up
private void setupSSHConnector(SshXpraConnector connector, Connection c) {
	try {
		final File knownHosts = getFileStreamPath("known_hosts");
		knownHosts.createNewFile();
		connector.getJsch().setKnownHosts(knownHosts.getAbsolutePath());
		if(c.sshPrivateKeyFile != null) {
			connector.getJsch().addIdentity(c.sshPrivateKeyFile);
		}
		if(c.displayId >= 0) {
			connector.setDisplay(c.displayId);
		}
	} catch (JSchException | IOException e) {
		// TODO implement some fix if necessary 
		e.printStackTrace();
	}		
}
 
Example #3
Source File: SshConnectionImpl.java    From gerrit-events with MIT License 6 votes vote down vote up
/**
 * Execute an ssh command on the server, without closing the session
 * so that a Reader can be returned with streaming data from the server.
 *
 * @param command the command to execute.
 * @return a Reader with streaming data from the server.
 * @throws IOException  if it is so.
 * @throws SshException if there are any ssh problems.
 */
@Override
public synchronized Reader executeCommandReader(String command) throws SshException, IOException {
    if (!isConnected()) {
        throw new IllegalStateException("Not connected!");
    }
    try {
        Channel channel = connectSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        InputStreamReader reader = new InputStreamReader(channel.getInputStream(), "utf-8");
        channel.connect();
        return reader;
    } catch (JSchException ex) {
        throw new SshException(ex);
    }
}
 
Example #4
Source File: SSHExecProcessAdapter.java    From teamcity-deployer-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public BuildFinishedStatus runProcess() {
  JSch.setLogger(new JSchBuildLogger(myLogger));
  Session session = null;
  try {
    session = myProvider.getSession();
    return executeCommand(session, myPty, myCommands);
  } catch (JSchException e) {
    logBuildProblem(myLogger, e.getMessage());
    LOG.warnAndDebugDetails("Error executing SSH command", e);
    return BuildFinishedStatus.FINISHED_FAILED;
  } finally {
    if (session != null) {
      session.disconnect();
    }
  }
}
 
Example #5
Source File: CustomJschConfigSessionFactory.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {

    JSch def = super.createDefaultJSch(fs);
    String keyName = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_NAME);
    String keyPath = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_PATH);

    if (keyName == null || keyName.isEmpty())
        keyName = GitDeploymentSynchronizerConstants.SSH_KEY;

    if (keyPath == null || keyPath.isEmpty())
        keyPath = System.getProperty("user.home") + "/" + GitDeploymentSynchronizerConstants.SSH_KEY_DIRECTORY;

    if (keyPath.endsWith("/"))
        def.addIdentity(keyPath + keyName);
    else
        def.addIdentity(keyPath + "/" + keyName);

    return def;
}
 
Example #6
Source File: SshExecutor.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
protected SshOutput executeCommand(ServerConfiguration serverConfig, Commands commands, ChannelExec channel)
        throws JSchException, IOException
{
    channel.setAgentForwarding(serverConfig.isAgentForwarding());
    SshOutput executionOutput = new SshOutput();
    try (ByteArrayOutputStream errorStream = new ByteArrayOutputStream())
    {
        channel.setCommand(commands.getJoinedCommands());
        channel.setErrStream(errorStream);
        channel.connect();
        executionOutput.setOutputStream(readChannelInputStream(channel));
        executionOutput.setErrorStream(new String(errorStream.toByteArray(), StandardCharsets.UTF_8));
        executionOutput.setExitStatus(channel.getExitStatus());
    }
    return executionOutput;
}
 
Example #7
Source File: ForecastAction.java    From fastdfs-zyc with GNU General Public License v2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping("/getDilatation")
public List<Line> getDilatation(String ip) throws IOException, MyException,JSchException {
    List<Line> lineList=new ArrayList<Line>();
    Line lines =new Line(ip);
    Forecast  forecast=getForecastObject(ip);
    if(forecast.getIpAddr()!=null){
        long average= forecast.getAverage();
        Calendar timeForForecast = Calendar.getInstance();
        timeForForecast.setTime(forecast.getTimeForForecast());
        lines.getData().add(new Long[] {timeForForecast.getTimeInMillis(),forecast.getWarning()/1024});
        for(int i=0;i<12;i++){
            long freeMB=(forecast.getWarning()+average*(i+1)*24*30)/1024;
            timeForForecast.add(Calendar.MONTH, 1);    // 加一个月
           // timeForForecast.set(Calendar.DATE, 1);     // 设置当前月第一天
            lines.getData().add(new Long[] {timeForForecast.getTimeInMillis(), freeMB });

        }
    }
    lineList.add(lines);
    return lineList;
}
 
Example #8
Source File: SshShell.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #9
Source File: SshdShellAutoConfigurationWithPublicKeyAndBannerImageTest.java    From sshd-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@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");
    try (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();
        verifyResponseContains(pis, "test run bob");
    }
    channel.disconnect();
    session.disconnect();
}
 
Example #10
Source File: LazyKnownHosts.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
LazyKnownHosts(JSch jsch, String knownHosts) throws JSchException {
	if (knownHosts != null) {
		try {
			final InputStream in = new ByteArrayInputStream(knownHosts.getBytes("UTF8"));
			try {
				jsch.setKnownHosts(in);
			} finally {
				in.close();
			}
		} catch (IOException e) {
			// no known hosts
		}
	}
	this.repo = jsch.getHostKeyRepository();

}
 
Example #11
Source File: JSchUtils.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * TODO: メソッドコメントを記述
 *
 * @param username
 * @param privateKey
 * @param passphrase
 * @param host
 * @param port
 * @return
 */
public static Session createSessionByPrivateKey(String username, String privateKey, String passphrase, String host,
        int port) {
    Charset charset = Charset.forName("UTF-8");
    byte[] privateKeyBytes = privateKey.getBytes(charset);
    byte[] passphraseBytes = null;
    if (passphrase != null) {
        passphraseBytes = passphrase.getBytes(charset);
    }

    try {
        JSch jsch = new JSch();
        jsch.addIdentity("name", privateKeyBytes, null, passphraseBytes);
        Session session = jsch.getSession(username, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        return session;
    } catch (JSchException e) {
        throw new AutoException("ECOMMON-000302", username, host, port);
    }
}
 
Example #12
Source File: StructureAction.java    From fastdfs-zyc with GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping("/serverInfo")
public ModelAndView serverInfo(String ip) throws IOException, MyException,JSchException {
    ModelAndView mv = new ModelAndView("structure/serverInfo.jsp");
    if(ip.indexOf(":")>=0){
     String[] data=ip.split(":");
        ip=data[0];
    }
    List<Group> groups=monitorService.listGroupInfo();
    for(Group group:groups){
      for(Storage storage:group.getStorageList()){
          if(storage.getIpAddr().equals(ip)){
              mv.addObject("serverInfo", storage);
          }
      }
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Calendar calendar = Calendar.getInstance();
    mv.addObject("end", sdf.format(calendar.getTime()));
    calendar.add(Calendar.HOUR, -1);
    mv.addObject("start", sdf.format(calendar.getTime()));
    return mv;
}
 
Example #13
Source File: SFTPUtil.java    From bestconf with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Create new channel every time a command needs to be executed. This is required to support execution of multiple
 * commands in parallel. All created channels are cleaned up when the session is closed.
 *
 *
 * @return a new {@link ChannelSftp}
 * @throws SftpException
 */
public ChannelSftp getSftpChannel() throws SftpException {

  try {
    ChannelSftp channelSftp = (ChannelSftp) this.session.openChannel("sftp");

    // In millsec
    int connTimeout = state.getPropAsInt(SFTP_CONNECTION_TIMEOUT_KEY, DEFAULT_SFTP_CONNECTION_TIMEOUT);
    channelSftp.connect(connTimeout);
    return channelSftp;
  } catch (JSchException e) {
    throw new SftpException(0, "Cannot open a channel to SFTP server", e);
  }
}
 
Example #15
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void knownHosts(final JSch sch, FS fs) throws JSchException {
    final File home = fs.userHome();
    if (home == null)
        return;
    final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
    try {
        final FileInputStream in = new FileInputStream(known_hosts);
        try {
            sch.setKnownHosts(in);
        } finally {
            in.close();
        }
    } catch (FileNotFoundException none) {
        // Oh well. They don't have a known hosts in home.
    } catch (IOException err) {
        // Oh well. They don't have a known hosts in home.
    }
}
 
Example #16
Source File: JobConfigUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Session getSession(String host, String username, String password, String privateKeyPath)
		throws JSchException {
	JSch jsch = new JSch();
	Session session = null;
	if (StringUtils.isNotBlank(privateKeyPath)) {
		jsch.addIdentity(privateKeyPath);
	}
	session = jsch.getSession(username, host, 22);

	Properties config = new Properties();
	config.put("StrictHostKeyChecking", "no");
	if (StringUtils.isNotBlank(password)) {
		session.setPassword(password);
		config.put("PreferredAuthentications", "password");
	}
	session.setConfig(config);
	session.connect();
	return session;
}
 
Example #17
Source File: CommandAsObjectResponserMethods.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * For creating a JSCH session.
 * 
 * @param host
 *            the host
 * @return a JSCH session
 * @throws JSchException
 *             the jsch exception
 */
private 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);
	if(switchedIdentity.getPasswd()!=null){
		try{
			session.setPassword(StringUtil.getPlain(switchedIdentity.getPasswd()));
		}catch(Exception e){
			LOGGER.error("Failed to Decrypt the password", e);
		}
	}
	conf.put(STRICT_HOST_KEY_CHECKING, "no");
	session.setConfig(conf);
    session.connect();
	LOGGER.debug("Session Established, for user ["+switchedIdentity.getUser()+"]"+":["+session.isConnected()+"]");
	return session;
}
 
Example #18
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 本地檔案放到遠端SFTP上
 * 	
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param localFile
 * @param remoteFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void put(String user, String password, String addr, int port,
		List<String> localFile, List<String> remoteFile) throws JSchException, SftpException, Exception {
	
	Session session = getSession(user, password, addr, port);	
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	try {
		for (int i=0; i<localFile.size(); i++) {
			String rf=remoteFile.get(i);
			String lf=localFile.get(i);
			logger.info("put local file: " + lf + " write to " + addr + " :" + rf );
			sftpChannel.put(lf, rf);
			logger.info("success write to " + addr + " :" + rf);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}		
}
 
Example #19
Source File: VFSUtils.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
public static boolean checkForWrongCredentials(Throwable exception) {
  if (exception.getCause() != null) {
    return checkForWrongCredentials(exception.getCause());
  } else {
    String message = exception.getMessage();
    return
      exception instanceof SmbAuthException && message.contains("The specified network password is not correct") ||
        exception instanceof JSchException && message.contains("Auth fail");
  }


}
 
Example #20
Source File: ConnectionManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #21
Source File: DeployUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/***
 * This method does other addition task like fetching hadoop core jars and
 * other required jar from libs of namenode. and adds essential agent
 * specific jars to distribution of agent.
 * 
 * @param javaHomeStr,
 *            absolute path of java home
 * @param session,
 *            jschSession instance
 * @param jumbuneHomeStr
 * @param deployer
 * @param distributionType
 * @param currentDir
 * @throws JSchException
 * @throws IOException
 * @throws InterruptedException
 */
private void updateJumbuneAndHadoopDistribution(String javaHomeStr, Session session,
		String jumbuneHomeStr, String hadoopDistributionType, String distributionType)
		throws JSchException, IOException, InterruptedException {
	String currentDir = System.getProperty(USER_DIR) + "/";
	String currentLibDir = currentDir + "/lib/";
	new File(currentLibDir).mkdirs();
	String hadoopHome = getHadoopLocation(session, hadoopDistributionType);
	if (hadoopHome.endsWith(File.separator)) {
		hadoopHome = hadoopHome.substring(0, hadoopHome.length() - 1);
	}
	try {
		SessionEstablisher.fetchHadoopJarsFromNamenode(session, username, namenodeIP,
				hadoopHome, currentDir + WEB_FOLDER_STRUCTURE, hadoopDistributionType,
				distributionType);
	} catch (java.lang.ArrayIndexOutOfBoundsException e) {
		CONSOLE_LOGGER.error("Invalid: Hadoop distribution [" + hadoopDistributionType
				+ "] passed during deploy doesn't match with the deployed distribution of Hadoop");
		exitVM(1);
	}

	String updateAgentJar = append(javaHomeStr, "/bin/", UPDATE_JAR, jumbuneHomeStr,
			UPDATE_AGENT_JAR);
	String copyHadoopJarsToLib = append("cp -r ", currentDir, WEB_FOLDER_STRUCTURE, " ",
			FoundPaths.get(JUMBUNE_HOME), Path.SEPARATOR, " ");
	executeCommand(copyHadoopJarsToLib);
	executeCommand(updateAgentJar);

	DEBUG_FILE_LOGGER.debug("Updated agent jar and lib folder");
}
 
Example #22
Source File: Authentication.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isValidKnownHostsFile(String knownHostsFile) {
    JSch test = new JSch();

    try {
        test.setKnownHosts(knownHostsFile);
    } catch (JSchException ex) {
        return false;
    }

    return true;
}
 
Example #23
Source File: ConnectionManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void delPortForwardingR(int rport) throws JSchException {
    synchronized (channelsSupportLock) {
        if (channelsSupport.containsKey(env)) {
            JSchChannelsSupport cs = channelsSupport.get(env);
            cs.delPortForwardingR(rport);
        }
    }
}
 
Example #24
Source File: SessionEstablisher.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * method for copying hadoop jars from namenode
 * @param session
 * @param username
 * @param namenodeIP
 * @param hadoopHome
 * @param destinationAbsolutePath
 * @param listOfFiles
 * @throws JSchException
 * @throws IOException
 */
public static void fetchHadoopJarsFromNamenode(Session session, String username, String namenodeIP, String hadoopHome, String destinationAbsolutePath, String hadoopDistributionType, String distributionType, String... files)
		throws JSchException, IOException {
	new File(destinationAbsolutePath).mkdirs();
	Deployer deployer = DeployerFactory.getDeployer(distributionType,hadoopDistributionType);
	String versionCommand = null ;
	String versionNumber = null ;
	if(!hadoopDistributionType.equalsIgnoreCase(ExtendedConstants.MAPR) || !hadoopDistributionType.equalsIgnoreCase(ExtendedConstants.EMRMAPR)){
	if (hadoopDistributionType.equalsIgnoreCase(ExtendedConstants.CLOUDERA)
			|| hadoopDistributionType.equalsIgnoreCase(ExtendedConstants.HORTONWORKS) || hadoopDistributionType.equalsIgnoreCase(ExtendedConstants.EMRAPACHE)) {
		versionCommand = File.separator + "usr" + File.separator + HADOOP_VERSION_YARN_COMMAND;
	}else if(distributionType.equalsIgnoreCase("Non-Yarn")){
		versionCommand = hadoopHome + File.separator + HADOOP_VERSION_NON_YARN_COMMAND;
	} else {
		versionCommand = hadoopHome + File.separator
				+ HADOOP_VERSION_YARN_COMMAND;
	}
	//begin mapr code changes
	} else{
		versionCommand = hadoopHome + File.separator + HADOOP_VERSION_YARN_COMMAND;
	}
	
	String versionResponse = executeCommand(session, versionCommand);
	versionNumber = getVersionNumber(versionResponse);
	//end mapr code changes
	String[] listOfFiles = deployer.getRelativePaths(versionNumber);
	for (String fileName : listOfFiles) {
		String command = SCP_COMMAND + hadoopHome + fileName;
		copyRemoteFile(session, command, destinationAbsolutePath);
	}
	CONSOLE_LOGGER.info("Syncing Jars from Hadoop to Jumbune.......[SUCCESS]");
}
 
Example #25
Source File: ConnectionManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #26
Source File: UnixSshFileSystemProvider.java    From jsch-nio with MIT License 5 votes vote down vote up
int write( UnixSshPath path, long startIndex, ByteBuffer bytes ) throws IOException {
    try {
        int bytesPosition = bytes.position();
        // TODO cache this buffer for reuse
        ByteBuffer temp = ByteBuffer.allocateDirect( bytes.limit() - bytesPosition );
        temp.put( bytes );
        bytes.position( bytesPosition );

        String command = path.getFileSystem().getCommand( "dd" )
                + " conv=notrunc bs=1 seek=" + startIndex 
                + " of=" + path.toAbsolutePath().quotedString();
        ChannelExecWrapper sshChannel = null;
        int written = 0;
        try {
            sshChannel = path.getFileSystem().getCommandRunner().open( command );
            try (OutputStream out = sshChannel.getOutputStream()) {
                WritableByteChannel outChannel = Channels.newChannel( out );
                temp.flip();
                written = outChannel.write( temp );
            }
            if ( written > 0 ) {
                bytes.position( bytesPosition + written );
            }
        }
        finally {
            int exitCode = sshChannel.close();
            if ( exitCode != 0 ) {
                throw new IOException( "dd failed " + exitCode );
            }
        }
        return written;
    }
    catch ( JSchException e ) {
        throw new IOException( e );
    }
}
 
Example #27
Source File: JGitConfigSessionFactory.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
    JSch jSch = super.getJSch(hc, fs);
    jSch.removeAllIdentity();
    if (!keyLocation.isEmpty())
        jSch.addIdentity(keyLocation, password);
    return jSch;
}
 
Example #28
Source File: SshUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Launch a command on the remote host and exit even if the command is not done (useful for launching daemons).
 * 
 * @param session the session to use.
 * @param command the command to launch.
 * @return the output of the command.
 * @throws JSchException
 * @throws IOException
 */
private static String launchACommandAndExit( Session session, String command ) throws JSchException, IOException {
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    StringBuilder sb = new StringBuilder();
    byte[] tmp = new byte[1024];
    while( true ) {
        while( in.available() > 0 ) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            sb.append(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            if (in.available() > 0)
                continue;
            break;
        }
        try {
            if (sb.length() > 0) {
                break;
            }
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    String remoteResponseStr = sb.toString().trim();
    return remoteResponseStr;
}
 
Example #29
Source File: SftpFileSystem.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a command and returns the (standard) output through a StringBuilder.
 *
 * @param command The command
 * @param output  The output
 * @return The exit code of the command
 * @throws JSchException       if a JSch error is detected.
 * @throws FileSystemException if a session cannot be created.
 * @throws IOException         if an I/O error is detected.
 */
private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException {
    final ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
    try {
        channel.setCommand(command);
        channel.setInputStream(null);
        try (final InputStreamReader stream = new InputStreamReader(channel.getInputStream())) {
            channel.setErrStream(System.err, true);
            channel.connect(connectTimeoutMillis);

            // Read the stream
            final char[] buffer = new char[EXEC_BUFFER_SIZE];
            int read;
            while ((read = stream.read(buffer, 0, buffer.length)) >= 0) {
                output.append(buffer, 0, read);
            }
        }

        // Wait until the command finishes (should not be long since we read the output stream)
        while (!channel.isClosed()) {
            try {
                Thread.sleep(SLEEP_MILLIS);
            } catch (final Exception ee) {
                // TODO: swallow exception, really?
            }
        }
    } finally {
        channel.disconnect();
    }
    return channel.getExitStatus();
}
 
Example #30
Source File: SshFenceByTcpPort.java    From hadoop with Apache License 2.0 5 votes vote down vote up
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;
}