@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);
 }
Exemplo n.º 3
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();
    }
  }
 @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();
 }
Exemplo n.º 5
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");
  }
Exemplo n.º 6
0
 @Override
 public void clear() {
   if (session != null && session.isConnected()) {
     session.disconnect();
     session = null;
   }
 }
 @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();
 }
Exemplo n.º 8
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;
  }
Exemplo n.º 9
0
  /**
   * This will execute the given command with given session and session is not closed at the end.
   *
   * @param commandInfo
   * @param session
   * @param commandOutput
   * @throws SSHApiException
   */
  public static Session executeCommand(
      CommandInfo commandInfo, Session session, CommandOutput commandOutput)
      throws SSHApiException {

    String command = commandInfo.getCommand();

    Channel channel = null;
    try {
      if (!session.isConnected()) {
        session.connect();
      }
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
    } catch (JSchException e) {
      session.disconnect();

      throw new SSHApiException("Unable to execute command - ", e);
    }

    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(commandOutput.getStandardError());
    try {
      channel.connect();
    } catch (JSchException e) {

      channel.disconnect();
      session.disconnect();
      throw new SSHApiException("Unable to retrieve command output. Command - " + command, e);
    }

    commandOutput.onOutput(channel);
    // Only disconnecting the channel, session can be reused
    channel.disconnect();
    return session;
  }
Exemplo n.º 10
0
 @PreDestroy
 public void disconnect() {
   if (session != null && session.isConnected()) {
     session.disconnect();
     session = null;
   }
 }
Exemplo n.º 11
0
  /**
   * Execute the command on the remote host.
   *
   * @param command - what to execute on the remote host.
   * @return return code of the process.
   * @throws BuildException bad parameter.
   * @throws JSchException if there's an underlying problem exposed in SSH
   * @throws IOException if there's a problem attaching streams.
   * @throws TimeoutException if we exceeded our timeout
   */
  public int execute(String command)
      throws BuildException, JSchException, IOException, TimeoutException {
    if (command == null) {
      throw new BuildException("Command is required.");
    }
    if (host == null) {
      throw new BuildException("Host is required.");
    }
    if (userInfo.getName() == null) {
      throw new BuildException("Username is required.");
    }
    if (userInfo.getKeyfile() == null && userInfo.getPassword() == null) {
      throw new BuildException("Password or Keyfile is required.");
    }

    Session session = null;
    try {
      session = openSession();
      return executeCommand(session, command);
    } finally {
      if (session != null && session.isConnected()) {
        session.disconnect();
      }
    }
  }
 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());
   }
 }
Exemplo n.º 13
0
 public void init() {
   sshSession = new SSHSession();
   Session session = sshSession.openSession("root", "123456", "10.16.0.110", 22);
   fileSender = new FileSender(session);
   boolean isUploaded = fileSender.upload("/opt/", new File("E:/akka-demo/akka-demo.iml"));
   session.disconnect();
 }
Exemplo n.º 14
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;
  }
Exemplo n.º 15
0
 /**
  * Get connection info for use in diagnostics messages
  *
  * @param session the session
  * @return a string to use in messages
  */
 public static String getSessionInfo(Session session) {
   if (session == null) {
     return "Not connected to any host";
   } else {
     return "SSH connection to " + session.getHost() + ":" + session.getPort();
   }
 }
 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();
 }
Exemplo n.º 17
0
 public void disconnect() throws GenericFileOperationFailedException {
   if (session != null && session.isConnected()) {
     session.disconnect();
   }
   if (channel != null && channel.isConnected()) {
     channel.disconnect();
   }
 }
  /**
   * Determines whether a vaild session exists for the contact of remote machine.
   *
   * @param sshContact ID of SSH Contact
   * @return <tt>true</tt> if the session is connected <tt>false</tt> otherwise
   */
  public boolean isSessionValid(ContactSSH sshContact) {
    Session sshSession = sshContact.getSSHSession();
    if (sshSession != null) if (sshSession.isConnected()) return true;

    // remove reference to an unconnected SSH Session, if any
    sshContact.setSSHSession(null);
    return false;
  }
Exemplo n.º 19
0
 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();
 }
Exemplo n.º 20
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();
 }
Exemplo n.º 21
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();
  }
Exemplo n.º 22
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;
 }
Exemplo n.º 23
0
 @Override
 public void start() throws MachineException {
   try {
     session = jsch.getSession(username, host, port);
     session.setUserInfo(user);
     // todo remember parent pid of shell to be able to kill all processes on client stop
     if (!session.isConnected()) {
       session.connect(connectionTimeout);
     }
   } catch (JSchException e) {
     throw new MachineException(
         "Ssh machine creation failed because ssh of machine is inaccessible. Error: "
             + e.getLocalizedMessage());
   }
 }
Exemplo n.º 24
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();
    }
  }
Exemplo n.º 25
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);
    }
  }
Exemplo n.º 26
0
  public ExecResult executeCommand(Session session, String command, String workingDir)
      throws PortalServiceException {
    ChannelExec channel = null;
    if (workingDir != null) {
      command = "cd " + workingDir + "; " + command;
    }

    try {
      channel = (ChannelExec) session.openChannel("exec");
      channel.setCommand(command);
      channel.setInputStream(null);
      channel.setErrStream(null);

      channel.connect();

      try (InputStream out = channel.getInputStream();
          InputStream err = channel.getErrStream()) {
        String outStr = readStream(out, channel);
        String errStr = readStream(err, channel);
        return new ExecResult(outStr, errStr, channel.getExitStatus());
      } catch (IOException | InterruptedException e) {
        throw new PortalServiceException(e.getMessage(), e);
      }
    } catch (JSchException e) {
      throw new PortalServiceException(e.getMessage(), e);
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
Exemplo n.º 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;
 }
Exemplo n.º 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;
 }
Exemplo n.º 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);
 }
Exemplo n.º 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;
 }