Linux下smb服务搭建与Java开发smb协议相关接口实现

一、Linux下搭建smb服务

1、安装服务
# yum install samba samba-common -y
# useradd -s /sbin/nologin george --创建samba服务登录用户
# smbpasswd -a george --将用户 george 设置为smb用户,并增加密码;修改密码时不用加 -a 参数,george必须是系统已经拥有的用户
# smbpasswd -x u1 --删除用户
# smbpasswd -d u1 --禁用用户
# smbpasswd -e u1 --启用用户
# pdbedit -L --列出所有用户
# pdbedit -Lv --列出所有用户的详细信息
# pdbedit -Lv george --列出用户 george 的详细信息

2、配置文件  /etc/samba/smb.conf
#######在最下端添加
[share]                        --共享名称
  path = /share                --共享路径
  write list = harry           --指定可以读写的用户
  
3、重启服务
service smb restart

二、smb.conf示例

[global]
display charset = UTF8
dos charset = cp950
unix charset = UTF8
log file = /var/log/samba/log.%m
max log size = 50
security = user
map to guest = Bad User
passdb backend = tdbsam
load printers = no
username map = /etc/samba/smbusers

[printers]
comment = All Printers
path = /var/tmp
printable = Yes
create mask = 0600
browseable = No

[print$]
comment = Printer Drivers
path = /var/lib/samba/drivers
write list = @printadmin root
force group = @printadmin
create mask = 0664
directory mask = 0775


[v213735532343]
comment=export of v213735532343
path=/nfs/v213735532343
writable=yes
browseable=no
posix locking=no
valid users=%U
hide unreadable = yes

 

三、Java开发smb协议相关接口

1.在pom.xml文件夹中添加如下的依赖

<dependency>
       <groupId>jcifs</groupId>
       <artifactId>jcifs</artifactId>
       <version>1.3.17</version>
</dependency>

2.交互代码

import jcifs.smb.*;
import java.io.*;
import java.net.MalformedURLException;

/**
 * @program: smbTest
 * @description:
 * @author:hw
 * @create: 2020-10-09 16:40
 */
public class SmbTest {
    public static void main(String[] args) {
        //smb访问的基本格式:smb:域名;用户名:密码@目的IP/文件夹/文件名.xxx
        //如果密码中有“@”这种特殊字符导致无法识别,需要采用NtlmPasswordAuthentication登录认证
//        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("192.168.212.232", "hwtest", "123456"); // 先登录验证
//        SmbFile smbFile = new SmbFile(remoteUrl,auth);

        String remoteUrl = "smb://hwtest:123456@192.168.212.232/hwtest/";

        //创建文件夹
        smbMkdir(remoteUrl,"test");

        //读取共享文件夹下的所有文件(文件夹)的名称
//        remoteUrl = remoteUrl + "test/";
//        getSharedFileList(remoteUrl);

        //上传文件
//        String shareFolderPath = "test";
//        String localFilePath = "C:\Users\Administrator\Desktop\51.png";
//        String fileName = "1.png";
//        uploadFileToSmb(remoteUrl,shareFolderPath,localFilePath,fileName);

        //下载文件到指定文件夹
//        String shareFolderPath = "test";
//        String fileName = "1.png";
//        String localDir = "C:\Users\Administrator\Desktop";
//        downloadFileToFolder(remoteUrl,shareFolderPath,fileName,localDir);

        //删除文件
//        String shareFolderPath = "test";
//        String fileName = "1.png";
//        deleteFile(remoteUrl,shareFolderPath,fileName);
    }

    /**
    * @Description: 创建文件夹
    * @Param:
    * @return:
    * @throws Exception
    * @author: hw
    * @date: 2020/10/9 16:51
    */
    public static void smbMkdir(String remoteUrl, String folderName) {
        SmbFile smbFile;
        try {
            // smb://userName:passWord@host/path/folderName
            smbFile = new SmbFile(remoteUrl + folderName);
            if (!smbFile.exists()) {
                smbFile.mkdir();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 读取共享文件夹下的所有文件(文件夹)的名称
     * @Param:
     * @return:
     * @throws Exception
     * @author: hw
     * @date: 2020/10/9 16:42
     */
    public static void getSharedFileList(String remoteUrl) {
        SmbFile smbFile;
        try {
            // smb://userName:passWord@host/path/
            smbFile = new SmbFile(remoteUrl);
            if (!smbFile.exists()) {
                System.out.println("no such folder");
            } else {
                SmbFile[] files = smbFile.listFiles();
                for (SmbFile f : files) {
                    System.out.println(f.getName());
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }

    /**
    * @Description: 上传文件
    * @Param:
    * @return:
    * @throws Exception
    * @author: hw
    * @date: 2020/10/9 17:21
    */
    public static void uploadFileToSmb(String remoteUrl, String shareFolderPath, String localFilePath, String fileName) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File localFile = new File(localFilePath);
            inputStream = new FileInputStream(localFile);
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            SmbFile smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            smbFile.connect();
            outputStream = new SmbFileOutputStream(smbFile);
            byte[] buffer = new byte[4096];
            int len = 0; // 读取长度
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 刷新缓冲的输出流
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
    * @Description: 下载文件到指定文件夹
    * @Param:
    * @return:
    * @throws Exception
    * @author: hw
    * @date: 2020/10/9 17:21
    */
    public static void downloadFileToFolder(String remoteUrl, String shareFolderPath, String fileName, String localDir) {
        InputStream in = null;
        OutputStream out = null;
        boolean flag = false;
        try {
            SmbFile remoteFile = new SmbFile(remoteUrl + shareFolderPath + File.separator + fileName);
            if (!remoteFile.exists()) {
               System.out.println("要下载的文件不存在");
            }else {
                flag = true;
                File localFile = new File(localDir + File.separator + fileName);
                in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
                out = new BufferedOutputStream(new FileOutputStream(localFile));
                byte[] buffer = new byte[1024];
                while (in.read(buffer) != -1) {
                    out.write(buffer);
                    buffer = new byte[1024];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(flag){
                try {
                    out.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @Description: 删除文件
     * @Param:
     * @return:
     * @throws Exception
     * @author: hw
     * @date: 2020/10/9 17:21
     */
    public static void deleteFile(String remoteUrl, String shareFolderPath, String fileName) {
        SmbFile SmbFile;
        try {
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            SmbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            if (SmbFile.exists()) {
                SmbFile.delete();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }
}

3.通过浏览器交互代码

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.net.UnknownHostException;

/**
 * @program: smbTest
 * @description:
 * @author: hw
 * @create: 2020-10-09 17:12
 */
@RestController
public class SmbController {
    /**
    * @Description: smb文件下载
    * @Param:
    * @return:
    * @throws Exception
    * @author: hw
    * @date: 2020/10/9 17:16
    */
    @GetMapping(value = "/smb")
    public static void downloadFileToBrowser(HttpServletResponse httpServletResponse,
                                             @RequestParam(name = "remoteUrl") String remoteUrl,
                                             @RequestParam(name = "shareFolderPath") String shareFolderPath,
                                             @RequestParam(name = "fileName") String fileName) {
        SmbFile smbFile;
        SmbFileInputStream smbFileInputStream = null;
        OutputStream outputStream = null;
        boolean flag = false;
        try {
            // smb://userName:passWord@host/path/shareFolderPath/fileName
            smbFile = new SmbFile(remoteUrl + shareFolderPath + "/" + fileName);
            if (!smbFile.exists()) {
                System.out.println("要下载的文件不存在");
            }else {
                flag = true;
                smbFileInputStream = new SmbFileInputStream(smbFile);
                httpServletResponse.setHeader("content-type", "application/octet-stream");
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=UTF-8");
                httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + fileName);
                // 处理空格转为加号的问题
                httpServletResponse.setHeader("Content-Disposition", "attachment; fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\+", "%20"));
                outputStream = httpServletResponse.getOutputStream();
                byte[] buff = new byte[2048];
                int len;
                while ((len = smbFileInputStream.read(buff)) != -1) {
                    outputStream.write(buff, 0, len);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(flag){
                try {
                    outputStream.close();
                    smbFileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  

原文地址:https://www.cnblogs.com/weihuang6620/p/13786997.html