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());
   }
 }
Example #2
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();
    }
  }
Example #3
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();
      }
    }
  }
 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);
   }
 }
Example #5
0
 public boolean getStreams() {
   try {
     in = channel.getInputStream();
   } catch (IOException e) {
     NeptusLog.pub().error(this + " :: Could not getInputStream.", e);
     execResponse += "\n :: Could not getInputStream. " + e.getMessage();
     return false;
   }
   try {
     out = channel.getOutputStream();
   } catch (IOException e) {
     NeptusLog.pub().error(this + " :: Could not getOutputStream.", e);
     execResponse += "\n :: Could not getOutputStream. " + e.getMessage();
     return false;
   }
   ((ChannelExec) channel).setErrStream(System.err);
   return true;
 }
  /*
   * (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");
    }
  }
Example #8
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;
   }
 }
Example #9
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");
  }
Example #10
0
  public void transfer(String fromFile, String toFile) throws IOException, JSchException {
    FileInputStream fis = null;
    String rfile = toFile;
    String lfile = fromFile;
    String command = "scp -t " + rfile; // $NON-NLS-1$
    try {
      Channel channel = session.openChannel("exec"); // $NON-NLS-1$
      ((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.out.println("err"); // $NON-NLS-1$
      }

      // send "C0644 filesize filename", where filename should not include
      // '/'
      long filesize = (new File(lfile)).length();
      command = "C0644 " + filesize + " "; // $NON-NLS-1$ //$NON-NLS-2$
      if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
      } else {
        command += lfile;
      }
      command += "\n"; // $NON-NLS-1$

      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        System.out.println("err"); // $NON-NLS-1$
      }

      // 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);
      }
      fis.close();
      fis = null;
      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      if (checkAck(in) != 0) {
        System.out.println("err"); // $NON-NLS-1$
      }
      out.close();

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

    } catch (IOException e) {
      if (fis != null) fis.close();
      throw e;
    }
  }
  public static boolean fileTransfer(
      String ifile[],
      String rfile[],
      Session session,
      String inFile1,
      String inFile2,
      String testName) {
    FileInputStream fis = null;
    Properties prop = null;
    String command = "";
    OutputStream out = null;
    InputStream in = null;
    Vector filelist = null;
    Channel chFileProcess = null;
    ChannelSftp channelSftp = null;
    ChannelSftp channelSftpcomp = null;
    long filesize = 0;
    String sftpMonitor = testName + "_SFTP_MONITOR";
    String sftpCompleted = testName + "_SFTP_COMPLETED";
    boolean isFileProcessed = false;
    prop = PropertyReader.getPropeties("OMS");
    sftpMonitor = prop.getProperty(sftpMonitor);
    sftpCompleted = prop.getProperty(sftpCompleted);
    try {
      System.out.println("Connection to the Remote Server succeeded");
      System.out.println("------------------------------------------------------");
      Channel chFilesTransfer = null;
      // session.connect();
      for (int iloop = 0; iloop < ifile.length; iloop++) {
        boolean ptimestamp = true;
        command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile[iloop];
        chFilesTransfer = session.openChannel("exec");
        ((ChannelExec) chFilesTransfer).setCommand(command);
        // get I/O streams for remote scp
        out = chFilesTransfer.getOutputStream();
        in = chFilesTransfer.getInputStream();
        chFilesTransfer.connect();
        System.out.println("Channel opened for file transfer of " + ifile[iloop]);
        System.out.println("------------------------------------------------------");
        if (checkAck(in) != 0) {
          System.exit(0);
        }
        File _lfile = new File(ifile[iloop]);
        if (ptimestamp) {
          command = "T " + (_lfile.lastModified() / 1000) + " 0";
          command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
          out.write(command.getBytes());
          out.flush();
          if (checkAck(in) != 0) {
            System.exit(0);
          }
        }
        filesize = _lfile.length();
        command = "C0644 " + filesize + " ";
        if (ifile[iloop].lastIndexOf('/') > 0) {
          command += ifile[iloop].substring(ifile[iloop].lastIndexOf('/') + 1);
        } else {
          command += ifile[iloop];
        }
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
        fis = new FileInputStream(ifile[iloop]);
        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();
        out.close();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
      }
      chFilesTransfer.disconnect();
      try {
        Thread.sleep(10000);
        chFileProcess = session.openChannel("sftp");
        chFileProcess.connect();
        channelSftp = (ChannelSftp) chFileProcess;
        channelSftp.cd(sftpMonitor);
        filelist = channelSftp.ls(sftpMonitor);
        Thread.sleep(10000);
        for (int i = 0; i < filelist.size(); i++) {
          // System.out.println("filelist.get(i).toString()---------->"+filelist.get(i).toString());
          Thread.sleep(10000);
          if (filelist.get(i).toString().contains(inFile1)) break;
        }
        channelSftpcomp = (ChannelSftp) chFileProcess;
        channelSftpcomp.cd(sftpCompleted);
        Thread.sleep(50000);
        Vector<ChannelSftp.LsEntry> filelistcomp =
            channelSftp.ls(sftpCompleted); // Thread.sleep(5000);
        StringBuffer sb = new StringBuffer(inFile1);

        for (int icounter = 0; icounter < 10; icounter++) {
          // System.out.println("inside loop");
          // System.out.println("filelist.get(icounter).toString()------>"+filelistcomp.get(icounter).toString());
          for (ChannelSftp.LsEntry filelist1 : filelistcomp) {
            if (!filelist1.getAttrs().isDir()) {
              // String s=filelist1.getFilename();
              // s.contains("test");
              // System.out.println("filelist1.getFilename()--------->"+filelist1.getFilename());
              if (filelist1.getFilename().contains(sb)) {
                isFileProcessed = true;
                break;
              } else {
                Thread.sleep(8000);
              }
            }
            if (isFileProcessed) {
              break;
            }
          }
        }
        if (isFileProcessed) {
          System.out.println("-------------------------------------------");
          System.out.println("File is processes and move to completed folder");
        } else {
          System.out.println("-------------------------------------------");
          System.out.println("File is not processes");
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
      // System.exit(0);
    }
    return isFileProcessed;
  }
Example #12
0
  public static void main(String[] arg) {
    if (arg.length != 2) {
      System.err.println("usage: java ScpFrom user@remotehost:file1 file2");
      System.exit(-1);
    }

    FileOutputStream fos = null;
    try {

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

      String prefix = null;
      if (new File(lfile).isDirectory()) {
        prefix = lfile + File.separator;
      }

      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();

      // exec 'scp -f rfile' remotely
      String command = "scp -f " + 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();

      byte[] buf = new byte[1024];

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

      while (true) {
        int c = checkAck(in);
        if (c != 'C') {
          break;
        }

        // read '0644 '
        in.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
          if (in.read(buf, 0, 1) < 0) {
            // error
            break;
          }
          if (buf[0] == ' ') break;
          filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
          in.read(buf, i, 1);
          if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
          }
        }

        // System.out.println("filesize="+filesize+", file="+file);

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

        // read a content of lfile
        fos = new FileOutputStream(prefix == null ? lfile : prefix + file);
        int foo;
        while (true) {
          if (buf.length < filesize) foo = buf.length;
          else foo = (int) filesize;
          foo = in.read(buf, 0, foo);
          if (foo < 0) {
            // error
            break;
          }
          fos.write(buf, 0, foo);
          filesize -= foo;
          if (filesize == 0L) break;
        }
        fos.close();
        fos = null;

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

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

      session.disconnect();

      System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fos != null) fos.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) {
      }
    }
  }
  private static void copyRemoteFile(Session session, String command, String fileLocation)
      throws JSchException, IOException {
    FileOutputStream fos = null;
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    OutputStream out = channel.getOutputStream();
    InputStream in = channel.getInputStream();
    channel.connect();
    bufs = new byte[Constants.ONE_ZERO_TWO_FOUR];

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

    while (true) {
      int c = checkAck(in);
      if (c != 'C') {
        break;
      }

      // read '0644 '
      in.read(bufs, 0, Constants.FIVE);

      long filesize = 0L;
      while (true) {
        if (in.read(bufs, 0, 1) < 0) {
          // error
          break;
        }
        if (bufs[0] == ' ') {
          break;
        }
        filesize = filesize * Constants.TENL + (long) (bufs[0] - '0');
      }

      String file = null;
      for (int i = 0; ; i++) {
        in.read(bufs, i, 1);
        if (bufs[i] == (byte) Constants.ZERO_CROSS_ZERO_A) {
          file = new String(bufs, 0, i);
          break;
        }
      }

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

      // read a content of file
      fos = new FileOutputStream(fileLocation == null ? fileLocation : fileLocation + file);
      filesize = readFile(fos, in, filesize);
      fos.close();
      if (checkAck(in) != 0) {
        System.exit(0);
      }
      // send '\0'
      bufs[0] = 0;
      out.write(bufs, 0, 1);
      out.flush();
    }
  }
  public void uploadFile(
      String pathLocalFile, String remoteFile, String host, String user, String pass) {
    System.out.println("++++++Start Upload File");
    FileInputStream fis = null;
    try {
      // String lfile =
      // "C:\\Users\\Dee\\AISTunerconfig\\Tuner\\var\\temp\\smf.E00.x.0";
      // String user = "******";
      // String host = "10.239.23.178";
      // String rfile = "/Users/test/equinox.conf/Config/smf.E00.x.0";

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

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

      boolean ptimestamp = true;

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

      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 (pathLocalFile.lastIndexOf('/') > 0) {
        command += pathLocalFile.substring(pathLocalFile.lastIndexOf('/') + 1);
      } else {
        command += pathLocalFile;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }

      // send a content of lfile
      fis = new FileInputStream(pathLocalFile);
      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.out.println("++++++Upload File Suscess");
      // System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
    }
  }
Example #16
0
  /*
   * (non-Javadoc)
   *
   * @see com.sysfera.godiet.Utils.RemoteAccess#copy(java.io.File,
   * java.lang.String)
   */
  @Override
  public void copy(ConfigurationFile localFile, String remotePath, Path path)
      throws RemoteAccessException {
    InputStream fis = null;

    Channel channel = null;
    try {
      channel = channelManager.getExecChannel(path);
      // exec 'scp -t rfile' remotely
      String command = "scp -p -t " + remotePath + "/";
      ((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) {
        throw new RemoteAccessException("Unable to scp");
        // on : " + user+ "@" + host + ":" + port);
      }

      // send "C0644 filesize filename", where filename should not include
      // '/'
      long filesize = localFile.getContents().getBytes().length;
      String localFileName = localFile.getAbsolutePath();
      command = "C0644 " + filesize + " ";
      if (localFileName.lastIndexOf('/') > 0) {
        command += localFileName.substring(localFileName.lastIndexOf('/') + 1);
      } else {
        command += localFileName;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        throw new RemoteAccessException("Unable to scp ");
        // + user + "@" + host + ":" + port + "Command: " + command);
      }

      // send a content of lfile
      fis = new ByteArrayInputStream(localFile.getContents().getBytes());
      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) {
        throw new RemoteAccessException("Error when close connection ");
        // + user +"@" + host + ":" + port + "Command: " + command);
      }
      out.close();
      channel.disconnect();
    } catch (Exception e) {
      throw new RemoteAccessException("Unable to scp"); // on :
      // " + user + "@"
      // + host + ":" + port, e);
    } finally {
      try {
        if (channel != null) {
          channel.disconnect();
        }
        try {
          if (fis != null) {
            fis.close();
          }
        } catch (Exception ee) {
        }
      } catch (Exception e) {
        log.error("SSH disconnect error", e);
      }
    }
  }
  private static void scpOutputFile(
      String host,
      String user,
      String password,
      String remoteOutputFilePath,
      String localOutputFilePath) {
    FileOutputStream fos = null;
    try {
      String rfile = remoteOutputFilePath;
      String lfile = localOutputFilePath;

      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();

      // exec 'scp -f rfile' remotely
      String command = "scp -f " + 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();

      byte[] buf = new byte[1024];

      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      while (true) {
        int c = checkAck(in);
        if (c != 'C') {
          break;
        }

        // read '0644 '
        in.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
          if (in.read(buf, 0, 1) < 0) {
            // error
            break;
          }
          if (buf[0] == ' ') break;
          filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
          in.read(buf, i, 1);
          if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
          }
        }

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

        // read a content of lfile
        fos = new FileOutputStream(lfile);
        int foo;
        while (true) {
          if (buf.length < filesize) foo = buf.length;
          else foo = (int) filesize;
          foo = in.read(buf, 0, foo);
          if (foo < 0) {
            // error
            break;
          }
          fos.write(buf, 0, foo);
          filesize -= foo;
          if (filesize == 0L) break;
        }
        fos.close();
        fos = null;

        if (checkAck(in) != 0) {
          break;
        }

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

    } catch (Exception e) {
      e.printStackTrace();
      try {
        if (fos != null) fos.close();
      } catch (Exception ee) {
      }
    }
  }
Example #18
0
  /**
   * copy a file from remote host to local
   *
   * @param rfile
   * @param lfile
   */
  public String scpFrom(String rfile, String lfile) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    FileOutputStream fos = null;
    // When get a rfile which with regular expression, to save the file with the same name as it get
    // from the remote server[add by phoebe]
    String completeLfile = lfile;

    try {
      // exec 'scp -f rfile' remotely
      String command = "scp -f " + 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();

      byte[] buf = new byte[1024];

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

      while (true) {
        int c = checkAck(in);
        if (c != 'C') {
          break;
        }

        // read '0644 '
        in.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
          if (in.read(buf, 0, 1) < 0) {
            // error
            break;
          }
          if (buf[0] == ' ') break;
          filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
          in.read(buf, i, 1);
          if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
          }
        }

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

        // When get a rfile which with regular expression, to save the file with the same name as it
        // get from the remote server[add by phoebe]
        if (completeLfile.contains("*")) {
          completeLfile = completeLfile.substring(0, completeLfile.lastIndexOf("/")) + "/" + file;
        }

        // read a content of lfile
        fos = new FileOutputStream(completeLfile);
        int foo;
        while (true) {
          if (buf.length < filesize) foo = buf.length;
          else foo = (int) filesize;
          foo = in.read(buf, 0, foo);
          if (foo < 0) {
            // error
            break;
          }
          fos.write(buf, 0, foo);
          filesize -= foo;
          if (filesize == 0L) break;
        }
        fos.close();
        fos = null;

        if (checkAck(in) != 0) {
          throw new ActionFailedException("Failed to get Ack, Copy may fail!");
        }

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

    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
    return completeLfile;
  }
  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) {
      }
    }
  }
Example #20
0
  /**
   * execute the given command in the remote host
   *
   * @param command
   * @return - command output in the remote host
   */
  public String exec(String command) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    StringBuffer data = new StringBuffer();
    OutputStream out = null;
    InputStream in = null;
    try {
      Channel channel;

      boolean channel_connected = false;
      int count = 0;
      while (!channel_connected) {

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

          out = channel.getOutputStream();
          in = channel.getInputStream();
          channel.connect();
          channel_connected = true;
        } catch (Exception e) {
          count++;
          String msg = e.getMessage();
          if (count < 5) {
            AutomationLogger.getInstance()
                .warn(
                    "Failed to connect to SSH server due to "
                        + msg
                        + ". Will try again in 1 second");
            if (msg.startsWith("session is down")) {
              AutomationLogger.getInstance().info("Try to re-connect session");
              connect();
            }
            Timer.sleep(1000);
          } else {
            throw new ActionFailedException("Failed to connect to SSH server due to " + e);
          }
        }
      }

      byte[] buf = new byte[1024];

      // read
      count = 0;
      while ((count = in.read(buf)) > 0) {
        data.append(new String(buf, 0, count));
      }

    } catch (Exception e) {
      AutomationLogger.getInstance().warn(e);
    } finally {
      try {
        in.close();
      } catch (Exception e) {
      }
      try {
        out.close();
      } catch (Exception e) {
      }

      if (channel != null) {
        channel.disconnect();
      }
    }
    return data.toString();
  }