@Test
 public void testCreateClientWithOverrideKeyPath() throws Exception {
   final String testKeyFilename = "myPrivateKey";
   final RandomFile theKey = new RandomFile(jenkinsHome.getRoot(), testKeyFilename);
   hostConfig =
       createWithOverrideUsernameAndPassword(mockJSch, TEST_PASSPHRASE, testKeyFilename, "");
   final BapSshCommonConfiguration commonConfiguration =
       new BapSshCommonConfiguration("Ignore me", null, null, false);
   getHostConfig().setCommonConfig(commonConfiguration);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockJSch.addIdentity(
       isA(String.class),
       aryEq(theKey.getContents()),
       (byte[]) isNull(),
       aryEq(BapSshUtil.toBytes(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());
   assertCreateClient();
 }
 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());
   }
 }
Пример #3
0
  static boolean getConnection(String username, String password, String host, int port) {
    try {
      JSch jsch = new JSch();

      session = jsch.getSession(username, host, port);

      UserInfo ui = new MyUserInfo();
      session.setUserInfo(ui);
      MyUserInfo temp = (MyUserInfo) ui;

      temp.setPassword(password);

      session.connect();

      Channel channel = session.openChannel("sftp");
      channel.connect();
      SFTPFileLoader.sftpChannel = (ChannelSftp) channel;

      return true;

    } catch (Exception e) {
      System.out.println(e);
      errorMessage += e.toString();
    }

    return false;
  }
 void a(Buffer paramBuffer)
 {
   a(paramBuffer.d());
   a(paramBuffer.e());
   f(paramBuffer.d());
   byte[] arrayOfByte = paramBuffer.j();
   int i = paramBuffer.d();
   paramBuffer.j();
   paramBuffer.d();
   try
   {
     paramBuffer = j();
     x = b(paramBuffer, Util.b(arrayOfByte), i);
     if (x == null) {
       x = b(paramBuffer, null, i);
     }
     if ((x == null) && (JSch.d().a(3))) {
       JSch.d().a(3, "ChannelForwardedTCPIP: " + Util.b(arrayOfByte) + ":" + i + " is not registered.");
     }
     return;
   }
   catch (JSchException paramBuffer)
   {
     for (;;)
     {
       paramBuffer = null;
     }
   }
 }
Пример #5
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();
      }
    }
  }
Пример #6
0
  /* (non-Javadoc)
   * @see net.sf.thingamablog.transport.PublishTransport#connect()
   */
  public boolean connect() {
    failMsg = "";
    if (isConnected) {
      failMsg = "Already connected";
      return false;
    }

    try {
      JSch jsch = new JSch();
      Session session = jsch.getSession(getUserName(), getAddress(), getPort());

      // password will be given via UserInfo interface.
      UserInfo ui = new MyUserInfo(getPassword());
      session.setUserInfo(ui);

      logger.info("Connecting to SFTP");
      session.connect();
      logger.info("Logged in to SFTP");

      Channel channel = session.openChannel("sftp");
      channel.connect();
      sftp = (ChannelSftp) channel;

      isConnected = true;
      return true;
    } catch (Exception ex) {
      failMsg = "Error logging in to " + getAddress();
      failMsg += "\n" + ex.getMessage();
      logger.log(Level.WARNING, failMsg, ex);
      ex.printStackTrace();
    }

    return false;
  }
Пример #7
0
  private void runJschTest(int port) throws Exception {
    JSchLogger.init();
    JSch sch = new JSch();
    JSch.setConfig("cipher.s2c", CRYPT_NAMES);
    JSch.setConfig("cipher.c2s", CRYPT_NAMES);
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), "localhost", port);
    s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
    s.connect();

    try {
      com.jcraft.jsch.Channel c = s.openChannel("shell");
      c.connect();

      try (OutputStream os = c.getOutputStream();
          InputStream is = c.getInputStream()) {
        String expected = "this is my command\n";
        byte[] expData = expected.getBytes(StandardCharsets.UTF_8);
        byte[] actData = new byte[expData.length + Long.SIZE /* just in case */];
        for (int i = 0; i < 10; i++) {
          os.write(expData);
          os.flush();

          int len = is.read(actData);
          String actual = new String(actData, 0, len);
          assertEquals("Mismatched command at iteration " + i, expected, actual);
        }
      } finally {
        c.disconnect();
      }
    } finally {
      s.disconnect();
    }
  }
  public synchronized void setIdentityRepository() {

    IdentityRepository[] repositories = getPluggedInIdentityRepositries();
    String[] selected = Utils.getSelectedSSHAgent().split(","); // $NON-NLS-1$
    IdentityRepository irepo = null;

    for (int i = 0; i < selected.length; i++) {
      for (int j = 0; j < repositories.length; j++) {
        IdentityRepository _irepo = repositories[j];
        if (selected[i].equals(_irepo.getName())
            && _irepo.getStatus() == IdentityRepository.RUNNING) {
          irepo = _irepo;
          break;
        }
      }
      if (irepo != null) break;
    }

    if (irepo != null) {
      jsch.setIdentityRepository(irepo);
    } else {
      // set the internal default IdentityRepository
      jsch.setIdentityRepository(null);
    }
  }
 @Test
 public void testCreateClientWillUseKeyIfKeyAndKeyPathPresent() throws Exception {
   final String testKey = "MyVeryBigKey";
   final BapSshCommonConfiguration defaultKeyInfo =
       new BapSshCommonConfiguration(
           TEST_PASSPHRASE, testKey, "/this/file/will/not/be/used", false);
   hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo);
   getHostConfig().setPassword("Ignore me");
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockJSch.addIdentity(
       isA(String.class),
       aryEq(BapSshUtil.toBytes(testKey)),
       (byte[]) isNull(),
       aryEq(BapSshUtil.toBytes(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());
   assertCreateClient();
 }
 private BapSshClient assertCreateClientWithDefaultKey(final boolean disableExec)
     throws Exception {
   final String testKey = "MyVeryBigKey";
   final BapSshCommonConfiguration defaultKeyInfo =
       new BapSshCommonConfiguration(TEST_PASSPHRASE, testKey, null, disableExec);
   hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo);
   getHostConfig().setPassword("Ignore me");
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockJSch.addIdentity(
       isA(String.class),
       aryEq(BapSshUtil.toBytes(testKey)),
       (byte[]) isNull(),
       aryEq(BapSshUtil.toBytes(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());
   return assertCreateClient();
 }
Пример #11
0
  @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;
  };
Пример #12
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.");
   }
 }
Пример #13
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();
  }
Пример #14
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;
 }
 @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();
 }
 @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);
 }
Пример #17
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");
  }
  @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;
    }
  }
Пример #19
0
  public Connection(WebSocket ws, String host, String username, String password, int port) {
    try {
      JSch jsch = new JSch();
      jsch.setConfig("StrictHostKeyChecking", "no");

      // Spawn a session to the SSH server
      this.sshServerSession = jsch.getSession(username, host, port);
      this.sshServerSession.setPassword(password);
      this.sshServerSession.connect();

      this.ssh = new SSHConnection(ws, (ChannelShell) sshServerSession.openChannel("shell"));
      this.sftp = new SFTPConnection((ChannelSftp) sshServerSession.openChannel("sftp"));
    } catch (JSchException e) {
      e.printStackTrace();
    }
  }
Пример #20
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);
    }
  }
Пример #21
0
  protected void addKnownHosts() {
    //
    if ((config.sshKnowHostFile == null) || (config.sshKnowHostFile == null)) {
      logger.debug("addUserIDFiles(): No userConfigDir or knownHostFile configured");
      return;
    }
    // Config director is for example" ~/.ssh/
    String configDir = config.userConfigDir;
    String knownHostsFile = config.sshKnowHostFile;

    FSPath configPath;
    try {
      if (configDir != null) {
        configPath = FSUtil.getDefault().resolvePath(configDir);
        FSPath hostsFile = configPath.resolvePath(knownHostsFile);
        if (hostsFile.exists()) {
          jsch.setKnownHosts(hostsFile.getPathname());
        }
      }
    } catch (IOException e) {
      logger.error(
          "addKnownHosts():Failed to read/acces known hosts file:{}/{} => IOException:{}",
          configDir,
          knownHostsFile,
          e);
      return;
    } catch (JSchException e) {
      logger.error(
          "addKnownHosts():Failed to add known hosts file:{}/{} => JSchException:{}",
          configDir,
          knownHostsFile,
          e);
      return;
    }
  }
Пример #22
0
  public static void main(String[] arg) {

    String xhost = "127.0.0.1";
    int xport = 0;

    try {
      JSch jsch = new JSch();

      String host = null;
      if (arg.length > 0) {
        host = arg[0];
      } else {
        host =
            JOptionPane.showInputDialog(
                "Enter username@hostname", System.getProperty("user.name") + "@localhost");
      }
      String user = host.substring(0, host.indexOf('@'));
      host = host.substring(host.indexOf('@') + 1);

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

      String display =
          JOptionPane.showInputDialog("Please enter display name", xhost + ":" + xport);
      xhost = display.substring(0, display.indexOf(':'));
      xport = Integer.parseInt(display.substring(display.indexOf(':') + 1));

      session.setX11Host(xhost);
      session.setX11Port(xport + 6000);

      // username and password will be given via UserInfo interface.
      UserInfo ui = new MyUserInfo();
      session.setUserInfo(ui);
      session.connect();

      Channel channel = session.openChannel("shell");

      channel.setXForwarding(true);

      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);

      channel.connect();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Пример #23
0
  /**
   * Open an ssh seession.
   *
   * @return the opened session
   * @throws JSchException on error
   */
  protected Session openSession() throws JSchException {
    JSch jsch = new JSch();
    if (null != userInfo.getKeyfile()) {
      jsch.addIdentity(userInfo.getKeyfile());
    }

    if (!userInfo.getTrust() && knownHosts != null) {
      project.log("Using known hosts: " + knownHosts, Project.MSG_DEBUG);
      jsch.setKnownHosts(knownHosts);
    }

    Session session = jsch.getSession(userInfo.getName(), host, port);
    session.setUserInfo(userInfo);
    project.log("Connecting to " + host + ":" + port, Project.MSG_VERBOSE);
    session.connect();
    return session;
  }
Пример #24
0
  public static void main(String[] arg) throws JSchException, InterruptedException {
    JSch jsch = new JSch();

    String[] proxyInfo = queryUserAndHost("proxy server", arg.length > 0 ? arg[0] : null);

    Session gateway = jsch.getSession(proxyInfo[0], proxyInfo[1]);

    UserInfo ui = new SwingDialogUserInfo();
    gateway.setUserInfo(ui);
    gateway.connect();

    String[] targetInfo = queryUserAndHost("target server", arg.length > 1 ? arg[1] : null);

    Session session = jsch.getSession(targetInfo[0], targetInfo[1]);

    session.setProxy(new ProxySSH(gateway));

    session.setUserInfo(ui);

    System.err.println("connecting session ...");
    session.connect();

    System.err.println("session connected.");
    System.err.println("opening shell channel ...");

    Channel channel = session.openChannel("shell");

    channel.setOutputStream(System.out, true);
    channel.setExtOutputStream(System.err, true);

    channel.setInputStream(System.in, true);

    channel.connect();

    System.err.println("shell channel connected.");

    do {
      Thread.sleep(100);
    } while (!channel.isEOF());
    System.err.println("exitcode: " + channel.getExitStatus());
    session.disconnect();
    Thread.sleep(50);

    gateway.disconnect();
  }
Пример #25
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();
 }
  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;
  }
Пример #27
-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;
 }
Пример #28
-1
 private Session connectToInstance(String publicDNS) throws Exception {
   JSch jsch = new JSch();
   jsch.addIdentity("rtp.pem");
   Session session = jsch.getSession("ubuntu", publicDNS);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
   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);
 }
Пример #30
-1
 /**
  * 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;
 }