@Test
 public void testCreateClientFailsIfPwdReturnsRelativePath() throws Exception {
   final String remoteRoot = "some/directory/in/my/home/dir";
   hostConfig = createWithOverrideUsernameAndPassword(mockJSch);
   getHostConfig().setRemoteRootDir(remoteRoot);
   final BapSshCommonConfiguration commonConfiguration =
       new BapSshCommonConfiguration("Ignore me", null, null, false);
   getHostConfig().setCommonConfig(commonConfiguration);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(TEST_PASSPHRASE);
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   expect(mockSftp.pwd()).andReturn("home/bap/" + remoteRoot);
   expect(mockSftp.isConnected()).andReturn(false);
   expect(mockSession.isConnected()).andReturn(false);
   assertCreateClientThrowsException("home/bap/" + remoteRoot);
 }
  @Override
  public void afterPropertiesSet() {
    jsch = new JSch();
    if (!isConnected) {
      if (null == session || !session.isConnected()) {
        try {
          session = jsch.getSession(sshUsername, host, port);
          session.setPassword(sshPassword);

          java.util.Properties config = new java.util.Properties();
          config.put("StrictHostKeyChecking", "no");
          session.setConfig(config);

          log.info("Открытие ssh соединения");
          session.connect();
          log.info("Tunnel status: " + session.isConnected());
          log.info("Устанавливаем туннель");
          session.setPortForwardingL(tunnelLocalPort, tunnelRemoteHost, tunnelRemotePort);
        } catch (Exception e) {
          log.error("Ошибка при построении соединения", e);
          System.exit(1);
        }
      }
      isConnected = true;
    }
  }
示例#3
0
  protected void connectSession() throws JSchException {
    if (session != null) {
      if (session.isConnected()) {
        session.disconnect();
      }
      session = null;
    }

    AutomationLogger.getInstance().info("Connectting...");

    if (StringUtil.notEmpty(user)) {
      session = jsch.getSession(user, host, 22);
      session.setPassword(password);
    } else if (auth != null) {
      session = auth.getSession(host);
    } else {
      throw new ItemNotFoundException("Authentication is missing!");
    }

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    AutomationLogger.getInstance().info("Connected");
  }
示例#4
0
  protected void initSession() throws JSchException {
    logger.info("initSession():{}", this);

    try {
      this.session = jsch.getSession(config.user, config.host, config.port);
      this.session.setUserInfo(new DummyRobot());

      addKnownHosts();
      addUserIDFiles();

      if (config.passwd != null) {
        session.setPassword(new String(config.passwd));
      }
      // Legacy options:
      // config.setProperty("StrictHostKeyChecking", "no");
      // if (sshOptions.compression == false) {
      // config.put("compression.s2c", "none");
      // config.put("compression.c2s", "none");
      // } else {
      // config.put("compression.s2c", "zlib,none");
      // config.put("compression.c2s", "zlib,none");
      // }
      this.session.setConfig(config.getProperties());
    } catch (JSchException e) {
      // chain into meaningfull exception:
      throw new JSchException("Couldn't connect to server:" + this, e);
    }
  }
 private void init() {
   otherHostInfo = getOtherHostInfo();
   JSch jSch = new JSch();
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   try {
     session = jSch.getSession(hostInfo.getUser(), hostInfo.getIp(), hostInfo.getPort());
     session.setConfig(config);
     session.setPassword(hostInfo.getPassword());
     session.connect(5000);
     System.out.println(hostInfo.getIp() + "已连接...");
     channel = session.openChannel("shell");
     channel.connect();
     expect =
         new ExpectBuilder()
             .withOutput(channel.getOutputStream())
             .withInputs(channel.getInputStream(), channel.getExtInputStream())
             .withEchoInput(System.out)
             .withEchoOutput(System.err)
             .withInputFilters(removeColors(), removeNonPrintable())
             .withExceptionOnFailure()
             .withTimeout(80000, TimeUnit.SECONDS)
             .withAutoFlushEcho(true)
             .withCombineInputs(true)
             .build();
     System.out.println(expect.getClass().getName());
   } catch (JSchException | IOException e) {
     e.printStackTrace();
     destroy();
     throw new RuntimeException("无法连接" + hostInfo.getIp() + ":" + hostInfo.getPort());
   }
 }
示例#6
0
  private static void sftpUpload() {
    JSch.setLogger(new JschLogger());
    Session session = null;
    try {
      JSch jsch = new JSch();
      session = jsch.getSession(USERNAME, HOST, PORT);
      session.setPassword(PASSWORD);
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.connect();

      Channel channel = session.openChannel(PROTOCOL_SFTP);
      channel.connect();

      BufferedInputStream in = new BufferedInputStream(new FileInputStream(SOURCE));
      ChannelSftp channelSftp = (ChannelSftp) channel;
      channelSftp.cd(TARGET);
      channelSftp.put(in, FILE_NAME);

    } catch (JSchException | SftpException | FileNotFoundException ex) {
      Logger.getLogger(JschDemo.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (session != null) {
        session.disconnect();
      }
    }
  }
 @Test
 public void testDontConnectSftpIfNoSourceFilesInAnyTransfers() throws Exception {
   final BapSshCommonConfiguration defaultKeyInfo =
       new BapSshCommonConfiguration(TEST_PASSPHRASE, null, null, false);
   hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo);
   final BapSshTransfer transfer1 =
       new BapSshTransfer(
           "", "", "", "", false, false, "ls -la", 10000, false, false, false, null);
   final BapSshTransfer transfer2 =
       new BapSshTransfer("", "", "", "", false, false, "pwd", 10000, false, false, false, null);
   final ArrayList<BapSshTransfer> transfers = new ArrayList<BapSshTransfer>();
   transfers.addAll(Arrays.asList(transfer1, transfer2));
   final BapSshPublisher publisher =
       new BapSshPublisher(
           getHostConfig().getName(), false, transfers, false, false, null, null, null);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(defaultKeyInfo.getPassphrase());
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   mockControl.replay();
   getHostConfig().createClient(buildInfo, publisher);
   mockControl.verify();
 }
 public void login(String username, String password) throws JSchException {
   session = jSch.getSession(username, ip, port);
   session.setPassword(password);
   //// FIXME: 03/04/2016 Security
   session.setConfig("StrictHostKeyChecking", "no");
   session.connect();
   channel = (ChannelSftp) session.openChannel("sftp");
   channel.connect();
 }
示例#9
0
 /**
  * 连接到指定的IP
  *
  * @throws JSchException
  */
 public void connect() throws JSchException {
   jsch = new JSch();
   session = jsch.getSession(user, host, 22);
   session.setPassword(passwd);
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
 }
  @Override
  protected Integer doInBackground(String... arg0) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Thread.currentThread().setName("SSHConnectionThread");
    try {

      JSch jsch = new JSch();
      session = jsch.getSession(arg0[1], arg0[0], 22);
      session.setPassword(arg0[2].getBytes());
      session.setConfig("StrictHostKeyChecking", "no");
      session.connect(timeout);
      System.out.println("connesso? " + session.isConnected());
      int assinged_port = session.setPortForwardingL(lhost, lport, rhost, rport);
      session.setPortForwardingL(lhost, 9001, rhost, 502);
      System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
      ConnectionManager.setSession(session);

    } catch (Exception e) {
      //			System.out.println(e.getLocalizedMessage());
      //			String errore = "";
      //			if(e instanceof JSchException) errore = "Errore SSH ";
      //			else if(e instanceof UnknownHostException) errore = "Ricontrolla il dominio o la
      // connessione internet, cè qualcosa di errato, attento agli spazi e maiscole";
      //			else if(e instanceof ConnectException) errore = "Ricontrolla i campi o la connessione cè
      // qualcosa che non va, attento agli spazi e maiscole";
      //			else errore = "Ricontrolla user, password e dominio, cè qualcosa di errato, attento agli
      // spazi e maiscole";
      //			if(isDialogActivated()){
      //				AlertMessageTask errorConnection = new AlertMessageTask();
      //				errorConnection.setActivity(getActivity());
      //				errorConnection.execute(errore);
      //			}
      if (fireEvent && !e.getLocalizedMessage().contains("PortForwardingL:")) {
        System.out.println("non è portforwarding ma " + e.getLocalizedMessage());
        if (MainActivity.handle == null) return null;
        Message msgObj = MainActivity.handle.obtainMessage();
        Bundle ba = new Bundle();
        ba.putInt("status", 0);
        msgObj.setData(ba);
        MainActivity.handle.sendMessage(msgObj);
        fireEvent = false;
      }
      return null;
    }
    if (fireEvent) {
      if (MainActivity.handle == null) return null;
      Message msgObj = MainActivity.handle.obtainMessage();
      Bundle ba = new Bundle();
      ba.putInt("status", 1);
      msgObj.setData(ba);
      MainActivity.handle.sendMessage(msgObj);
      fireEvent = false;
    }
    return null;
  };
示例#11
0
 @Override
 public void send(String path, String filename, Binary content) throws IOException {
   Session session = null;
   Channel channel = null;
   ChannelSftp channelSftp = null;
   logger.debug("preparing the host information for sftp.");
   InputStream data = null;
   try {
     JSch jsch = new JSch();
     session = jsch.getSession(this.username, this.server, this.remotePort);
     if (this.password != null) {
       session.setPassword(this.password);
     }
     java.util.Properties config = new java.util.Properties();
     config.put("StrictHostKeyChecking", "no");
     session.setConfig(config);
     session.connect();
     logger.debug("Host connected.");
     channel = session.openChannel("sftp");
     channel.connect();
     logger.debug("sftp channel opened and connected.");
     channelSftp = (ChannelSftp) channel;
     if (path != null) {
       channelSftp.cd(path);
     }
     File f = new File(filename);
     data = content.getDataAsStream();
     channelSftp.put(data, f.getName());
     logger.info("File transfered successfully to host.");
   } catch (Exception ex) {
     throw new IOException("SFTP problem", ex);
   } finally {
     if (data != null) {
       try {
         data.close();
       } catch (IOException e) {
       }
     }
     if (channelSftp != null) {
       channelSftp.exit();
     }
     logger.info("sftp Channel exited.");
     if (channel != null) {
       channel.disconnect();
     }
     logger.info("Channel disconnected.");
     if (session != null) {
       session.disconnect();
     }
     logger.info("Host Session disconnected.");
   }
 }
示例#12
0
  @BeforeClass(alwaysRun = true)
  public void initServer() throws JSchException {
    testDataCreator.create();
    sshServer.start();

    final JSch jsch = new JSch();
    session = jsch.getSession("admin", "localhost", SshServerWrapper.DEFAULT_PORT);
    final java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setPassword("admin");
    session.connect();
  }
示例#13
0
 public Session getSession() {
   Session session;
   try {
     JSch jSch = new JSch();
     session = jSch.getSession(username, host, port);
     session.setPassword(passwd);
     UserInfo userInfo = new MyUser(passwd, null);
     session.setConfig("PreferredAuthentications", "publickey,password,keyboard-interactive");
     session.setUserInfo(userInfo);
   } catch (JSchException e) {
     e.printStackTrace();
     return null;
   }
   return session;
 }
示例#14
0
  /**
   * @param userName the name of the account being logged into.
   * @param hostName this should be the host. I found values like <code>foo.com</code> work, where
   *     <code>http://foo.com</code> don't.
   * @param userPassword if you are not using key based authentication, then you are likely being
   *     prompted for a password each time you login. This is that password. It is <em>not</em> the
   *     passphrase for the private key!
   * @param port the default is 22, and if you specify N<0 for this value we'll default it to 22
   * @param knownHostsFile this is the known hosts file. If you don't specify it, jsch does some
   *     magic to work without your specification. If you have it in a non well-known location,
   *     however, this property is for you. An example: <code>/home/user/.ssh/known_hosts</code>
   * @param knownHostsInputStream this is the known hosts file. If you don't specify it, jsch does
   *     some magic to work without your specification. If you have it in a non well-known location,
   *     however, this property is for you. An example: <code>/home/user/.ssh/known_hosts</code>.
   *     Note that you may specify this <em>or</em> the #knownHostsFile - not both!
   * @param privateKey this is usually used when you want passwordless automation (obviously, for
   *     this integration it's useless since this lets you specify a password once, anyway, but
   *     still good to have if required). This file might be ~/.ssh/id_dsa, or a <code>.pem</code>
   *     for your remote server (for example, on EC2)
   * @param pvKeyPassPhrase sometimes, to be extra secure, the private key itself is extra
   *     encrypted. In order to surmount that, we need the private key passphrase. Specify that
   *     here.
   * @throws Exception thrown if any of a myriad of scenarios plays out
   */
  public SftpSession(
      String userName,
      String hostName,
      String userPassword,
      int port,
      String knownHostsFile,
      InputStream knownHostsInputStream,
      String privateKey,
      String pvKeyPassPhrase)
      throws Exception {
    JSch jSch = new JSch();

    if (port <= 0) {
      port = 22;
    }

    this.privateKey = privateKey;
    this.privateKeyPassphrase = pvKeyPassPhrase;

    if (!StringUtils.isEmpty(knownHostsFile)) {
      jSch.setKnownHosts(knownHostsFile);
    } else if (null != knownHostsInputStream) {
      jSch.setKnownHosts(knownHostsInputStream);
    }

    // private key
    if (!StringUtils.isEmpty(this.privateKey)) {
      if (!StringUtils.isEmpty(privateKeyPassphrase)) {
        jSch.addIdentity(this.privateKey, privateKeyPassphrase);
      } else {
        jSch.addIdentity(this.privateKey);
      }
    }

    session = jSch.getSession(userName, hostName, port);

    if (!StringUtils.isEmpty(userPassword)) {
      session.setPassword(userPassword);
    }

    userInfo = new OptimisticUserInfoImpl(userPassword);
    session.setUserInfo(userInfo);
    session.connect();
    channel = (ChannelSftp) session.openChannel("sftp");
  }
  public static Session getSession(String host, String user, String pwd, int port) {
    Session session = null;
    Properties config = null;
    JSch jsch = null;
    try {
      jsch = new JSch();
      session = jsch.getSession(user, host, port);
      session.setPassword(pwd);
      config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
    } catch (Exception e) {
      session = null;
      e.printStackTrace();
    }

    return session;
  }
 @Test
 public void testFailToConnect() throws Exception {
   hostConfig = createWithOverrideUsernameAndPassword(mockJSch);
   getHostConfig().setCommonConfig(new BapSshCommonConfiguration("", "", "", false));
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(TEST_PASSPHRASE);
   mockSession.setConfig((Properties) anyObject());
   final JSchException exception = new JSchException("meh");
   mockSession.connect(getHostConfig().getTimeout());
   expectLastCall().andThrow(exception);
   expect(mockSession.isConnected()).andReturn(false);
   assertCreateClientThrowsException(exception);
 }
示例#17
0
  /**
   * @param filename The complete filename which will be after receiving file
   * @param user
   * @param host
   * @param password
   * @param remotFolder
   * @return
   */
  public static int getFileSFTP(
      String filename, String user, String host, String password, String remotFolder) {
    ResourceBundle rb = ResourceBundle.getBundle(EzLinkConstant.PATH_CONFIG_PROPERTY_FILE_NAME);
    File f = new File(filename);
    logger.error("SFTP file receive start");
    JSch jsch = new JSch();
    Session session = null;
    int error = 0;
    try {
      session = jsch.getSession(user, host, 22);
      session.setConfig("StrictHostKeyChecking", "no");
      session.setPassword(password);
      //		    UserInfo ui=new MyUserInfo();
      //		      session.setUserInfo(ui);
      session.connect();

      Channel channel = session.openChannel("sftp");
      channel.connect();
      ChannelSftp sftpChannel = (ChannelSftp) channel;
      logger.debug("receiving file:" + f.getAbsolutePath());
      SftpProgressMonitor monitor = new MyProgressMonitor();
      sftpChannel.cd(remotFolder);
      sftpChannel.lcd(f.getParent());
      sftpChannel.get(f.getName(), f.getName(), monitor, ChannelSftp.OVERWRITE);
      sftpChannel.exit();
      //		    session.disconnect();
      logger.error("SFTP file receive successfully");
    } catch (JSchException e) {
      logger.error(
          "File transfer Exception",
          e); // To change body of catch statement use File | Settings | File Templates.
      error = -1;
    } catch (SftpException e) {
      logger.error("SFTP Exception", e);
      error = -2;
      //		} catch (FileNotFoundException e) {
      //			logger.error("File not found to transfer"+filename);
    } finally {

      session.disconnect();
    }
    return error;
  }
  private static void runCommandOnHost(String host, String user, String password, String command) {
    try {
      JSch jsch = new JSch();

      Session session = jsch.getSession(user, host, 22);
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.setPassword(password);
      session.connect();
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      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;
        }
        if (channel.isClosed()) {
          if (in.available() > 0) continue;
          // System.out.println("exit-status: "+channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception ee) {
        }
      }
      channel.disconnect();
      session.disconnect();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  @Test
  public void testSendFileWithSftpException() throws Exception {
    mockJSch = createMock(JSch.class);
    mockSession = createMock(Session.class);
    mockChannelSftp = createMock(ChannelSftp.class);
    expect(mockJSch.getSession(USERNAME, HOSTNAME, PORT)).andReturn(mockSession);
    mockSession.setPassword(PASSWORD);
    mockSession.setConfig(STRICTHOSTKEYCHECKING, STRICTHOSTKEYCHECKING_VALUE);
    mockSession.connect();
    expect(mockSession.openChannel("sftp")).andReturn(mockChannelSftp);
    mockChannelSftp.connect();
    mockChannelSftp.put(isA(InputStream.class), eq(FTPDESTINATIONFILENAME));
    expectLastCall().andThrow(new SftpException(1, "Test"));
    replay(mockJSch, mockSession, mockChannelSftp);

    sftpClientImpl.setJsch(mockJSch);

    assertEquals(false, sftpClientImpl.sendFile(FILE_CONTENT));
    assertEquals("Error in SftpClient\n", logFactoryMock.getError(true));
  }
  public static void main(String[] s) throws IOException, JSchException, SftpException {
    JSch jsch = new JSch();
    Session session = null;
    session = jsch.getSession("username", "machineIp/hostname", 22);
    session.setPassword("userpass");
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    ChannelSftp channel = null;
    channel = (ChannelSftp) session.openChannel("sftp");
    channel.connect();
    String destinationPath = "C:\\logs\\";
    channel.cd("/home/username/");
    Vector<ChannelSftp.LsEntry> list = channel.ls("*.txt");
    for (ChannelSftp.LsEntry entry : list) {
      channel.get(entry.getFilename(), destinationPath + entry.getFilename());
    }

    channel.disconnect();
    session.disconnect();
  }
 private BapSshClient assertCreateWithDefaultInfo(final String responseFromPwd)
     throws JSchException, SftpException {
   final BapSshCommonConfiguration commonConfiguration =
       new BapSshCommonConfiguration("Ignore me", null, null, false);
   getHostConfig().setCommonConfig(commonConfiguration);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(getHostConfig().getPassword());
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   if (responseFromPwd != null) expect(mockSftp.pwd()).andReturn(responseFromPwd);
   return assertCreateClient();
 }
  /** Connect the socket and open the connection. */
  public void connect(String host, int port, String username, String password) throws IOException {
    if (debug > 0) System.err.println("Wrapper: connect(" + host + "," + port + ")");

    this.host = host;
    this.port = port;
    this.username = username;
    this.password = password;

    if (isClosed()) {
      try {
        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setUserInfo(defaultUserInfo);
        session.connect();
        System.out.println("connected");
      } catch (JSchException e) {
        e.printStackTrace();
        throw new IOException("connect or authenticate failed");
      }
    }
  }
 @Test
 public void testCreateClientWithDefaultPassword() throws Exception {
   final BapSshCommonConfiguration defaultKeyInfo =
       new BapSshCommonConfiguration(TEST_PASSPHRASE, null, null, false);
   hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo);
   getHostConfig().setPassword("Ignore me");
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(defaultKeyInfo.getPassphrase());
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   assertCreateClient();
 }
示例#24
0
  public String Conecta(String host, String command)
      throws JSchException, IOException, InterruptedException {

    ConstantesUsers constantes = new ConstantesUsers();

    JSch jsch = new JSch();
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    Session session = jsch.getSession(constantes.getUser(), host, constantes.getPort());
    session.setPassword(constantes.getPassword());
    session.setConfig(config);
    String saida = null;
    if (!session.isConnected()) {
      session.connect();
      //			System.out.println("Conectado");
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
      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));
          saida = new String(tmp, 0, i);
        }
        if (channel.isClosed()) {
          channel.disconnect();
          break;
        }
      }

      channel.disconnect();
      session.disconnect();
    } else {
      System.out.println("Conexao já estabelecida");
    }
    return saida;
  }
示例#25
0
  public void login(String password) throws KettleJobException {
    this.password = password;

    s.setPassword(this.getPassword());
    try {
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      // set compression property
      // zlib, none
      String compress = getCompression();
      if (compress != null) {
        config.put(COMPRESSION_S2C, compress);
        config.put(COMPRESSION_C2S, compress);
      }
      s.setConfig(config);
      s.connect();
      Channel channel = s.openChannel("sftp");
      channel.connect();
      c = (ChannelSftp) channel;
    } catch (JSchException e) {
      throw new KettleJobException(e);
    }
  }
 @Before
 public void setup() throws JSchException, SftpException {
   mockJSch = createMock(JSch.class);
   mockSession = createMock(Session.class);
   mockChannelSftp = createMock(ChannelSftp.class);
   expect(mockJSch.getSession(USERNAME, HOSTNAME, PORT)).andReturn(mockSession);
   mockSession.setPassword(PASSWORD);
   mockSession.setConfig(STRICTHOSTKEYCHECKING, STRICTHOSTKEYCHECKING_VALUE);
   mockSession.connect();
   expect(mockSession.openChannel("sftp")).andReturn(mockChannelSftp);
   mockChannelSftp.connect();
   mockChannelSftp.put(isA(InputStream.class), eq(FTPDESTINATIONFILENAME));
   mockChannelSftp.disconnect();
   mockSession.disconnect();
   replay(mockJSch, mockSession, mockChannelSftp);
   sftpClientImpl.setJsch(mockJSch);
   sftpClientImpl.setFtpDestinationFileName(FTPDESTINATIONFILENAME);
   sftpClientImpl.setHostname(HOSTNAME);
   sftpClientImpl.setPassword(PASSWORD);
   sftpClientImpl.setUsername(USERNAME);
   sftpClientImpl.setPort(PORT);
   logFactoryMock.getError(true);
 }
示例#27
0
  public ScpClient() throws JSchException {

    String user =
        ConsoleLogPlugin.getDefault()
            .getPreferenceStore()
            .getString(ConsoleLogPreferenceConstants.SCP_USER);
    String host =
        ConsoleLogPlugin.getDefault()
            .getPreferenceStore()
            .getString(ConsoleLogPreferenceConstants.HOST_NAME);

    JSch jsch = new JSch();

    session = jsch.getSession(user, host, 22);

    session.setPassword(
        ConsoleLogPlugin.getDefault()
            .getPreferenceStore()
            .getString(ConsoleLogPreferenceConstants.SCP_PASSWORD));
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no"); // $NON-NLS-1$ //$NON-NLS-2$
    session.setConfig(config);
    session.connect();
  }
示例#28
-1
 @Override
 public Session create() throws Exception {
   JSch jsch = new JSch();
   session =
       jsch.getSession(
           loginCredentials.getUser(),
           hostAndPort.getHostText(),
           hostAndPort.getPortOrDefault(22));
   if (sessionTimeout != 0) session.setTimeout(sessionTimeout);
   if (loginCredentials.getPrivateKey() == null) {
     session.setPassword(loginCredentials.getPassword());
   } else {
     byte[] privateKey = loginCredentials.getPrivateKey().getBytes();
     if (CredentialUtils.isPrivateKeyEncrypted(privateKey)) {
       throw new IllegalArgumentException(
           "JschSshClientModule does not support private keys that require a passphrase");
     }
     jsch.addIdentity(
         loginCredentials.getUser(),
         Arrays.copyOf(privateKey, privateKey.length),
         null,
         emptyPassPhrase);
   }
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect(connectTimeout);
   return session;
 }
示例#29
-1
 public void openSshConnection() throws JSchException {
   JSch jSch = new JSch();
   if (privateKeyLocation != null) {
     session = jSch.getSession(username, destinationHost, connectionPort);
     jSch.addIdentity(privateKeyLocation);
   } else {
     session = jSch.getSession(username, destinationHost, connectionPort);
     session.setPassword(password);
   }
   session.setConfig("StrictHostKeyChecking", "no");
   session.setConfig(
       "PreferredAuthentications",
       "publickey,keyboard-interactive,password"); // Skipping kerberos authentication
   session.connect(SLEEP_MILLISECONDS);
 }
 /**
  * method for establishing connection while authentication
  *
  * @param username
  * @param namenodeIP
  * @param nnpwd
  * @param privateKeyPath
  * @return
  * @throws JSchException
  * @throws IOException
  * @throws InterruptedException
  */
 public static Session establishConnection(
     String username, String namenodeIP, String nnpwd, String privateKeyPath)
     throws JSchException, IOException, InterruptedException {
   JSch jsch = new JSch();
   Session session = jsch.getSession(username, namenodeIP, Constants.TWENTY_TWO);
   session.setPassword(nnpwd);
   UserInfo info = new JumbuneUserInfo();
   jsch.addIdentity(privateKeyPath, nnpwd);
   session.setUserInfo(info);
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
   return session;
 }