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\nsdfs".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"); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM