Java Code Examples for com.jcraft.jsch.JSch#setLogger()

The following examples show how to use com.jcraft.jsch.JSch#setLogger() . 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: SftpClient.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void disconnect(boolean force) throws RemoteException {
    if (sftpSession == null) {
        // nothing to do
        LOGGER.log(Level.FINE, "Remote client not created yet => nothing to do");
        return;
    }
    if (!force
            && sftpSession.getServerAliveInterval() > 0) {
        LOGGER.log(Level.FINE, "Keep-alive running and disconnecting not forced -> do nothing");
        return;
    }
    LOGGER.log(Level.FINE, "Remote client trying to disconnect");
    if (sftpSession.isConnected()) {
        LOGGER.log(Level.FINE, "Remote client connected -> disconnecting");
        JSch.setLogger(DEV_NULL_LOGGER);
        sftpSession.disconnect();
        LOGGER.log(Level.FINE, "Remote client disconnected");
    }
    sftpClient = null;
    sftpSession = null;

    sftpLogger.info("QUIT"); // NOI18N
    sftpLogger.info(NbBundle.getMessage(SftpClient.class, "LOG_Goodbye"));
}
 
Example 2
Source File: JschBuilder.java    From jwala with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
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 4
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;
}
 
Example 5
Source File: SshFenceByTcpPort.java    From big-c 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;
}
 
Example 6
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private SshSessionFactory getSshSessionFactory() {
  JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
    @Override
    protected void configure(OpenSshConfig.Host hc, Session session) {
      if (!GitMonitoringService.this.strictHostKeyCheckingEnabled) {
        session.setConfig("StrictHostKeyChecking", "no");
      }
    }

    @Override
    protected JSch createDefaultJSch(FS fs) throws JSchException {
      if (GitMonitoringService.this.isJschLoggerEnabled) {
        JSch.setLogger(new JschLogger());
      }
      JSch defaultJSch = super.createDefaultJSch(fs);
      defaultJSch.getIdentityRepository().removeAll();
      if (GitMonitoringService.this.privateKeyPath != null) {
        defaultJSch.addIdentity(GitMonitoringService.this.privateKeyPath, GitMonitoringService.this.passphrase);
      } else {
        defaultJSch.addIdentity("gaas-git", GitMonitoringService.this.privateKey, null,
            GitMonitoringService.this.passphrase.getBytes(Charset.forName("UTF-8")));
      }
      if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHosts)) {
        defaultJSch.setKnownHosts(new ByteArrayInputStream(GitMonitoringService.this.knownHosts.getBytes(Charset.forName("UTF-8"))));
      } else if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHostsFile)) {
        defaultJSch.setKnownHosts(GitMonitoringService.this.knownHostsFile);
      }
      return defaultJSch;
    }
  };
  return sessionFactory;
}
 
Example 7
Source File: JSchLogger.java    From termd with Apache License 2.0 4 votes vote down vote up
public static void init() {
    JSch.setLogger(new JSchLogger());
}
 
Example 8
Source File: SSHShellUtil.java    From mcg-helper with Apache License 2.0 4 votes vote down vote up
public static String execute(String ip, int port, String userName, String password, String secretKey, String shell) throws JSchException, IOException {
		String response = null;
		JSch.setLogger(new ShellLogger());
		JSch jsch = new JSch();
		Session session = jsch.getSession(userName, ip, port);
		UserInfo ui = null;
		if(StringUtils.isEmpty(secretKey)) {
			ui = new SSHUserInfo(password);
		} else {
			ui = new SSHGoogleAuthUserInfo(secretKey, password);
		}
		session.setUserInfo(ui);
		session.connect(6000);

		Channel channel = session.openChannel("shell");
		PipedInputStream pipedInputStream = new PipedInputStream();
		PipedOutputStream pipedOutputStream = new PipedOutputStream();
		pipedOutputStream.connect(pipedInputStream);
		
		Thread thread = new Thread(new MonitorShellUser(channel, shell, pipedOutputStream));
		thread.start();
		
		channel.setInputStream(pipedInputStream);
		
		PipedOutputStream shellPipedOutputStream = new PipedOutputStream();
		PipedInputStream receiveStream = new PipedInputStream(); 
		shellPipedOutputStream.connect(receiveStream);
		
		channel.setOutputStream(shellPipedOutputStream);
		((ChannelShell)channel).setPtyType("vt100", 160, 24, 1000, 480);   // dumb
		//((ChannelShell)channel).setTerminalMode("binary".getBytes(Constants.CHARSET));
	//	((ChannelShell)channel).setEnv("LANG", "zh_CN.UTF-8");
		try {
			channel.connect();
			response = IOUtils.toString(receiveStream, "UTF-8");
		}finally {
//			if(channel.isClosed()) {
				pipedOutputStream.close();
				pipedInputStream.close();
				shellPipedOutputStream.close();
				receiveStream.close();
				channel.disconnect();
				session.disconnect();
			}
//		}
			
		return response;
	}
 
Example 9
Source File: JSchHelper.java    From ssh-proxy with Apache License 2.0 4 votes vote down vote up
protected static void registerLogger() {
	JSch.setLogger(new JSchSlf4JLogger());
}
 
Example 10
Source File: JSchLogger.java    From termd with Apache License 2.0 4 votes vote down vote up
public static void init() {
    JSch.setLogger(new JSchLogger());
}
 
Example 11
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
  }
}