private static String[] queryUserAndHost(String promptSuffix, String useThis) {
   if (useThis == null || !useThis.contains("@")) {
     useThis =
         JOptionPane.showInputDialog(
             "Enter username@hostname for " + promptSuffix,
             System.getProperty("user.name") + "@localhost");
   }
   if (useThis == null) {
     throw new NoSuchElementException("User does not want!");
   }
   return useThis.split("@");
 }
Beispiel #2
0
  public byte[] uncompress(byte[] buffer, int start, int[] length) {
    int inflated_end = 0;

    stream.next_in = buffer;
    stream.next_in_index = start;
    stream.avail_in = length[0];

    while (true) {
      stream.next_out = tmpbuf;
      stream.next_out_index = 0;
      stream.avail_out = BUF_SIZE;
      int status = stream.inflate(JZlib.Z_PARTIAL_FLUSH);
      switch (status) {
        case JZlib.Z_OK:
          if (inflated_buf.length < inflated_end + BUF_SIZE - stream.avail_out) {
            byte[] foo = new byte[inflated_end + BUF_SIZE - stream.avail_out];
            System.arraycopy(inflated_buf, 0, foo, 0, inflated_end);
            inflated_buf = foo;
          }
          System.arraycopy(tmpbuf, 0, inflated_buf, inflated_end, BUF_SIZE - stream.avail_out);
          inflated_end += (BUF_SIZE - stream.avail_out);
          length[0] = inflated_end;
          break;
        case JZlib.Z_BUF_ERROR:
          if (inflated_end > buffer.length - start) {
            byte[] foo = new byte[inflated_end + start];
            System.arraycopy(buffer, 0, foo, 0, start);
            System.arraycopy(inflated_buf, 0, foo, start, inflated_end);
            buffer = foo;
          } else {
            System.arraycopy(inflated_buf, 0, buffer, start, inflated_end);
          }
          length[0] = inflated_end;
          return buffer;
        default:
          System.err.println("uncompress: inflate returnd " + status);
          return null;
      }
    }
  }
  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);
    }
  }
  public static void main(String[] arg) {

    int lport;
    String rhost;
    int rport;

    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 foo = JOptionPane.showInputDialog("Enter -L port:host:hostport", "port:host:hostport");
      lport = Integer.parseInt(foo.substring(0, foo.indexOf(':')));
      foo = foo.substring(foo.indexOf(':') + 1);
      rhost = foo.substring(0, foo.indexOf(':'));
      rport = Integer.parseInt(foo.substring(foo.indexOf(':') + 1));

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

      session.connect();

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

      int assinged_port = session.setPortForwardingL(lport, rhost, rport);
      System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Beispiel #5
0
  public int compress(byte[] buf, int start, int len) {
    stream.next_in = buf;
    stream.next_in_index = start;
    stream.avail_in = len - start;
    int status;
    int outputlen = start;

    do {
      stream.next_out = tmpbuf;
      stream.next_out_index = 0;
      stream.avail_out = BUF_SIZE;
      status = stream.deflate(JZlib.Z_PARTIAL_FLUSH);
      switch (status) {
        case JZlib.Z_OK:
          System.arraycopy(tmpbuf, 0, buf, outputlen, BUF_SIZE - stream.avail_out);
          outputlen += (BUF_SIZE - stream.avail_out);
          break;
        default:
          System.err.println("compress: deflate returnd " + status);
      }
    } while (stream.avail_out == 0);
    return outputlen;
  }
  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) {
      }
    }
  }
  /**
   * Creates a SSH Session with a remote machine and tries to login according to the details
   * specified by Contact An appropriate message is shown to the end user in case the login fails
   *
   * @param sshContact ID of SSH Contact
   * @throws JSchException if a JSch is unable to create a SSH Session with the remote machine
   * @throws InterruptedException if the thread is interrupted before session connected or is timed
   *     out
   * @throws OperationFailedException if not of above reasons :-)
   */
  public void createSSHSessionAndLogin(ContactSSH sshContact)
      throws JSchException, OperationFailedException, InterruptedException {
    logger.info("Creating a new SSH Session to " + sshContact.getHostName());

    // creating a new JSch Stack identifier for contact
    JSch jsch = new JSch();

    String knownHosts = (String) accountID.getAccountProperties().get("KNOWN_HOSTS_FILE");

    if (!knownHosts.equals("Optional")) jsch.setKnownHosts(knownHosts);

    String identitiyKey = (String) accountID.getAccountProperties().get("IDENTITY_FILE");

    String userName = sshContact.getUserName();

    // use the name of system user if the contact has not supplied SSH
    // details
    if (userName.equals("")) userName = System.getProperty("user.name");

    if (!identitiyKey.equals("Optional")) jsch.addIdentity(identitiyKey);

    // creating a new session for the contact
    Session session =
        jsch.getSession(
            userName, sshContact.getHostName(), sshContact.getSSHConfigurationForm().getPort());

    /**
     * Creating and associating User Info with the session User Info passes authentication from
     * sshContact to SSH Stack
     */
    SSHUserInfo sshUserInfo = new SSHUserInfo(sshContact);

    session.setUserInfo(sshUserInfo);

    /** initializing the session */
    session.connect(connectionTimeout);

    int count = 0;

    // wait for session to get connected
    while (!session.isConnected() && count <= 30000) {
      Thread.sleep(1000);
      count += 1000;
      logger.trace("SSH:" + sshContact.getHostName() + ": Sleep zzz .. ");
    }

    // if timeout have exceeded
    if (count > 30000) {
      sshContact.setSSHSession(null);
      JOptionPane.showMessageDialog(
          null, "SSH Connection attempt to " + sshContact.getHostName() + " timed out");

      // error codes are not defined yet
      throw new OperationFailedException(
          "SSH Connection attempt to " + sshContact.getHostName() + " timed out", 2);
    }

    sshContact.setJSch(jsch);
    sshContact.setSSHSession(session);

    logger.info("A new SSH Session to " + sshContact.getHostName() + " Created");
  }
  /**
   * This will not reuse any session, it will create the session and close it at the end
   *
   * @param commandInfo Encapsulated information about command. E.g :- executable name parameters
   *     etc ...
   * @param serverInfo The SSHing server information.
   * @param authenticationInfo Security data needs to be communicated with remote server.
   * @param commandOutput The output of the command.
   * @param configReader configuration required for ssh/gshissh connection
   * @throws SSHApiException throw exception when error occurs
   */
  public static void executeCommand(
      CommandInfo commandInfo,
      ServerInfo serverInfo,
      AuthenticationInfo authenticationInfo,
      CommandOutput commandOutput,
      ConfigReader configReader)
      throws SSHApiException {

    if (authenticationInfo instanceof GSIAuthenticationInfo) {
      System.setProperty(
          X509_CERT_DIR,
          (String)
              ((GSIAuthenticationInfo) authenticationInfo).getProperties().get("X509_CERT_DIR"));
    }

    JSch jsch = new ExtendedJSch();

    log.debug(
        "Connecting to server - "
            + serverInfo.getHost()
            + ":"
            + serverInfo.getPort()
            + " with user name - "
            + serverInfo.getUserName());

    Session session;

    try {
      session =
          jsch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getPort());
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while creating SSH session."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    java.util.Properties config = configReader.getProperties();
    session.setConfig(config);

    // =============================================================
    // Handling vanilla SSH pieces
    // =============================================================
    if (authenticationInfo instanceof SSHPasswordAuthentication) {
      String password =
          ((SSHPasswordAuthentication) authenticationInfo)
              .getPassword(serverInfo.getUserName(), serverInfo.getHost());

      session.setUserInfo(new SSHAPIUIKeyboardInteractive(password));

      // TODO figure out why we need to set password to session
      session.setPassword(password);

    } else if (authenticationInfo instanceof SSHPublicKeyFileAuthentication) {
      SSHPublicKeyFileAuthentication sshPublicKeyFileAuthentication =
          (SSHPublicKeyFileAuthentication) authenticationInfo;

      String privateKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The private key file for vanilla SSH " + privateKeyFile);

      String publicKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The public key file for vanilla SSH " + publicKeyFile);

      Identity identityFile;

      try {
        identityFile = GSISSHIdentityFile.newInstance(privateKeyFile, null, jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using files. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName()
                + " private key file - "
                + privateKeyFile
                + ", public key file - "
                + publicKeyFile,
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);

    } else if (authenticationInfo instanceof SSHPublicKeyAuthentication) {

      SSHPublicKeyAuthentication sshPublicKeyAuthentication =
          (SSHPublicKeyAuthentication) authenticationInfo;

      Identity identityFile;

      try {
        String name = serverInfo.getUserName() + "_" + serverInfo.getHost();
        identityFile =
            GSISSHIdentityFile.newInstance(
                name,
                sshPublicKeyAuthentication.getPrivateKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                sshPublicKeyAuthentication.getPublicKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using byte arrays. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName(),
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);
    }

    // Not a good way, but we dont have any choice
    if (session instanceof ExtendedSession) {
      if (authenticationInfo instanceof GSIAuthenticationInfo) {
        ((ExtendedSession) session)
            .setAuthenticationInfo((GSIAuthenticationInfo) authenticationInfo);
      }
    }

    try {
      session.connect();
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while connecting to server."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    String command = commandInfo.getCommand();

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

      throw new SSHApiException(
          "Unable to execute command - "
              + command
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          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
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    commandOutput.onOutput(channel);

    channel.disconnect();
    session.disconnect();
  }
Beispiel #9
0
    @Override
    public Integer call() {
      int exitstatus = Integer.MAX_VALUE;
      Boolean useIdentityFile = null;
      String credentials = null;
      String userName = nodeCredentials.getUsername();

      if (nodeCredentials instanceof LoginCredentialsPassword) {
        useIdentityFile = false;
        credentials = ((LoginCredentialsPassword) nodeCredentials).getPassword();
      } else if (nodeCredentials instanceof LoginCredentialsPrivateKey) {
        useIdentityFile = true;
        credentials = ((LoginCredentialsPrivateKey) nodeCredentials).getKey().getKeyPath();
      }

      ChannelExec c = null;
      SshClient ssh = null;

      try {
        ssh = new SshClient();
        ssh.createSession(nodeAddress, userName, false);

        log.info("connecting with username: "******"connecting using identity file: " + credentials);
        } else {
          log.info("connecting using password: "******"executing command: " + command);
        c.connect();

        new Thread(
                new Runnable() {
                  public void run() {
                    String line;
                    BufferedReader bufferedInputReader =
                        new BufferedReader(new InputStreamReader(is));
                    try {
                      while ((line = bufferedInputReader.readLine()) != null) {
                        output.append(line);
                        synchronized (timeStamp) {
                          timeStamp = System.currentTimeMillis();
                        }
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                })
            .start();

        new Thread(
                new Runnable() {
                  public void run() {
                    String line;
                    BufferedReader bufferedErrorReader =
                        new BufferedReader(new InputStreamReader(err));
                    try {
                      while ((line = bufferedErrorReader.readLine()) != null) {
                        error.append(line);
                        synchronized (timeStamp) {
                          timeStamp = System.currentTimeMillis();
                        }
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                })
            .start();

        while (!c.isClosed()) {
          synchronized (this.timeStamp) {
            if (System.currentTimeMillis() - this.timeStamp > MAXIMUM_WAITING_TIME_INACTIVITY) {
              log.warn("command execution seems inactive, canceling!");
              break;
            }
          }
          log.info("waiting for command to finish.");
          try {
            Thread.sleep(SshClient.DEFAULT_WAITING_TIME_PER_CYCLE);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        exitstatus = c.getExitStatus();

      } catch (JSchException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (c != null) {
          c.disconnect();
        }

        if (ssh != null) {
          try {
            ssh.disconnectSession();
          } catch (JSchException e) {
            e.printStackTrace();
          }
        }
      }
      return exitstatus;
    }
public class ScpRetrieveFileTransfer extends AbstractRetrieveFileTransfer
    implements IScpFileTransfer {

  private static final String SCP_COMMAND =
      System.getProperty(
          "org.eclipse.ecf.filetransfer.scp.retrieve.scpcommand", "scp -f "); // $NON-NLS-1$
  private static final String SCP_EXEC =
      System.getProperty(
          "org.eclipse.ecf.filetransfer.scp.retrieve.scpcommand", "exec"); // $NON-NLS-1$

  String username;

  Channel channel;

  OutputStream responseStream;

  private ScpUtil scpUtil;

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer
   * #doPause()
   */
  protected boolean doPause() {
    return false;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer
   * #doResume()
   */
  protected boolean doResume() {
    return false;
  }

  public URL getTargetURL() {
    return getRemoteFileURL();
  }

  public Map getOptions() {
    return options;
  }

  /*
   * (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);
    }
  }

  static int checkAck(InputStream in) throws IOException {
    int b = in.read();
    // b may be 0 for success,
    // 1 for error,
    // 2 for fatal error,
    // -1
    if (b == 0) return b;
    if (b == -1) return b;

    if (b == 1 || b == 2) {
      StringBuffer sb = new StringBuffer();
      int c;
      do {
        c = in.read();
        sb.append((char) c);
      } while (c != '\n');
      if (b == 1 || b == 2) { // error
        throw new IOException(
            Messages.ScpRetrieveFileTransfer_EXCEPTION_SCP_PROTOCOL + ": " + sb.toString());
      }
    }
    return b;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer
   * #handleReceivedData(byte[], int, double,
   * org.eclipse.core.runtime.IProgressMonitor)
   */
  protected void handleReceivedData(byte[] buf, int bytes, double factor, IProgressMonitor monitor)
      throws IOException {
    if (bytes == -1) {
      done = true;
    } else {
      int fileBytes = bytes;
      if ((bytesReceived + bytes) > fileLength) {
        fileBytes = (int) (fileLength - bytesReceived);
      }
      bytesReceived += fileBytes;
      localFileContents.write(buf, 0, fileBytes);
      fireTransferReceiveDataEvent();
      monitor.worked((int) Math.round(factor * fileBytes));
      if (fileBytes != bytes) {
        scpUtil.checkAck(buf[fileBytes], remoteFileContents);
        done = true;
      }
    }
  }

  private long readFileSize(InputStream ins, byte[] buf) throws IOException {
    long filesize = 0L;
    while (true) {
      if (ins.read(buf, 0, 1) < 0) {
        throw new IOException(Messages.ScpRetrieveFileTransfer_EXCEPTION_ERROR_READING_FILE);
      }
      if (buf[0] == ' ') break;
      filesize = filesize * 10L + (buf[0] - '0');
    }
    return filesize;
  }

  private String readFileName(InputStream ins, byte[] buf) throws IOException {
    String file = null;
    for (int i = 0; ; i++) {
      ins.read(buf, i, 1);
      if (buf[i] == (byte) 0x0a) {
        file = new String(buf, 0, i);
        break;
      }
    }
    return file;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.outgoing.AbstractOutgoingFileTransfer
   * #hardClose()
   */
  protected void hardClose() {
    try {
      if (remoteFileContents != null && scpUtil != null) {
        scpUtil.sendZeroToStream(responseStream);
        scpUtil.dispose();
        scpUtil = null;
        remoteFileContents = null;
        responseStream = null;
      }
    } catch (final IOException e) {
      exception = e;
    } finally {
      super.hardClose();
      channel = null;
      username = null;
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer
   * #getAdapter(java.lang.Class)
   */
  public Object getAdapter(Class adapter) {
    if (adapter == null) return null;
    if (adapter.equals(IFileTransferPausable.class)) return null;
    return super.getAdapter(adapter);
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer
   * #setupProxy(org.eclipse.ecf.core.util.Proxy)
   */
  protected void setupProxy(Proxy proxy) {
    this.proxy = proxy;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.scp.IScpFileTransfer#getConnectContext
   * ()
   */
  public IConnectContext getConnectContext() {
    return connectContext;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.scp.IScpFileTransfer#getUsername()
   */
  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.scp.IScpFileTransfer#promptPassphrase
   * ()
   */
  public boolean promptPassphrase() {
    // XXX TODO
    // return (keyFile != null);
    return false;
  }

  public Proxy getProxy() {
    return this.proxy;
  }
}
Beispiel #11
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) {
      }
    }
  }