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

 

转载于:https://www.cnblogs.com/pixy/p/4810422.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. hicore: hicore 是一个在高性能计算节点上运行的进程,主要用于高性能计算和科学计算任务。它通常用于执行大量的计算任务,需要大量的计算资源和高速的网络连接。hicore 进程通常使用的是大页内存,可以有效地减少内存碎片和减少内存访问的开销。 使用说明: hicore 进程通常由专门的运维人员或者高性能计算专家来管理和使用,在使用时需要注意以下几点: - 确保高性能计算节点上的资源足够支持 hicore 进程的运行; - 需要使用专门的工具和算法来编写和运行 hicore 进程; - 确保 hicore 进程使用的内存分配和释放方式正确,不会导致内存泄漏或者内存错误。 2. sshd: sshd 是 Secure Shell Daemon 的缩写,是一种远程登录协议,它允许用户在不安全的网络中通过加密连接登录到远程计算机上,并且可以在远程计算机上执行命令和程序。sshd 进程通常会占用一定的内存和网络资源。 使用说明: sshd 进程通常是在服务器或者云计算环境下使用的,用于远程登录和管理服务器。在使用时需要注意以下几点: - 确保 sshd 进程的配置和安全设置正确,不会导致安全漏洞; - 确保 sshd 进程的网络连接稳定和可靠,不会出现网络中断或者连接超时的问题; - 确保 sshd 进程的权限和访问控制正确,不会导致未授权的访问或者权限不足的问题。 3. oscproc: oscproc 是操作系统进程的缩写,它是操作系统内部运行的进程,用于执行系统任务和管理系统资源。oscproc 进程通常会占用一定的内存和 CPU 资源。 使用说明: oscproc 进程通常由操作系统内部自动创建和管理,在使用时需要注意以下几点: - 避免修改或者删除系统进程,否则可能会导致系统崩溃或者无法启动; - 确保系统进程的权限和访问控制正确,不会导致未授权的访问或者权限不足的问题; - 在使用系统进程时需要谨慎,避免对系统的稳定性和安全性造成影响。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值