예제 #1
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;
  }
예제 #2
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;
  }
예제 #3
0
  private void runJschTest(int port) throws Exception {
    JSchLogger.init();
    JSch sch = new JSch();
    JSch.setConfig("cipher.s2c", CRYPT_NAMES);
    JSch.setConfig("cipher.c2s", CRYPT_NAMES);
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), "localhost", port);
    s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
    s.connect();

    try {
      com.jcraft.jsch.Channel c = s.openChannel("shell");
      c.connect();

      try (OutputStream os = c.getOutputStream();
          InputStream is = c.getInputStream()) {
        String expected = "this is my command\n";
        byte[] expData = expected.getBytes(StandardCharsets.UTF_8);
        byte[] actData = new byte[expData.length + Long.SIZE /* just in case */];
        for (int i = 0; i < 10; i++) {
          os.write(expData);
          os.flush();

          int len = is.read(actData);
          String actual = new String(actData, 0, len);
          assertEquals("Mismatched command at iteration " + i, expected, actual);
        }
      } finally {
        c.disconnect();
      }
    } finally {
      s.disconnect();
    }
  }
예제 #4
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();
  }
예제 #5
0
 @Override
 public void start() throws MachineException {
   try {
     session = jsch.getSession(username, host, port);
     session.setUserInfo(user);
     // todo remember parent pid of shell to be able to kill all processes on client stop
     if (!session.isConnected()) {
       session.connect(connectionTimeout);
     }
   } catch (JSchException e) {
     throw new MachineException(
         "Ssh machine creation failed because ssh of machine is inaccessible. Error: "
             + e.getLocalizedMessage());
   }
 }
예제 #6
0
 public Session getSession() {
   Session session;
   try {
     JSch jSch = new JSch();
     session = jSch.getSession(username, host, port);
     session.setPassword(passwd);
     UserInfo userInfo = new MyUser(passwd, null);
     session.setConfig("PreferredAuthentications", "publickey,password,keyboard-interactive");
     session.setUserInfo(userInfo);
   } catch (JSchException e) {
     e.printStackTrace();
     return null;
   }
   return session;
 }
예제 #7
0
 public void push(String user, String server, File f, String to) {
   file = f;
   if (ssh == null)
     try {
       ssh = jsch.getSession(user, server, 22);
       UserInfo ui = new SSHUserInfo();
       ssh.setUserInfo(ui);
       ssh.setConfig("StrictHostKeyChecking", "no");
       ssh.setPortForwardingL(28947, "127.0.0.1", 28947);
       ssh.connect();
     } catch (JSchException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   Thread t = new Thread(this);
   t.start();
 }
예제 #8
0
  public static void main(String[] arg) {

    String xhost = "127.0.0.1";
    int xport = 0;

    try {
      JSch jsch = new JSch();

      String host = null;
      if (arg.length > 0) {
        host = arg[0];
      } else {
        host =
            JOptionPane.showInputDialog(
                "Enter username@hostname", System.getProperty("user.name") + "@localhost");
      }
      String user = host.substring(0, host.indexOf('@'));
      host = host.substring(host.indexOf('@') + 1);

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

      String display =
          JOptionPane.showInputDialog("Please enter display name", xhost + ":" + xport);
      xhost = display.substring(0, display.indexOf(':'));
      xport = Integer.parseInt(display.substring(display.indexOf(':') + 1));

      session.setX11Host(xhost);
      session.setX11Port(xport + 6000);

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

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

      channel.setXForwarding(true);

      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);

      channel.connect();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
예제 #9
0
  /**
   * Open an ssh seession.
   *
   * @return the opened session
   * @throws JSchException on error
   */
  protected Session openSession() throws JSchException {
    JSch jsch = new JSch();
    if (null != userInfo.getKeyfile()) {
      jsch.addIdentity(userInfo.getKeyfile());
    }

    if (!userInfo.getTrust() && knownHosts != null) {
      project.log("Using known hosts: " + knownHosts, Project.MSG_DEBUG);
      jsch.setKnownHosts(knownHosts);
    }

    Session session = jsch.getSession(userInfo.getName(), host, port);
    session.setUserInfo(userInfo);
    project.log("Connecting to " + host + ":" + port, Project.MSG_VERBOSE);
    session.connect();
    return session;
  }
예제 #10
0
  /**
   * @param userName the name of the account being logged into.
   * @param hostName this should be the host. I found values like <code>foo.com</code> work, where
   *     <code>http://foo.com</code> don't.
   * @param userPassword if you are not using key based authentication, then you are likely being
   *     prompted for a password each time you login. This is that password. It is <em>not</em> the
   *     passphrase for the private key!
   * @param port the default is 22, and if you specify N<0 for this value we'll default it to 22
   * @param knownHostsFile this is the known hosts file. If you don't specify it, jsch does some
   *     magic to work without your specification. If you have it in a non well-known location,
   *     however, this property is for you. An example: <code>/home/user/.ssh/known_hosts</code>
   * @param knownHostsInputStream this is the known hosts file. If you don't specify it, jsch does
   *     some magic to work without your specification. If you have it in a non well-known location,
   *     however, this property is for you. An example: <code>/home/user/.ssh/known_hosts</code>.
   *     Note that you may specify this <em>or</em> the #knownHostsFile - not both!
   * @param privateKey this is usually used when you want passwordless automation (obviously, for
   *     this integration it's useless since this lets you specify a password once, anyway, but
   *     still good to have if required). This file might be ~/.ssh/id_dsa, or a <code>.pem</code>
   *     for your remote server (for example, on EC2)
   * @param pvKeyPassPhrase sometimes, to be extra secure, the private key itself is extra
   *     encrypted. In order to surmount that, we need the private key passphrase. Specify that
   *     here.
   * @throws Exception thrown if any of a myriad of scenarios plays out
   */
  public SftpSession(
      String userName,
      String hostName,
      String userPassword,
      int port,
      String knownHostsFile,
      InputStream knownHostsInputStream,
      String privateKey,
      String pvKeyPassPhrase)
      throws Exception {
    JSch jSch = new JSch();

    if (port <= 0) {
      port = 22;
    }

    this.privateKey = privateKey;
    this.privateKeyPassphrase = pvKeyPassPhrase;

    if (!StringUtils.isEmpty(knownHostsFile)) {
      jSch.setKnownHosts(knownHostsFile);
    } else if (null != knownHostsInputStream) {
      jSch.setKnownHosts(knownHostsInputStream);
    }

    // private key
    if (!StringUtils.isEmpty(this.privateKey)) {
      if (!StringUtils.isEmpty(privateKeyPassphrase)) {
        jSch.addIdentity(this.privateKey, privateKeyPassphrase);
      } else {
        jSch.addIdentity(this.privateKey);
      }
    }

    session = jSch.getSession(userName, hostName, port);

    if (!StringUtils.isEmpty(userPassword)) {
      session.setPassword(userPassword);
    }

    userInfo = new OptimisticUserInfoImpl(userPassword);
    session.setUserInfo(userInfo);
    session.connect();
    channel = (ChannelSftp) session.openChannel("sftp");
  }
  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);
    }
  }
  /** Connect the socket and open the connection. */
  public void connect(String host, int port, String username, String password) throws IOException {
    if (debug > 0) System.err.println("Wrapper: connect(" + host + "," + port + ")");

    this.host = host;
    this.port = port;
    this.username = username;
    this.password = password;

    if (isClosed()) {
      try {
        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setUserInfo(defaultUserInfo);
        session.connect();
        System.out.println("connected");
      } catch (JSchException e) {
        e.printStackTrace();
        throw new IOException("connect or authenticate failed");
      }
    }
  }
  @Override
  public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
    if (!(dir instanceof SFTPPath)) {
      throw new IllegalArgumentException(dir.toString());
    }

    SFTPHost sftpHost = (SFTPHost) dir.getFileSystem();

    String username = sftpHost.getUserName();
    String host = sftpHost.getHost();
    int port = sftpHost.getPort();
    Session session;
    try {
      session = jsch.getSession(username, host, port);
      UserInfo userinfo = new SFTPUserInfo(sftpHost.getPassword());
      session.setUserInfo(userinfo);
      session.connect();

      ChannelSftp sftp = (ChannelSftp) session.openChannel(SFTP);

      sftp.connect();

      SFTPPath sftpPath = (SFTPPath) dir;
      String dirString = sftpPath.getPathString();
      try {
        sftp.mkdir(dirString);
      } catch (SftpException e) {
        throw new IOException(dirString, e);
      }

      sftp.quit();

      session.disconnect();
      // throw new UnsupportedOperationException();
    } catch (JSchException e) {
      throw new FileSystemException(e.getMessage());
    }
  }
예제 #14
0
  private static void testUploadStp() throws JSchException, SftpException {
    Channel channel = null;
    Session session = null;

    try {
      JSch jsch = new JSch();

      // jsch.setKnownHosts("/home/foo/.ssh/known_hosts");

      String user = "******";
      String host = "10.238.226.75";

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

      String passwd = "sdpuser";
      session.setPassword(passwd);

      UserInfo ui =
          new MyUserInfo() {
            public void showMessage(String message) {
              //	          JOptionPane.showMessageDialog(null, message);
            }

            public boolean promptYesNo(String message) {
              //	          Object[] options={ "yes", "no" };
              //	          int foo=JOptionPane.showOptionDialog(null,
              //	                                               message,
              //	                                               "Warning",
              //	                                               JOptionPane.DEFAULT_OPTION,
              //	                                               JOptionPane.WARNING_MESSAGE,
              //	                                               null, options, options[0]);
              return true;
            }

            // If password is not given before the invocation of Session#connect(),
            // implement also following methods,
            //   * UserInfo#getPassword(),
            //   * UserInfo#promptPassword(String message) and
            //   * UIKeyboardInteractive#promptKeyboardInteractive()

          };

      session.setUserInfo(ui);

      // It must not be recommended, but if you want to skip host-key check,
      // invoke following,
      // session.setConfig("StrictHostKeyChecking", "no");

      // session.connect();
      session.connect(30000); // making a connection with timeout.

      channel = session.openChannel("sftp");

      channel.connect(3 * 1000);

      ChannelSftp sftp = (ChannelSftp) channel;

      sftp.cd("/var/opt/fds/logs");
      File f = new File("D:/Doneeeeeeeee.java");
      FileInputStream uploadStream = new FileInputStream(f);
      sftp.put(uploadStream, f.getName());

      System.out.println("Done :) ");
      //		    System.out.println(sftp.getHome());
      //		    for (Object o : sftp.ls("")) {
      //		        System.out.println(((ChannelSftp.LsEntry)o).getFilename());
      //		    }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      //	      Session session=jsch.getSession("usersdp","10.238.226.75",22);

      channel.disconnect();
      session.disconnect();
    }
  }
예제 #15
0
  public void openConnectionInternal() throws AuthenticationException {
    if (authenticationInfo == null) {
      authenticationInfo = new AuthenticationInfo();
    }

    if (!interactive) {
      uIKeyboardInteractive = null;
      setInteractiveUserInfo(new NullInteractiveUserInfo());
    }

    JSch sch = new JSch();

    File privateKey;
    try {
      privateKey = ScpHelper.getPrivateKey(authenticationInfo);
    } catch (FileNotFoundException e) {
      throw new AuthenticationException(e.getMessage());
    }

    try {
      Connector connector = ConnectorFactory.getDefault().createConnector();
      if (connector != null) {
        IdentityRepository repo = new RemoteIdentityRepository(connector);
        sch.setIdentityRepository(repo);
      }
    } catch (AgentProxyException e) {
      fireSessionDebug("Unable to connect to agent: " + e.toString());
    }

    if (privateKey != null && privateKey.exists()) {
      fireSessionDebug("Using private key: " + privateKey);
      try {
        sch.addIdentity(privateKey.getAbsolutePath(), authenticationInfo.getPassphrase());
      } catch (JSchException e) {
        throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e);
      }
    }

    String host = getRepository().getHost();
    int port =
        repository.getPort() == WagonConstants.UNKNOWN_PORT
            ? ScpHelper.DEFAULT_SSH_PORT
            : repository.getPort();
    try {
      String userName = authenticationInfo.getUserName();
      if (userName == null) {
        userName = System.getProperty("user.name");
      }
      session = sch.getSession(userName, host, port);
      session.setTimeout(getTimeout());
    } catch (JSchException e) {
      throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e);
    }

    Proxy proxy = null;
    ProxyInfo proxyInfo = getProxyInfo(ProxyInfo.PROXY_SOCKS5, getRepository().getHost());
    if (proxyInfo != null && proxyInfo.getHost() != null) {
      proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort());
      ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
    } else {
      proxyInfo = getProxyInfo(ProxyInfo.PROXY_HTTP, getRepository().getHost());
      if (proxyInfo != null && proxyInfo.getHost() != null) {
        proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort());
        ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
      } else {
        // Backwards compatibility
        proxyInfo = getProxyInfo(getRepository().getProtocol(), getRepository().getHost());
        if (proxyInfo != null && proxyInfo.getHost() != null) {
          // if port == 1080 we will use SOCKS5 Proxy, otherwise will use HTTP Proxy
          if (proxyInfo.getPort() == SOCKS5_PROXY_PORT) {
            proxy = new ProxySOCKS5(proxyInfo.getHost(), proxyInfo.getPort());
            ((ProxySOCKS5) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
          } else {
            proxy = new ProxyHTTP(proxyInfo.getHost(), proxyInfo.getPort());
            ((ProxyHTTP) proxy).setUserPasswd(proxyInfo.getUserName(), proxyInfo.getPassword());
          }
        }
      }
    }
    session.setProxy(proxy);

    // username and password will be given via UserInfo interface.
    UserInfo ui = new WagonUserInfo(authenticationInfo, getInteractiveUserInfo());

    if (uIKeyboardInteractive != null) {
      ui = new UserInfoUIKeyboardInteractiveProxy(ui, uIKeyboardInteractive);
    }

    Properties config = new Properties();
    if (getKnownHostsProvider() != null) {
      try {
        String contents = getKnownHostsProvider().getContents();
        if (contents != null) {
          sch.setKnownHosts(new StringInputStream(contents));
        }
      } catch (JSchException e) {
        // continue without known_hosts
      }
      config.setProperty("StrictHostKeyChecking", getKnownHostsProvider().getHostKeyChecking());
    }

    if (authenticationInfo.getPassword() != null) {
      config.setProperty(
          "PreferredAuthentications", "gssapi-with-mic,publickey,password,keyboard-interactive");
    }

    config.setProperty("BatchMode", interactive ? "no" : "yes");

    session.setConfig(config);

    session.setUserInfo(ui);

    StringWriter stringWriter = new StringWriter();
    try {
      session.connect();

      if (getKnownHostsProvider() != null) {
        PrintWriter w = new PrintWriter(stringWriter);

        HostKeyRepository hkr = sch.getHostKeyRepository();
        HostKey[] keys = hkr.getHostKey();

        for (int i = 0; keys != null && i < keys.length; i++) {
          HostKey key = keys[i];
          w.println(key.getHost() + " " + key.getType() + " " + key.getKey());
        }
      }
    } catch (JSchException e) {
      if (e.getMessage().startsWith("UnknownHostKey:")
          || e.getMessage().startsWith("reject HostKey:")) {
        throw new UnknownHostException(host, e);
      } else if (e.getMessage().contains("HostKey has been changed")) {
        throw new KnownHostChangedException(host, e);
      } else {
        throw new AuthenticationException("Cannot connect. Reason: " + e.getMessage(), e);
      }
    }

    try {
      getKnownHostsProvider().storeKnownHosts(stringWriter.toString());
    } catch (IOException e) {
      closeConnection();

      throw new AuthenticationException(
          "Connection aborted - failed to write to known_hosts. Reason: " + e.getMessage(), e);
    }
  }
  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");
  }
예제 #18
0
파일: scp.java 프로젝트: tmar89/ftpsmanager
  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) {
      }
    }
  }
예제 #19
0
  /**
   * 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();
  }
예제 #20
0
  protected Session createSession(final RemoteFileConfiguration configuration)
      throws JSchException {
    final JSch jsch = new JSch();
    JSch.setLogger(new JSchLogger());

    SftpConfiguration sftpConfig = (SftpConfiguration) configuration;

    if (isNotEmpty(sftpConfig.getCiphers())) {
      LOG.debug("Using ciphers: {}", sftpConfig.getCiphers());
      Hashtable<String, String> ciphers = new Hashtable<String, String>();
      ciphers.put("cipher.s2c", sftpConfig.getCiphers());
      ciphers.put("cipher.c2s", sftpConfig.getCiphers());
      JSch.setConfig(ciphers);
    }

    if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {
      LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile());
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase());
      } else {
        jsch.addIdentity(sftpConfig.getPrivateKeyFile());
      }
    }

    if (sftpConfig.getPrivateKey() != null) {
      LOG.debug("Using private key information from byte array");
      byte[] passphrase = null;
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        try {
          passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new JSchException("Cannot transform passphrase to byte[]", e);
        }
      }
      jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase);
    }

    if (sftpConfig.getPrivateKeyUri() != null) {
      LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri());
      byte[] passphrase = null;
      if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
        try {
          passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new JSchException("Cannot transform passphrase to byte[]", e);
        }
      }
      try {
        InputStream is =
            ResourceHelper.resolveMandatoryResourceAsInputStream(
                endpoint.getCamelContext().getClassResolver(), sftpConfig.getPrivateKeyUri());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOHelper.copyAndCloseInput(is, bos);
        jsch.addIdentity("ID", bos.toByteArray(), null, passphrase);
      } catch (IOException e) {
        throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e);
      }
    }

    if (sftpConfig.getKeyPair() != null) {
      LOG.debug("Using private key information from key pair");
      KeyPair keyPair = sftpConfig.getKeyPair();
      if (keyPair.getPrivate() != null && keyPair.getPublic() != null) {
        if (keyPair.getPrivate() instanceof RSAPrivateKey
            && keyPair.getPublic() instanceof RSAPublicKey) {
          jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null);
        } else if (keyPair.getPrivate() instanceof DSAPrivateKey
            && keyPair.getPublic() instanceof DSAPublicKey) {
          jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null);
        } else {
          LOG.warn("Only RSA and DSA key pairs are supported");
        }
      } else {
        LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled");
      }
    }

    if (isNotEmpty(sftpConfig.getKnownHostsFile())) {
      LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile());
      jsch.setKnownHosts(sftpConfig.getKnownHostsFile());
    }

    if (isNotEmpty(sftpConfig.getKnownHostsUri())) {
      LOG.debug("Using knownhosts uri: {}", sftpConfig.getKnownHostsUri());
      try {
        InputStream is =
            ResourceHelper.resolveMandatoryResourceAsInputStream(
                endpoint.getCamelContext().getClassResolver(), sftpConfig.getKnownHostsUri());
        jsch.setKnownHosts(is);
      } catch (IOException e) {
        throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e);
      }
    }

    if (sftpConfig.getKnownHosts() != null) {
      LOG.debug("Using knownhosts information from byte array");
      jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
    }

    final Session session =
        jsch.getSession(
            configuration.getUsername(), configuration.getHost(), configuration.getPort());

    if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
      LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
      session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
    }

    session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
    session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());

    // compression
    if (sftpConfig.getCompression() > 0) {
      LOG.debug("Using compression: {}", sftpConfig.getCompression());
      session.setConfig("compression.s2c", "[email protected],zlib,none");
      session.setConfig("compression.c2s", "[email protected],zlib,none");
      session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
    }

    // set the PreferredAuthentications
    if (sftpConfig.getPreferredAuthentications() != null) {
      LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
      session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
    }

    // set user information
    session.setUserInfo(
        new ExtendedUserInfo() {
          public String getPassphrase() {
            return null;
          }

          public String getPassword() {
            return configuration.getPassword();
          }

          public boolean promptPassword(String s) {
            return true;
          }

          public boolean promptPassphrase(String s) {
            return true;
          }

          public boolean promptYesNo(String s) {
            LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
            // Return 'false' indicating modification of the hosts file is disabled.
            return false;
          }

          public void showMessage(String s) {
            LOG.trace("Message received from Server: " + s);
          }

          public String[] promptKeyboardInteractive(
              String destination,
              String name,
              String instruction,
              String[] prompt,
              boolean[] echo) {
            // must return an empty array if password is null
            if (configuration.getPassword() == null) {
              return new String[0];
            } else {
              return new String[] {configuration.getPassword()};
            }
          }
        });

    // set the SO_TIMEOUT for the time after the connect phase
    if (configuration.getSoTimeout() > 0) {
      session.setTimeout(configuration.getSoTimeout());
    }

    // set proxy if configured
    if (proxy != null) {
      session.setProxy(proxy);
    }

    return session;
  }
예제 #21
0
  // Taken from Apache Camel test source
  private void setupKnownHosts(int port) {
    String knownHostsFile = SCP_ROOT_DIR + "/" + KNOWN_HOSTS;

    // For security reasons (avoiding man in the middle attacks),
    // camel-jsch will only connect to known hosts. For unit testing
    // we use a known key, but since the port is dynamic, the
    // known_hosts file will be generated by the following code and
    // should contain a line like below (if
    // "HashKnownHosts"=="yes" the hostname:port part will be
    // hashed and look a bit more complicated).
    //
    // [localhost]:21000 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDd \
    // fIWeSV4o68dRrKSzFd/Bk51E65UTmmSrmW0O1ohtzi6HzsDPjXgCtlTt3F \
    // qTcfFfI92IlTr4JWqC9UK1QT1ZTeng0MkPQmv68hDANHbt5CpETZHjW5q4 \
    // OOgWhVvj5IyOC2NZHtKlJBkdsMAa15ouOOJLzBvAvbqOR/yUROsEiQ==

    JSch jsch = new JSch();
    try {
      jsch.setKnownHosts(knownHostsFile);
      Session s = jsch.getSession("alice", "localhost", port);
      s.setConfig("StrictHostKeyChecking", "ask");

      // TODO: by the current jsch (0.1.51) setting "HashKnownHosts" to "no" is a workaround
      // to make the tests run green, see also http://sourceforge.net/p/jsch/bugs/63/
      s.setConfig("HashKnownHosts", "no");
      s.setUserInfo(
          new UserInfo() {
            @Override
            public String getPassphrase() {
              return null;
            }

            @Override
            public String getPassword() {
              return "security";
            }

            @Override
            public boolean promptPassword(String message) {
              return true;
            }

            @Override
            public boolean promptPassphrase(String message) {
              return false;
            }

            @Override
            public boolean promptYesNo(String message) {
              // accept host authenticity
              return true;
            }

            @Override
            public void showMessage(String message) {}
          });
      // in the process of connecting, "[localhost]:<port>" is added to the knownHostsFile
      s.connect();
      s.disconnect();
    } catch (JSchException e) {
      e.printStackTrace();
    }
  }
예제 #22
0
  private static void testDownloadStp() throws JSchException, SftpException {
    Channel channel = null;
    Session session = null;
    OutputStream os = null;
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    try {
      JSch jsch = new JSch();

      // jsch.setKnownHosts("/home/foo/.ssh/known_hosts");

      String user = "******";
      String host = "10.238.226.75";

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

      String passwd = "sdpuser";
      session.setPassword(passwd);

      UserInfo ui =
          new MyUserInfo() {
            public void showMessage(String message) {
              //	          JOptionPane.showMessageDialog(null, message);
            }

            public boolean promptYesNo(String message) {
              //	          Object[] options={ "yes", "no" };
              //	          int foo=JOptionPane.showOptionDialog(null,
              //	                                               message,
              //	                                               "Warning",
              //	                                               JOptionPane.DEFAULT_OPTION,
              //	                                               JOptionPane.WARNING_MESSAGE,
              //	                                               null, options, options[0]);
              return true;
            }

            // If password is not given before the invocation of Session#connect(),
            // implement also following methods,
            //   * UserInfo#getPassword(),
            //   * UserInfo#promptPassword(String message) and
            //   * UIKeyboardInteractive#promptKeyboardInteractive()

          };

      session.setUserInfo(ui);

      // It must not be recommended, but if you want to skip host-key check,
      // invoke following,
      // session.setConfig("StrictHostKeyChecking", "no");

      // session.connect();
      session.connect(30000); // making a connection with timeout.

      channel = session.openChannel("sftp");

      channel.connect(3 * 1000);

      ChannelSftp sftp = (ChannelSftp) channel;

      sftp.cd("/var/opt/fds/logs");
      byte[] buffer = new byte[1024];
      bis = new BufferedInputStream(sftp.get("TTMonitor.log"));
      File newFile = new File("D:/Doneeeeeeeee.java");
      os = new FileOutputStream(newFile);
      bos = new BufferedOutputStream(os);
      int readCount;
      System.out.println("Getting: the file");
      while ((readCount = bis.read(buffer)) > 0) {
        System.out.println("Writing ");
        bos.write(buffer, 0, readCount);
      }

      System.out.println("Done :) ");
      //		    System.out.println(sftp.getHome());
      //		    for (Object o : sftp.ls("")) {
      //		        System.out.println(((ChannelSftp.LsEntry)o).getFilename());
      //		    }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      //	      Session session=jsch.getSession("usersdp","10.238.226.75",22);

      try {
        if (os != null) {
          os.close();
        }
        if (bis != null) {
          bis.close();
        }
        if (bos != null) {
          bos.close();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      channel.disconnect();
      session.disconnect();
    }
  }
예제 #23
-1
 /**
  * method for establishing connection while authentication
  *
  * @param username
  * @param namenodeIP
  * @param nnpwd
  * @param privateKeyPath
  * @return
  * @throws JSchException
  * @throws IOException
  * @throws InterruptedException
  */
 public static Session establishConnection(
     String username, String namenodeIP, String nnpwd, String privateKeyPath)
     throws JSchException, IOException, InterruptedException {
   JSch jsch = new JSch();
   Session session = jsch.getSession(username, namenodeIP, Constants.TWENTY_TWO);
   session.setPassword(nnpwd);
   UserInfo info = new JumbuneUserInfo();
   jsch.addIdentity(privateKeyPath, nnpwd);
   session.setUserInfo(info);
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
   return session;
 }