Trilead,SSH2的Java调用

  最近项目要部署10台设备,如果每台设备都手动进行部署想想也是醉了。

  因为之前一直使用SecurityFX以及SecurityCRT,所以考虑是否可以使用基于SSH2的类库来实现文件拷贝以及远程命令调用。

  后来发现了Trilead库:

  jar下载地址:

  http://mvnrepository.com/artifact/com.trilead/trilead-ssh2/1.0.0-build221

  git源码地址:

  https://github.com/jenkinsci/trilead-ssh2/

  看到源码地址,知道了这是Jekins相关的开源项目。

  上代码:

  实现远程指令执行:

        Connection conn = new Connection("10.1.108.35");
        try {
            conn.connect();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            conn.authenticateWithPassword("root", "rootbd");
            Session session = conn.openSession();
            SFTPv3Client client = new SFTPv3Client(conn);
            //client.rm("/apps/123/Nero.exe");
            session.execCommand("mkdir /apps/123");
            InputStream inp = session.getStdout();
            InputStreamReader reader = new InputStreamReader(inp);
            BufferedReader br = new BufferedReader(reader);

            String line = br.readLine();
            System.out.println(line);

  这是前半段代码,主要是实现了远程执行指令,调用的是session的execCommand;

  还可以使用SFTPv3Client(Security FTP)内置的常用函数,ls,rm等来进行常用简单操作;

  下面是后半段代码,主要是实现了文件上传功能;

            SCPClient scpClient = conn.createSCPClient();
            
            System.out.println("开始拷贝文件...");
            scpClient.put("e:\\tmp\\sendFiles\\Nero.exe", "/apps/123/");
            System.out.println("拷贝文件完成!");
            Vector<SFTPv3DirectoryEntry> files = client.ls("/apps/123");
            for(SFTPv3DirectoryEntry item : files){
                System.out.println("文件名称: " + item.filename);
            }
            /*
            SFTPv3FileHandle handle = client.createFile("/apps/123/Nero.exe");
            File localFile = new File("e:\\tmp\\sendFiles\\Nero.exe");
            FileInputStream fis = new FileInputStream(localFile);
            byte[] arr = new byte[(int) localFile.length()];
            fis.read(arr);
            fis.close();
            client.write(handle, 0, arr, 0, arr.length);
            client.closeFile(handle);
            */
            client.close();
            conn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

  这里采用的是SCPClient,熟悉Linux指令的童鞋都知道SCP指令用于远程拷贝文件,局域网内部100M带宽可以达到80M/s的传输速率,很快;

  后面是实践SFTPClient的ls函数,返回的是SFTPv3DirectoryEntry的Vector(向量,具备自动伸缩功能)对象,获取远端的文件列表信息;

  最后是一大段的注释,是通过SFTPv3Client来进行传输,可以控制到字节力度,但是传输速度太慢;在网络不好的情况下,想要使用断点续传等机制可以采用。

  

  

posted on 2017-04-06 22:44  下士闻道  阅读(5747)  评论(0编辑  收藏  举报

导航