sshdjava示例

sshdjava示例,java,ssh,sshd,Java,Ssh,Sshd,有人能给我指出一些使用SSHD访问服务器并从JAVA应用程序执行一些命令的示例代码吗。我已经浏览了ApacheSHD网站和下载,还没有找到任何有用的文档和示例代码。我还用谷歌搜索了SSHD示例代码,但没有成功。这一个可以运行,我已经检查过了。我只是删除了导入。 apache版本sshd-core-0.7.0.jar public class SshClient extends AbstractFactoryManager implements ClientFactoryManager {

有人能给我指出一些使用SSHD访问服务器并从JAVA应用程序执行一些命令的示例代码吗。我已经浏览了ApacheSHD网站和下载,还没有找到任何有用的文档和示例代码。我还用谷歌搜索了SSHD示例代码,但没有成功。

这一个可以运行,我已经检查过了。我只是删除了导入。 apache版本sshd-core-0.7.0.jar

public class SshClient extends AbstractFactoryManager implements ClientFactoryManager {

    protected IoConnector connector;
    protected SessionFactory sessionFactory;

    private ServerKeyVerifier serverKeyVerifier;

    public SshClient() {
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public ServerKeyVerifier getServerKeyVerifier() {
        return serverKeyVerifier;
    }

    public void setServerKeyVerifier(ServerKeyVerifier serverKeyVerifier) {
        this.serverKeyVerifier = serverKeyVerifier;
    }

    public void start() {
        // Register the additional agent forwarding channel if needed
        if (getAgentFactory() != null) {
            List<NamedFactory<Channel>> factories = getChannelFactories();
            if (factories == null) {
                factories = new ArrayList<NamedFactory<Channel>>();
            } else {
                factories = new ArrayList<NamedFactory<Channel>>(factories);
            }
            factories.add(getAgentFactory().getChannelForwardingFactory());
            setChannelFactories(factories);
        }
        connector = createAcceptor();

        if (sessionFactory == null) {
            sessionFactory = new SessionFactory();
        }
        sessionFactory.setClient(this);
        connector.setHandler(sessionFactory);
    }

    protected NioSocketConnector createAcceptor() {
        return new NioSocketConnector(getNioWorkers());
    }

    public void stop() {
        connector.dispose();
        connector = null;
    }

    public ConnectFuture connect(String host, int port) throws Exception {
        assert host != null;
        assert port >= 0;
        if (connector == null) {
            throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
        }
        SocketAddress address = new InetSocketAddress(host, port);
        return connect(address);
    }

    public ConnectFuture connect(SocketAddress address) throws Exception {
        assert address != null;
        if (connector == null) {
            throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
        }
        final ConnectFuture connectFuture = new DefaultConnectFuture(null);
        connector.connect(address).addListener(new IoFutureListener<org.apache.mina.core.future.ConnectFuture>() {
            public void operationComplete(org.apache.mina.core.future.ConnectFuture future) {
                if (future.isCanceled()) {
                    connectFuture.cancel();
                } else if (future.getException() != null) {
                    connectFuture.setException(future.getException());
                } else {
                    ClientSessionImpl session = (ClientSessionImpl) AbstractSession.getSession(future.getSession());
                    connectFuture.setSession(session);
                }
            }
        });
        return connectFuture;
    }

    /**
     * Setup a default client.  The client does not require any additional setup.
     *
     * @return a newly create SSH client
     */
    public static SshClient setUpDefaultClient() {
        SshClient client = new SshClient();
        // DHG14 uses 2048 bits key which are not supported by the default JCE provider
        if (SecurityUtils.isBouncyCastleRegistered()) {
            client.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(
                    new DHG14.Factory(),
                    new DHG1.Factory()));
            client.setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
        } else {
            client.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(
                    new DHG1.Factory()));
            client.setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
        }
        setUpDefaultCiphers(client);
        // Compression is not enabled by default
        // client.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(
        //         new CompressionNone.Factory(),
        //         new CompressionZlib.Factory(),
        //         new CompressionDelayedZlib.Factory()));
        client.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(
                new CompressionNone.Factory()));
        client.setMacFactories(Arrays.<NamedFactory<Mac>>asList(
                new HMACMD5.Factory(),
                new HMACSHA1.Factory(),
                new HMACMD596.Factory(),
                new HMACSHA196.Factory()));
        client.setSignatureFactories(Arrays.<NamedFactory<Signature>>asList(
                new SignatureDSA.Factory(),
                new SignatureRSA.Factory()));
        return client;
    }

    private static void setUpDefaultCiphers(SshClient client) {
        List<NamedFactory<Cipher>> avail = new LinkedList<NamedFactory<Cipher>>();
        avail.add(new AES128CBC.Factory());
        avail.add(new TripleDESCBC.Factory());
        avail.add(new BlowfishCBC.Factory());
        avail.add(new AES192CBC.Factory());
        avail.add(new AES256CBC.Factory());

        for (Iterator<NamedFactory<Cipher>> i = avail.iterator(); i.hasNext();) {
            final NamedFactory<Cipher> f = i.next();
            try {
                final Cipher c = f.create();
                final byte[] key = new byte[c.getBlockSize()];
                final byte[] iv = new byte[c.getIVSize()];
                c.init(Cipher.Mode.Encrypt, key, iv);
            } catch (InvalidKeyException e) {
                i.remove();
            } catch (Exception e) {
                i.remove();
            }
        }
        client.setCipherFactories(avail);
    }

    /*=================================
          Main class implementation
     *=================================*/

    public static void main(String[] args) throws Exception {
        int port = 22;
        String host = null;
        String login = System.getProperty("user.name");
        boolean agentForward = false;
        List<String> command = null;
        int logLevel = 0;
        boolean error = false;

        for (int i = 0; i < args.length; i++) {
            if (command == null && "-p".equals(args[i])) {
                if (i + 1 >= args.length) {
                    System.err.println("option requires an argument: " + args[i]);
                    error = true;
                    break;
                }
                port = Integer.parseInt(args[++i]);
            } else if (command == null && "-l".equals(args[i])) {
                if (i + 1 >= args.length) {
                    System.err.println("option requires an argument: " + args[i]);
                    error = true;
                    break;
                }
                login = args[++i];
            } else if (command == null && "-v".equals(args[i])) {
                logLevel = 1;
            } else if (command == null && "-vv".equals(args[i])) {
                logLevel = 2;
            } else if (command == null && "-vvv".equals(args[i])) {
                logLevel = 3;
            } else if ("-A".equals(args[i])) {
                agentForward = true;
            } else if ("-a".equals(args[i])) {
                agentForward = false;
            } else if (command == null && args[i].startsWith("-")) {
                System.err.println("illegal option: " + args[i]);
                error = true;
                break;
            } else {
                if (host == null) {
                    host = args[i];
                } else {
                    if (command == null) {
                        command = new ArrayList<String>();
                    }
                    command.add(args[i]);
                }
            }
        }
        if (host == null) {
            System.err.println("hostname required");
            error = true;
        }
        if (error) {
            System.err.println("usage: ssh [-A|-a] [-v[v][v]] [-l login] [-p port] hostname [command]");
            System.exit(-1);
        }

        // TODO: handle log level

        SshClient client = SshClient.setUpDefaultClient();
        client.start();

        try {
            boolean hasKeys = false;

            /*
            String authSock = System.getenv(SshAgent.SSH_AUTHSOCKET_ENV_NAME);
            if (authSock == null) {
                KeyPair[] keys = null;
                AgentServer server = new AgentServer();
                authSock = server.start();
                List<String> files = new ArrayList<String>();
                File f = new File(System.getProperty("user.home"), ".ssh/id_dsa");
                if (f.exists() && f.isFile() && f.canRead()) {
                    files.add(f.getAbsolutePath());
                }
                f = new File(System.getProperty("user.home"), ".ssh/id_rsa");
                if (f.exists() && f.isFile() && f.canRead()) {
                    files.add(f.getAbsolutePath());
                }
                try {
                    if (files.size() > 0) {
                        keys = new FileKeyPairProvider(files.toArray(new String[0]), new PasswordFinder() {
                            public char[] getPassword() {
                                try {
                                    System.out.println("Enter password for private key: ");
                                    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
                                    String password = r.readLine();
                                    return password.toCharArray();
                                } catch (IOException e) {
                                    return null;
                                }
                            }
                        }).loadKeys();
                    }
                } catch (Exception e) {
                }
                SshAgent agent = new AgentClient(authSock);
                for (KeyPair key : keys) {
                    agent.addIdentity(key, "");
                }
                agent.close();
            }
            if (authSock != null) {
                SshAgent agent = new AgentClient(authSock);
                hasKeys = agent.getIdentities().size() > 0;
            }
            client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, authSock);
            */

            ClientSession session = client.connect(host, port).await().getSession();
            int ret = ClientSession.WAIT_AUTH;

            while ((ret & ClientSession.WAIT_AUTH) != 0) {
                if (hasKeys) {
                    session.authAgent(login);
                    ret = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                } else {
                    System.out.print("Password:");
                    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
                    String password = r.readLine();
                    session.authPassword(login, password);
                    ret = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                }
            }
            if ((ret & ClientSession.CLOSED) != 0) {
                System.err.println("error");
                System.exit(-1);
            }
            ClientChannel channel;
            if (command == null) {
                channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
                ((ChannelShell) channel).setAgentForwarding(agentForward);
                channel.setIn(new NoCloseInputStream(System.in));
            } else {
                channel = session.createChannel(ClientChannel.CHANNEL_EXEC);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Writer w = new OutputStreamWriter(baos);
                for (String cmd : command) {
                    w.append(cmd).append(" ");
                }
                w.append("\n");
                w.close();
                channel.setIn(new ByteArrayInputStream(baos.toByteArray()));
            }
            channel.setOut(new NoCloseOutputStream(System.out));
            channel.setErr(new NoCloseOutputStream(System.err));
            channel.open().await();
            channel.waitFor(ClientChannel.CLOSED, 0);
            session.close(false);
        } finally {
            client.stop();
        }
    }

}
公共类SshClient扩展AbstractFactoryManager实现ClientFactoryManager{
受保护的IOC连接器;
受保护的SessionFactory SessionFactory;
专用ServerKeyVerifier ServerKeyVerifier;
公共SshClient(){
}
public SessionFactory getSessionFactory(){
返回工厂;
}
public void setSessionFactory(SessionFactory SessionFactory){
this.sessionFactory=sessionFactory;
}
public ServerKeyVerifier getServerKeyVerifier(){
返回服务器密钥验证器;
}
public void setServerKeyVerifier(ServerKeyVerifier ServerKeyVerifier){
this.serverKeyVerifier=serverKeyVerifier;
}
公开作废开始(){
//如果需要,请注册附加代理转发通道
如果(getAgentFactory()!=null){
List factories=getChannelFactories();
if(工厂==null){
工厂=新的ArrayList();
}否则{
工厂=新阵列列表(工厂);
}
add(getAgentFactory().getChannelForwardingFactory());
工厂(厂),;
}
连接器=createAcceptor();
if(sessionFactory==null){
sessionFactory=新sessionFactory();
}
setClient(this);
connector.setHandler(sessionFactory);
}
受保护的NioSocketConnector createAcceptor(){
返回新的NioSocketConnector(getNioWorkers());
}
公共停车场(){
connector.dispose();
连接器=空;
}
public ConnectFuture connect(字符串主机,int端口)引发异常{
断言主机!=null;
断言端口>=0;
if(连接器==null){
抛出新的IllegalStateException(“SshClient未启动。请在连接到服务器之前调用start()方法”);
}
SocketAddress地址=新的InetSocketAddress(主机、端口);
返回连接(地址);
}
public ConnectFuture connect(SocketAddress地址)引发异常{
断言地址!=null;
if(连接器==null){
抛出新的IllegalStateException(“SshClient未启动。请在连接到服务器之前调用start()方法”);
}
final ConnectFuture=new DefaultConnectFuture(null);
connector.connect(地址).addListener(新的IoFutureListener(){
public void operation complete(org.apache.mina.core.future.ConnectFuture){
if(future.isCanceled()){
connectFuture.cancel();
}else if(future.getException()!=null){
connectFuture.setException(future.getException());
}否则{
ClientSessionImpl会话=(ClientSessionImpl)AbstractSession.getSession(future.getSession());
connectFuture.setSession(会话);
}
}
});
回归未来;
}
/**
*设置默认客户端。客户端不需要任何其他设置。
*
*@返回新创建的SSH客户端
*/
公共静态SshClient setUpDefaultClient(){
SshClient客户端=新的SshClient();
//DHG14使用默认JCE提供程序不支持的2048位密钥
if(SecurityUtils.isBouncyCastleRegistered()){
client.setKeyExchangeFactories(Arrays.asList(
新的DHG14.Factory(),
新的DHG1.Factory());
client.setRandomFactory(新的SingletonRandomFactory(新的BouncyCastleRandom.Factory());
}否则{
client.setKeyExchangeFactories(Arrays.asList(
新的DHG1.Factory());
setRandomFactory(新的SingletonRandomFactory(新的JceRandom.Factory());
}
设置默认密码(客户端);
//默认情况下不启用压缩
//client.setCompressionFactorys(Arrays.asList(
//新的CompressionNone.Factory(),
//新压缩zlib.Factory(),
//新的压缩延迟zlib.Factory());
client.setCompressionFactorys(Arrays.asList(
新压缩无。工厂();
client.setMacFactories(Arrays.asList(
新的HMACMD5.Factory(),
新的HMACSHA1.Factory(),
新的HMACMD596.Factory(),
新HMACSHA196.Factory());
client.setSignatureFactories(Arrays.asList(
新签名sa.Factory(),
新签名者a.Factory());
返回客户;
}
专用静态无效设置默认密码(SshClient客户端){
List avail=new LinkedList();
add(新的AES128CBC.Factory());
add(新的三元组scbc.Factory());
add(新的BlowfishCBC.Factory());
avail.add(新的AES192CBC.Factory());
avail.add(新AES256CBC.Factory());
for(迭代器i=avail.Iterator();i.hasNext();){
最终名称工厂f=i.next();
试一试{
最终密码c=f.create();
最终字节[]键=新字节[c.getBlockSize()];
最后一个字节[]iv=新字节[c.getIVSize()];
c、 init(Cipher.Mode.Encrypt,key,iv);
}捕获(InvalidKeyException e){
i、 删除();
}捕获(例外e){
i、 删除();
}
}
客户。设置密码工厂(可用);
}
/*====
public static void main(String[] args) throws IOException, InterruptedException
{
    SshClient client = SshClient.setUpDefaultClient();
    client.start();

    final ClientSession session = client.connect("bob", "bob.mynetwork.com", 22).await().getSession();

    int authState = ClientSession.WAIT_AUTH;
    while ((authState & ClientSession.WAIT_AUTH) != 0) {

        session.addPasswordIdentity("bobspassword");

        System.out.println("authenticating...");
        final AuthFuture authFuture = session.auth();
        authFuture.addListener(new SshFutureListener<AuthFuture>()
        {
            @Override
            public void operationComplete(AuthFuture arg0)
            {
                System.out.println("Authentication completed with " + ( arg0.isSuccess() ? "success" : "failure"));
            }
        });

        authState = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
    }

    if ((authState & ClientSession.CLOSED) != 0) {
        System.err.println("error");
        System.exit(-1);
    }

    final ClientChannel channel = session.createShellChannel();
    channel.setOut(new NoCloseOutputStream(System.out));
    channel.setErr(new NoCloseOutputStream(System.err));
    channel.open();

    executeCommand(channel, "pwd\n");
    executeCommand(channel, "ll\n");
    channel.waitFor(ClientChannel.CLOSED, 0);

    session.close(false);
    client.stop();
}

private static void executeCommand(final ClientChannel channel, final String command) throws IOException
{
    final InputStream commandInput = new ByteArrayInputStream(command.getBytes());
    channel.setIn(new NoCloseInputStream(commandInput));
}