java使用Jsch/ssh2实现从linux服务端遍历文件名以及文件内容回显到客户端

java使用Jsch/ssh2实现从linux服务端遍历文件名以及文件内容回显到客户端


这里只我上传的是测试类,需改下参数直接用就行。

jsch依赖:

  <dependency>
 
            <groupId>com.jcraft</groupId>
 
            <artifactId>jsch</artifactId>
 
            <version>0.1.51</version>
 
        </dependency>
 

/**
 * $Id: TranscodingAnalyzerDemo.java,v 1.0 2018/8/15 20:08 潘明生 Exp $
 * <p>
 * Copyright 2016 Asiainfo Technologies(China),Inc. All rights reserved.
 */
package com.asiainfo.emos.routine.ssh.down;
 
/**
 * @author 潘明生
 * @version $Id: TranscodingAnalyzerDemo.java,v 1.1 2018/8/15 20:08 潘明生 Exp $
 * Created on 2018/8/15 20:08
 */
 
import com.jcraft.jsch.*;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
 
public class TranscodingAnalyzer {
 
    private ChannelSftp channelSftp;
 
    private Session session = null;
 
    private int timeout = 60000;
 
    public TranscodingAnalyzer(SshConfiguration conf) throws JSchException {
 
        System.out.println("try connect to  " + conf.getHost() + ",username: " + conf.getUsername() + ",password: " + conf.getPassword() + ",port: " + conf.getPort());
 
        //创建JSch对象
        JSch jSch = new JSch();
 
        //根据用户名,主机ip和端口获取一个Session对象
        session = jSch.getSession(conf.getUsername(), conf.getHost(), conf.getPort());
 
        //设置密码
        session.setPassword(conf.getPassword());
 
        Properties config = new Properties();
 
        config.put("StrictHostKeyChecking", "no");
 
        //为Session对象设置properties
        session.setConfig(config);
 
        //设置超时
        session.setTimeout(timeout);
 
        //通过Session建立连接
        session.connect();
 
    }
 
    /**
     * 遍历文件名
     * @param directory
     * @return
     * @throws Exception
     */
    public List<String> listFiles(String directory) throws Exception {
        //通道
        channelSftp = (ChannelSftp) session.openChannel("sftp");
        //连接通道
        channelSftp.connect();
 
        Vector fileList;
 
        List<String> fileNameList = new ArrayList<String>();
 
        fileList = channelSftp.ls(directory);
 
        Iterator it = fileList.iterator();
 
        while (it.hasNext()) {
 
            String fileName = ((ChannelSftp.LsEntry) it.next()).getFilename();
 
            if (".".equals(fileName) || "..".equals(fileName)) {
 
                continue;
            }
 
            fileNameList.add(fileName);
            session.disconnect();
 
 
 
            channelSftp.quit();
        }
 
        return fileNameList;
 
    }
 
 
 
    public void close() {
 
        session.disconnect();
 
    }
 
    /**
     * 查看文件
     * @param src
     * @param filename
     * @return
     * @throws JSchException
     * @throws SftpException
     * @throws InterruptedException
     * @throws IOException
     */
 
    public String catFile(String src, String filename) throws JSchException, SftpException, InterruptedException, IOException {
 
        //通道
        channelSftp = (ChannelSftp) session.openChannel("sftp");
        //连接通道
        channelSftp.connect();
        StringBuffer sb = new StringBuffer();
        try {
            //String fileName = src.substring(src.lastIndexOf("/") + 1);
 
            //无论是文件夹还是文件打包下载
            //打开通道,设置通道类型,和执行的命令
            Channel channel = session.openChannel("exec");
            ChannelExec channelExec = (ChannelExec) channel;
 
            // String srcPath = src.substring(0, src.lastIndexOf("/"));
 
            //   filename = fileName + "_" + UUID.randomUUID().toString();
 
 
            //将"/" 的文件夹打包成名为/run/user/download/filename.zip
            String cmdGet = "cat " + filename;
            channelExec.setCommand("cd " + src + ";" + cmdGet);
 
            channelExec.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader
                    (channelExec.getInputStream()));
 
            channelExec.connect();
            String line = "";
 
 
            while ((line = input.readLine()) != null) {
 
                sb.append(line + "\n");
                System.out.println(line);// 打印控制台输出
                System.out.println("-------------------------------------分类---------------------");
 
            }
            System.out.println(sb);
 
            // 关闭通道
            channelExec.disconnect();
 
            input.close();
 
            //关闭session
            session.disconnect();
 
            channelSftp.quit();
 
        } catch (Exception e) {
            throw e;
        }
        return sb.toString();
 
    }
 
 
    /**
     * mian方法调用上面的方法即可实现,该对应参数就是了。
     * @param args
     */
 
    public static void main(String[] args)
 
    {
        SshConfiguration configuration=new SshConfiguration();
        configuration.setHost("10.4.8.51");
        configuration.setUsername("root");
        configuration.setPassword("root");
        configuration.setPort(22);//默认端口
        try{
            TranscodingAnalyzer sshUtil=new TranscodingAnalyzer(configuration);
            String directory = "/root/test_shell";
          //  List<String> listFilename = sshUtil.listFiles(directory);
 
 
        //    System.out.println(listFilename);
 
            String filename = "test1.sh";
            sshUtil.catFile(directory,filename);
 
            sshUtil.close();
        }catch(Exception e){
            e.printStackTrace();
        }
 
    }
 
 
 
 }
 

效果参考我这篇 https://blog.csdn.net/qq_39136928/article/details/82352015
————————————————
版权声明:本文为CSDN博主「潘丶」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_39136928/article/details/82352445
posted @ 2022-11-26 07:23  商君治国安邦之张莽  阅读(472)  评论(0编辑  收藏  举报