Esempio 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;
   }
 }
  /**
   * 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;
  }
Esempio n. 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;
  }
 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());
   }
 }
Esempio n. 5
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;
  }
Esempio n. 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();
      }
    }
  }
Esempio n. 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();
    }
  }
Esempio n. 8
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();
      }
    }
  }
 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();
 }
Esempio n. 10
0
 public boolean connectChannel() {
   try {
     channel.connect();
   } catch (JSchException e) {
     session.disconnect();
     NeptusLog.pub().error(this + " :: Could not connect a channel.", e);
     execResponse += "\n :: Could not connect a channel. " + e.getMessage();
     return false;
   }
   return true;
 }
Esempio n. 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.");
   }
 }
Esempio n. 12
0
 public static ChannelTunnel connect(final Channel channel) throws SshException {
   try {
     final InputStream in = channel.getInputStream();
     final OutputStream out = channel.getOutputStream();
     channel.connect();
     if (!checkAck(in)) {
       throw new SshException("Invalid acknowledgement received");
     }
     return new ChannelTunnel(in, out);
   } catch (IOException e) {
     throw new SshException(e);
   } catch (JSchException e) {
     throw new SshException(e);
   }
 }
  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);
    }
  }
Esempio n. 14
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();
  }
  public static boolean downloadFromSftp(
      String inputFile, String outPutFile, Session session, String testName) {
    Channel chFileDownload = null;
    ChannelSftp channelSftp = null;
    Properties prop = null;
    boolean isFileDownloaded = false;
    String sftpCompleted = "_SFTP_COMPLETED";
    try {
      System.out.println("inside download");
      System.out.println("------------------------------------");
      prop = PropertyReader.getPropeties("OMS");
      sftpCompleted = testName + sftpCompleted;
      sftpCompleted = prop.getProperty(sftpCompleted);
      chFileDownload = session.openChannel("sftp");
      chFileDownload.connect();
      channelSftp = (ChannelSftp) chFileDownload;
      channelSftp.cd(sftpCompleted);
      Vector<ChannelSftp.LsEntry> filelistcomp = channelSftp.ls(sftpCompleted);
      // System.out.println("inputFile---------->"+inputFile);
      // System.out.println("outPutFile---------->"+outPutFile);
      StringBuffer sb = new StringBuffer(inputFile);
      for (ChannelSftp.LsEntry filelist : filelistcomp) {
        if (!filelist.getAttrs().isDir()) {
          if (filelist.getFilename().contains(sb)) {
            // System.out.println("inside download loop");
            channelSftp.get(filelist.getFilename(), outPutFile);
            String filePath = outPutFile + filelist.getFilename();
            // System.out.println("filePath---------->"+filePath);
            File f = new File(outPutFile + filelist.getFilename());
            File targetFile = new File(outPutFile + inputFile);
            if (f.exists()) {
              // System.out.println("File downloaded");
              isFileDownloaded = true;
            }
            f.renameTo(targetFile);
          }
        }
      }

    } catch (Exception e) {

    }
    return isFileDownloaded;
  }
Esempio n. 16
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);
    }
  }
Esempio n. 18
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.outgoing.AbstractOutgoingFileTransfer
   * #openStreams()
   */
  protected void openStreams() throws IncomingFileTransferException {
    try {
      // Set input stream from local file
      final URL url = getRemoteFileURL();
      this.username = url.getUserInfo();

      scpUtil = new ScpUtil(this);
      final Session s = scpUtil.getSession();
      s.connect();

      final String command = SCP_COMMAND + scpUtil.trimTargetFile(url.getPath());
      channel = s.openChannel(SCP_EXEC);
      ((ChannelExec) channel).setCommand(command);
      channel.connect();

      final InputStream ins = channel.getInputStream();
      responseStream = channel.getOutputStream();
      scpUtil.sendZeroToStream(responseStream);

      final int c = checkAck(ins);
      if (c != 'C') throw new IOException(Messages.ScpRetrieveFileTransfer_EXCEPTION_SCP_PROTOCOL);
      // read '0644 '
      final byte[] buf = new byte[1024];
      ins.read(buf, 0, 5);

      setFileLength(readFileSize(ins, buf));
      readFileName(ins, buf);
      // set input stream for reading rest of file
      remoteFileContents = ins;

      scpUtil.sendZeroToStream(responseStream);

      fireReceiveStartEvent();
    } catch (final Exception e) {
      channel = null;
      username = null;
      throw new IncomingFileTransferException(
          NLS.bind(
              Messages.ScpRetrieveFileTransfer_EXCEPTION_CONNECTING, getRemoteFileURL().toString()),
          e);
    }
  }
  /**
   * Creates a channel for shell type in the current session channel types = shell, sftp, exec(X
   * forwarding), direct-tcpip(stream forwarding) etc
   *
   * @param sshContact ID of SSH Contact
   */
  public void createShellChannel(ContactSSH sshContact) throws IOException {
    try {
      Channel shellChannel = sshContact.getSSHSession().openChannel("shell");

      // initalizing the reader and writers of ssh contact
      sshContact.initializeShellIO(shellChannel.getInputStream(), shellChannel.getOutputStream());

      ((ChannelShell) shellChannel)
          .setPtyType(sshContact.getSSHConfigurationForm().getTerminalType());

      // initializing the shell
      shellChannel.connect(1000);

      sshContact.setShellChannel(shellChannel);

      sshContact.sendLine("export PS1=");
    } catch (JSchException ex) {
      sshContact.setSSHSession(null);
      throw new IOException("Unable to create shell channel to remote" + " server");
    }
  }
Esempio n. 20
0
 public String sendCommandShellChannel(Session session, List<String> lstCommand, String expected) {
   StringBuilder result = new StringBuilder();
   try {
     Channel channel = session.openChannel("shell");
     Expect expect = new Expect(channel.getInputStream(), channel.getOutputStream());
     expect.setDefault_timeout(30);
     channel.connect();
     for (String command : lstCommand) {
       Pattern p = Pattern.compile("ssh\\s\\w*@\\d*.\\d*.\\d*.\\d*");
       Matcher m = p.matcher(command);
       int start = 0;
       int end = 0;
       while (m.find()) {
         start = m.start();
         end = m.end();
       }
       if (start == 0 && end == 0) { // khong chay command ssh mtc@...
         expect.expect(expected);
         expect.send(command + "\n");
         expect.expect(expected);
         expect.send(command + "\n");
         expect.expect(expected);
         result.append(expect.before + expect.match);
       } else { // chay command ssh mtc@...
         expect.expect("$"); // dang dung o 137
         expect.send(command + "\n"); // send ssh mtc@...
         expect.expect(":");
         result.append(expect.before + expect.match);
         expect.send(passwd); // send passwd
         expect.expect(expected); // send expected cua mtc
         result.append(expect.before + expect.match);
       }
     }
     expect.close();
     return result.toString();
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Esempio n. 21
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;
  }
 /**
  * This method execute the given command over SSH
  *
  * @param session
  * @param command Command to be executed
  * @throws JSchException
  * @throws IOException
  * @throws InterruptedException
  */
 @SuppressWarnings("unused")
 private static void executeCommand(Session session, String command)
     throws JSchException, IOException, InterruptedException {
   InputStream in = null;
   Channel channel = null;
   try {
     channel = session.openChannel("exec");
     ((ChannelExec) channel).setCommand(command);
     channel.setInputStream(null);
     ((ChannelExec) channel).setErrStream(System.err);
     in = channel.getInputStream();
     channel.connect();
     String msg = validateCommandExecution(channel, in);
   } finally {
     if (in != null) {
       in.close();
     }
     if (channel != null) {
       channel.disconnect();
     }
   }
 }
Esempio n. 23
0
  public String runCommand(String params) {
    try {
      StringBuilder sb = new StringBuilder();
      Channel channel = ConnectionManager.getSession().openChannel("exec");
      channel.setInputStream(null);
      channel.setOutputStream(System.out);
      ((ChannelExec) channel).setCommand(params);
      ((ChannelExec) channel).setPty(false);
      channel.connect();
      InputStream in = channel.getInputStream();
      //			byte[] tmp = new byte[1024];
      while (true) {
        InputStreamReader is = new InputStreamReader(in);

        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();
        while (read != null) {
          System.out.println(read);
          sb.append(read);
          read = br.readLine();
        }
        if (channel.isClosed()) {
          System.out.println(sb.toString());
          System.out.println("exit-status:" + channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception ee) {
        }
      }
      channel.disconnect();
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return "empty";
    }
  }
 // Removing the Files from Error and completed folder
 public static boolean deleteFileFromSftp(
     String sftpCompleted, Session session, String sftpError) {
   Channel chFileRemove = null;
   ChannelSftp channelSftp = null;
   Properties prop = null;
   boolean isFileRemoved = false;
   boolean isFileComp = false;
   boolean isFileError = false;
   try {
     session.connect();
     prop = PropertyReader.getPropeties("OMS");
     // sftpCompleted=prop.getProperty(sftpCompleted);
     chFileRemove = session.openChannel("sftp");
     chFileRemove.connect();
     channelSftp = (ChannelSftp) chFileRemove;
     channelSftp.cd(sftpCompleted);
     Vector<ChannelSftp.LsEntry> filelist = channelSftp.ls(sftpCompleted);
     // System.out.println("befre filelist-------->"+filelist.size());
     for (ChannelSftp.LsEntry filelistComp : filelist) {
       if (!filelistComp.getAttrs().isDir()) {
         channelSftp.rm(filelistComp.getFilename());
       }
     }
     filelist = channelSftp.ls(sftpError);
     for (ChannelSftp.LsEntry filelistError : filelist) {
       if (!filelistError.getAttrs().isDir()) {
         channelSftp.rm(filelistError.getFilename());
       }
     }
     isFileRemoved = true;
   } catch (Exception e) {
     isFileRemoved = false;
     e.printStackTrace();
   } finally {
     chFileRemove.disconnect();
   }
   return isFileRemoved;
 }
Esempio n. 25
0
  /**
   * Carry out the transfer.
   *
   * @throws IOException on i/o errors
   * @throws JSchException on errors detected by scp
   */
  public void execute() throws IOException, JSchException {
    String command = "scp -f ";
    if (isRecursive) {
      command += "-r ";
    }
    command += remoteFile;
    Channel channel = openExecChannel(command);
    try {
      // get I/O streams for remote scp
      OutputStream out = channel.getOutputStream();
      InputStream in = channel.getInputStream();

      channel.connect();

      sendAck(out);
      startRemoteCpProtocol(in, out, localFile);
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
    log("done\n");
  }
Esempio n. 26
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);
    }
  }
Esempio n. 27
0
  public void execCmd(String command) {
    //        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    //        String command = "";
    BufferedReader reader = null;
    Channel channel = null;

    try {
      //            while ((command = br.readLine()) != null) {
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
      channel.setInputStream(null);
      ((ChannelExec) channel).setErrStream(System.err);

      channel.connect();
      InputStream in = channel.getInputStream();
      reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
      String buf = null;
      while ((buf = reader.readLine()) != null) {
        System.out.println(buf);
      }
      //            }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      channel.disconnect();
      session.disconnect();
    }
  }
  public static void main(String[] arg) {
    if (arg.length != 2) {
      System.err.println("usage: java ScpTo file1 user@remotehost:file2");
      System.exit(-1);
    }

    FileInputStream fis = null;
    try {

      String lfile = arg[0];
      String user = arg[1].substring(0, arg[1].indexOf('@'));
      arg[1] = arg[1].substring(arg[1].indexOf('@') + 1);
      String host = arg[1].substring(0, arg[1].indexOf(':'));
      String rfile = arg[1].substring(arg[1].indexOf(':') + 1);

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

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

      boolean ptimestamp = true;

      // exec 'scp -t rfile' remotely
      String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile;
      Channel 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();

      if (checkAck(in) != 0) {
        System.exit(0);
      }

      File _lfile = new File(lfile);

      if (ptimestamp) {
        command = "T " + (_lfile.lastModified() / 1000) + " 0";
        // The access time should be sent here,
        // but it is not accessible with JavaAPI ;-<
        command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
      }

      // send "C0644 filesize filename", where filename should not include '/'
      long filesize = _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();
      if (checkAck(in) != 0) {
        System.exit(0);
      }

      // send a content of lfile
      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();
      fis = null;
      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }
      out.close();

      channel.disconnect();
      session.disconnect();

      System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
    }
  }
  private static void scpConfigFile(
      String host,
      String user,
      String password,
      String runReporterConfigFilePath,
      String remoteFile) {
    FileInputStream fis = null;
    try {

      String lfile = runReporterConfigFilePath;
      String rfile = remoteFile;

      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();
      boolean ptimestamp = true;

      // exec 'scp -t rfile' remotely
      String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile;
      Channel 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();

      if (checkAck(in) != 0) {
        System.exit(0);
      }

      File _lfile = new File(lfile);

      if (ptimestamp) {
        command = "T " + (_lfile.lastModified() / 1000) + " 0";
        // The access time should be sent here,
        // but it is not accessible with JavaAPI ;-<
        command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
      }

      // send "C0644 filesize filename", where filename should not include '/'
      long filesize = _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();
      if (checkAck(in) != 0) {
        System.exit(0);
      }

      // send a content of lfile
      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();
      fis = null;
      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }
      out.close();

      channel.disconnect();
      session.disconnect();

    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
    }
  }
Esempio n. 30
-1
  public static void main(String[] arg) {
    try {
      JSch jsch = new JSch();

      String user = "******";
      String host = "hddev-c01-edge-01";
      int port = 22;
      String privateKey = "src/main/resources/id_rsa";

      jsch.addIdentity(privateKey);

      System.out.println("identity added ");

      Session session = jsch.getSession(user, host, port);
      System.out.println("session created.");

      // disabling StrictHostKeyChecking may help to make connection but makes it insecure
      // see
      // http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
      //
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);

      session.connect();
      System.out.println("session connected.....");

      Channel channel = session.openChannel("sftp");
      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);
      channel.connect();
      System.out.println("shell channel connected....");

      ChannelSftp c = (ChannelSftp) channel;

      String fileName = "src/main/resources/test.txt";
      c.put(fileName, "./in/");
      c.exit();
      System.out.println("done");

    } catch (Exception e) {
      System.err.println(e);
    }
  }