Package org.dru.clay.respository.transport.ssh

Source Code of org.dru.clay.respository.transport.ssh.Test

package org.dru.clay.respository.transport.ssh;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.userauth.method.AuthMethod;

import com.jcraft.jsch.agentproxy.AgentProxy;
import com.jcraft.jsch.agentproxy.AgentProxyException;
import com.jcraft.jsch.agentproxy.Connector;
import com.jcraft.jsch.agentproxy.ConnectorFactory;
import com.jcraft.jsch.agentproxy.Identity;
import com.jcraft.jsch.agentproxy.sshj.AuthAgent;

public class Test {

  public static void main(String[] args) throws Exception {
    final SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();

    ssh.connect("dev4");
    try {
      AgentProxy agentProxy = getAgentProxy();
      if (agentProxy == null) {
        System.err.println("No agentProxy");
        System.exit(0);
      }
      ssh.auth(System.getProperty("user.name"), getAuthMethods(agentProxy));
      final Session session = ssh.startSession();
      try {
        final Command cmd = session.exec("ping -c 1 google.com");
        System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
        cmd.join(5, TimeUnit.SECONDS);
        System.out.println("\n** exit status: " + cmd.getExitStatus());
      } finally {
        session.close();
      }
    } finally {
      ssh.disconnect();
    }
  }

  private static AgentProxy getAgentProxy() {
    Connector connector = getAgentConnector();
    if (connector != null)
      return new AgentProxy(connector);
    return null;
  }

  private static Connector getAgentConnector() {
    try {
      return ConnectorFactory.getDefault().createConnector();
    } catch (AgentProxyException e) {
      System.err.println(e);
    }
    return null;
  }

  private static List<AuthMethod> getAuthMethods(AgentProxy agent) throws Exception {
    Identity[] identities = agent.getIdentities();
    List<AuthMethod> result = new ArrayList<AuthMethod>();
    for (Identity identity : identities) {
      result.add(new AuthAgent(agent, identity));
    }
    return result;
  }
}
TOP

Related Classes of org.dru.clay.respository.transport.ssh.Test

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.