Ejemplo n.º 1
2
 public String sendCommand(Session session, String Command) {
   StringBuilder result = new StringBuilder();
   try {
     Channel channel = session.openChannel("exec");
     ((ChannelExec) channel).setCommand(Command);
     InputStream in = channel.getInputStream();
     channel.connect();
     byte[] tmp = new byte[1024];
     boolean allow = true;
     while (allow) {
       while (in.available() > 0) {
         int i = in.read(tmp, 0, 1024);
         if (i < 0) break;
         result.append(new String(tmp, 0, i));
       }
       if (channel.isClosed()) {
         if (in.available() > 0) continue;
         System.out.println("exit-status: " + channel.getExitStatus());
         break;
       }
     }
     channel.disconnect();
     return result.toString();
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Ejemplo n.º 2
0
 private void executeCommand(final String command) throws JSchException, IOException {
   c = (ChannelExec) session.openChannel("exec");
   c.setCommand(command);
   latestChannelOutputStream = c.getOutputStream();
   latestChannelInputStream = c.getInputStream();
   c.connect();
 }
Ejemplo n.º 3
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();
      }
    }
  }
Ejemplo n.º 4
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 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);
 }
 @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();
 }
Ejemplo n.º 7
0
  private String execAndGetOutput(String command)
      throws JSchException, MachineException, IOException {
    ChannelExec exec = (ChannelExec) session.openChannel("exec");
    exec.setCommand(command);

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        InputStream erStream = exec.getErrStream()) {

      exec.connect(connectionTimeout);

      ListLineConsumer listLineConsumer = new ListLineConsumer();
      String line;
      while ((line = reader.readLine()) != null) {
        listLineConsumer.writeLine(line);
      }
      // read stream to wait until command finishes its work
      IoUtil.readStream(erStream);
      if (exec.getExitStatus() != 0) {
        throw new MachineException(
            format(
                "Error code: %s. Error: %s",
                exec.getExitStatus(), IoUtil.readAndCloseQuietly(exec.getErrStream())));
      }
      return listLineConsumer.getText();
    } finally {
      exec.disconnect();
    }
  }
Ejemplo n.º 8
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;
  }
 @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());
   }
 }
Ejemplo n.º 11
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;
  }
Ejemplo n.º 12
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;
  }
Ejemplo n.º 13
0
  /**
   * This method execute the given command over SSH using shell prompt
   *
   * @param session
   * @param command Command to be executed
   * @throws JSchException
   * @throws IOException
   * @throws InterruptedException
   */
  public static String executeCommandUsingShell(Session session, String echoCommand)
      throws JSchException, IOException {
    ChannelShell channelShell = null;
    BufferedReader brIn = null;
    DataOutputStream dataOut = null;
    String hadoopHome = null;
    try {
      channelShell = (ChannelShell) session.openChannel("shell");
      channelShell.connect();
      brIn = new BufferedReader(new InputStreamReader(channelShell.getInputStream()));
      dataOut = new DataOutputStream(channelShell.getOutputStream());
      dataOut.writeBytes(echoCommand);
      dataOut.flush();
      String line = null;
      while ((line = brIn.readLine()) != null) {
        if (line.contains("$ echo $HADOOP_HOME")) {
          hadoopHome = brIn.readLine();
          break;
        }
      }

    } finally {
      if (brIn != null) {
        brIn.close();
      }
      if (dataOut != null) {
        dataOut.close();
      }
      if (channelShell != null) {
        channelShell.disconnect();
      }
    }
    return hadoopHome;
  }
Ejemplo n.º 14
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();
    }
  }
Ejemplo n.º 15
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();
      }
    }
  }
 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();
 }
Ejemplo n.º 17
0
  /**
   * Copy a file to specific destination with WinSCP command
   *
   * @param lfile file you want to transfer
   * @param rfile destination file
   */
  public synchronized void scpTo(String lfile, String rfile) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    try {
      // exec 'scp -t rfile' remotely
      String command = "scp -p -t " + rfile;

      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      // get I/O streams for remote scp
      OutputStream out = channel.getOutputStream();
      InputStream in = channel.getInputStream();

      channel.connect();

      // byte[] tmp = new byte[1];
      checkAck(in);

      // send "C0644 filesize filename", where filename should not include '/'
      int filesize = (int) (new File(lfile)).length();
      command = "C0644 " + filesize + " ";
      if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
      } else {
        command += lfile;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      checkAck(in);

      // send a content of lfile
      FileInputStream fis = new FileInputStream(lfile);
      byte[] buf = new byte[1024];
      while (true) {
        int len = fis.read(buf, 0, buf.length);
        if (len <= 0) break;
        out.write(buf, 0, len);
        out.flush();
      }
      fis.close();

      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();

      checkAck(in);
    } catch (Exception e) {
      throw new ItemNotFoundException("Failed to copy file: " + e.getMessage());
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
Ejemplo n.º 18
0
 /**
  * @param session
  * @return
  * @throws JSchException
  */
 private ChannelExec getExecChannel(Session session) throws IOException {
   ChannelExec channel;
   try {
     channel = (ChannelExec) session.openChannel("exec");
   } catch (JSchException e) {
     throw new IOException();
   }
   return channel;
 }
Ejemplo 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();
 }
Ejemplo n.º 20
0
  private void copyRecursively(String sourceFolder, String targetFolder) throws MachineException {
    // create target dir
    try {
      int execCode = execAndGetCode("mkdir -p " + targetFolder);

      if (execCode != 0) {
        throw new MachineException(
            format("Creation of folder %s failed. Exit code is %s", targetFolder, execCode));
      }
    } catch (JSchException | IOException e) {
      throw new MachineException(
          format("Creation of folder %s failed. Error: %s", targetFolder, e.getLocalizedMessage()));
    }

    // not normalized paths don't work
    final String targetAbsolutePath = getAbsolutePath(targetFolder);

    // copy files
    ChannelSftp sftp = null;
    try {
      sftp = (ChannelSftp) session.openChannel("sftp");
      sftp.connect(connectionTimeout);

      final ChannelSftp finalSftp = sftp;
      Files.walkFileTree(
          Paths.get(sourceFolder),
          new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
              try {
                if (!attrs.isDirectory()) {
                  copyFile(
                      file.toString(),
                      Paths.get(targetAbsolutePath, file.getFileName().toString()).toString(),
                      finalSftp);
                } else {
                  finalSftp.mkdir(file.normalize().toString());
                }
              } catch (MachineException | SftpException e) {
                throw new IOException(
                    format(
                        "Sftp copying of file %s failed. Error: %s",
                        file, e.getLocalizedMessage()));
              }
              return FileVisitResult.CONTINUE;
            }
          });
    } catch (JSchException | IOException e) {
      throw new MachineException("Copying failed. Error: " + e.getLocalizedMessage());
    } finally {
      if (sftp != null) {
        sftp.disconnect();
      }
    }
  }
Ejemplo n.º 21
0
 private void executeShellScripts(Session session) throws IOException, JSchException {
   Channel channel = session.openChannel("shell");
   File shellScript = new File("scripts/ubuntu-scripts.txt");
   FileInputStream fin = new FileInputStream(shellScript);
   byte fileContent[] = new byte[(int) shellScript.length()];
   fin.read(fileContent);
   InputStream in = new ByteArrayInputStream(fileContent);
   channel.setInputStream(in);
   channel.setOutputStream(System.out);
   channel.connect();
 }
Ejemplo n.º 22
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.");
   }
 }
Ejemplo n.º 23
0
 private ChannelSftp getSftp() {
   checkConnected();
   logger.debug("%s@%s:%d: Opening sftp Channel.", username, host, port);
   ChannelSftp sftp = null;
   try {
     sftp = (ChannelSftp) session.openChannel("sftp");
     sftp.connect();
   } catch (JSchException e) {
     throw new SshException(
         String.format("%s@%s:%d: Error connecting to sftp.", username, host, port), e);
   }
   return sftp;
 }
Ejemplo n.º 24
0
 private void copyFile(String sourcePath, String targetPath) throws MachineException {
   ChannelSftp sftp = null;
   try {
     sftp = (ChannelSftp) session.openChannel("sftp");
     sftp.connect(connectionTimeout);
     String absoluteTargetPath = getAbsolutePath(targetPath);
     copyFile(sourcePath, absoluteTargetPath, sftp);
   } catch (JSchException e) {
     throw new MachineException("Sftp copying failed. Error: " + e.getLocalizedMessage());
   } finally {
     if (sftp != null) {
       sftp.disconnect();
     }
   }
 }
Ejemplo n.º 25
0
  void scpStringToFile(Session session, String workingDir, String fileName, String userDataString)
      throws PortalServiceException {
    String command = "scp -t " + workingDir + "/" + fileName;

    ChannelExec channel;
    try {
      channel = (ChannelExec) session.openChannel("exec");
    } catch (JSchException e1) {
      throw new PortalServiceException(e1.getMessage(), e1);
    }
    channel.setCommand(command);

    // get I/O streams for remote scp
    try (OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream()) {
      channel.connect();

      checkAck(in);

      byte[] userData = userDataString.getBytes("UTF-8");

      // send "C0644 filesize filename", where filename should not include '/'
      long filesize = userData.length;
      command = "C0644 " + filesize + " " + fileName;
      // if (lfile.lastIndexOf('/') > 0) {
      // command += lfile.substring(lfile.lastIndexOf('/') + 1);
      // } else {
      // command += lfile;
      // }
      command += "\n";
      out.write(command.getBytes());
      out.flush();

      checkAck(in);

      out.write(userData);
      out.write(0);

      out.flush();
      checkAck(in);
      out.close();

    } catch (IOException | JSchException e) {
      throw new PortalServiceException(e.getMessage(), e);
    }

    channel.disconnect();
  }
Ejemplo n.º 26
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);
    }
  }
  /**
   * Gets the value of the specified environment variable.
   *
   * @param ses SSH session.
   * @param cmd environment variable name.
   * @return environment variable value.
   * @throws JSchException In case of SSH error.
   * @throws IOException If failed.
   */
  private String exec(Session ses, String cmd) throws JSchException, IOException {
    ChannelExec ch = null;

    try {
      ch = (ChannelExec) ses.openChannel("exec");

      ch.setCommand(cmd);

      ch.connect();

      try (BufferedReader reader = new BufferedReader(new InputStreamReader(ch.getInputStream()))) {
        return reader.readLine();
      }
    } finally {
      if (ch != null && ch.isConnected()) ch.disconnect();
    }
  }
Ejemplo n.º 28
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");
  }
Ejemplo n.º 29
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();
  }
Ejemplo n.º 30
0
 /**
  * FIXME Comment this
  *
  * @param session
  * @param cmd
  * @return return code of the process.
  * @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
  */
 private int executeCommand(Session session, String cmd)
     throws JSchException, IOException, TimeoutException {
   final ChannelExec channel;
   session.setTimeout((int) maxwait);
   /* execute the command */
   channel = (ChannelExec) session.openChannel("exec");
   channel.setCommand(cmd);
   attachStreams(channel);
   project.log("executing command: " + cmd, Project.MSG_VERBOSE);
   channel.connect();
   try {
     waitFor(channel);
   } finally {
     streamHandler.stop();
     closeStreams(channel);
   }
   return channel.getExitStatus();
 }