zoukankan      html  css  js  c++  java
  • Java SSH库使用简介:Apache sshd和JSch(Java Secure Channel)

    1.Apache sshd

    Apache sshd是一个SSH协议的100%纯Java库,支持客户端和服务器。sshd库基于Apache MINA项目(可伸缩高性能的异步IO库)。

    官方网站:http://mina.apache.org/sshd-project/documentation.html

    客户端示例代码:

        public void clentTest() throws IOException
        {
            String cmd="ifconfig";
            SshClient client=SshClient.setUpDefaultClient();
            client.start();
            ClientSession session=client.connect("bellring", "10.2.48.179", 22).await().getSession();
            session.addPasswordIdentity("bellring");
         //session.addPublicKeyIdentity(SecurityUtils.loadKeyPairIdentity("keyname", new FileInputStream("priKey.pem"), null));
    if(!session.auth().await().isSuccess()) System.out.println("auth failed"); ChannelExec ec=session.createExecChannel(cmd); ec.setOut(System.out); ec.open(); ec.waitFor(ClientChannel.CLOSED, 0); ec.close(); client.stop(); }
        public void sshdClientSftpTest() throws IOException, InterruptedException
        {
            Path src=Paths.get("src_sshd.txt");
            Files.deleteIfExists(src);
            Files.createFile(src);
            Files.write(src, "adsfa
    sdfs".getBytes());
    
            
            SshClient client=SshClient.setUpDefaultClient();
            client.start();
            ClientSession session=client.connect("bellring", "10.2.48.179", 22).await().getSession();
            //session.addPasswordIdentity("bellring");
         session.addPublicKeyIdentity(SecurityUtils.loadKeyPairIdentity("keyname", new FileInputStream("priKey.pem"), null));
    if(!session.auth().await().isSuccess())
                System.out.println("auth failed");
            
            SftpClient sftp=session.createSftpClient();
            
            for(DirEntry de:sftp.readDir("."))
                System.out.println(de.filename+" "+de.attributes.type);
            
            OutputStream os=sftp.write("test/dst_sshd.txt");
            Files.copy(src, os);
            os.close();
            
            //sftp.remove("delete_file.txt");
            
            InputStream is=sftp.read("test/dst_sshd.txt");
            Path dst=Paths.get("dst1_sshd.txt");
            Files.deleteIfExists(dst);
            Files.copy(is, dst);
            is.close();
            
            sftp.close();
            client.stop();
        }

    服务器端示例代码:

        public void serverTest() throws IOException, InterruptedException
        {
            SshServer sshd = SshServer.setUpDefaultServer();
            sshd.setPort(22);
            
            //*give host key generator a path, when sshd server restart, the same key will be load and used to authenticate the server
            sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));
            
            sshd.setPasswordAuthenticator(new PasswordAuthenticator(){
                @Override
                public boolean authenticate(String username, String password, ServerSession session) {
                    System.out.println("authen:  user="+username+"  password="+password);
                    if("bellring".equals(username) && "123456".equals(password))
                        return true;
                    return false;
                }});
            
            //use file ~/.ssh/authorized_keys
            sshd.setPublickeyAuthenticator(new DefaultAuthorizedKeysAuthenticator(false));
                    
            //* CommandFactory can be userd in addition to the ShellFactory,
            //*  it can also be used instead of the ShellFactory. 
            //*  The CommandFactory is used when direct commands are sent to the SSH server, 
            //*  as this is the case when running ssh localhost shutdown or scp xxx
            ScpCommandFactory scpCmdFactory=new ScpCommandFactory();
            scpCmdFactory.setDelegateCommandFactory(new CommandFactory() {
                 public Command createCommand(String command) {
                     System.out.println("command = "" + command + """);
                     return new ProcessShellFactory(("cmd /c "+command).split(" ")).create();
                  }
            });
            sshd.setCommandFactory(scpCmdFactory);
            
            sshd.start();
        }

    2.JSch(Java Secure Channel)

    jsch也是SSH2的纯Java实现。依赖于JavaTm Cryptography Extension(JCE)。JSch支持客户端。

    官网:http://www.jcraft.com/jsch/

    示例:http://www.jcraft.com/jsch/examples/

    客户端远程命令执行示例:

        public void testJschClient() throws JSchException, InterruptedException
        {
            JSch jsch=new JSch();

        
    //set private key for auth
         jsch.addIdentity("yangtianxin_pc");
    Session session
    =jsch.getSession("bellring", "10.2.48.179", 22); session.setConfig("StrictHostKeyChecking", "no");
    //set auth info interactively //session.setUserInfo(new UserInfo(){.....}); //session.setPassword("bellring"); session.connect(); com.jcraft.jsch.ChannelExec ec=(com.jcraft.jsch.ChannelExec)session.openChannel("exec"); ec.setCommand("ifconfig"); ec.setInputStream(null); ec.setErrStream(System.err); ec.setOutputStream(System.out); ec.connect(); while(!ec.isClosed()) Thread.sleep(500); ec.disconnect(); session.disconnect(); }

    sftp文件操作示例

        public void testJschClientSftp() throws JSchException, InterruptedException, SftpException, IOException
        {
            JSch jsch=new JSch();
        
         //add private key for auth
         //jsch.addIdentity("yangtianxin_pc");
    Session session
    =jsch.getSession("bellring", "10.2.48.179", 22); session.setConfig("StrictHostKeyChecking", "no");
    //set auth info interactively //session.setUserInfo(new UserInfo(){.....}); session.setPassword("bellring"); session.connect(); com.jcraft.jsch.ChannelSftp sftpChannel=(com.jcraft.jsch.ChannelSftp)session.openChannel("sftp"); sftpChannel.connect(); Path src=Paths.get("src.txt"); Files.deleteIfExists(src); Files.createFile(src); Files.write(src, "adsfasdfs".getBytes()); @SuppressWarnings("unchecked") Vector<LsEntry> vector=sftpChannel.ls("."); for(LsEntry entry: vector) System.out.println(entry.getFilename()+" "+entry.getAttrs().getSize()); sftpChannel.cd("test"); sftpChannel.put("src.txt", "dst.txt"); sftpChannel.get("dst.txt", "dst1.txt"); sftpChannel.rm("dst.txt"); sftpChannel.disconnect(); session.disconnect(); System.out.println("done"); }
  • 相关阅读:
    基础数据类型补充、集合、深浅拷贝
    python中(id,is,==,)小数据池,代码块
    字典:python的基础数据类型
    五四青年节后记
    test
    agl---atumotive grade linux开篇
    传感器
    金字塔原理
    写在2017年底
    C# 输出16进值
  • 原文地址:https://www.cnblogs.com/pixy/p/4810422.html
Copyright © 2011-2022 走看看