Samba (简体中文)

SambaSMB/CIFS 网络协议的重新实现, 可以在 Linux 和 Windows 系统间进行文件、打印机共享,和 NFS 的功能类似。本文介绍如何配置和使用 Samba.

翻译状态:本文是 Samba翻译。上次翻译日期:2020-05-06。如果英文版本有所更改,则您可以帮助同步翻译。

服务器

安装

安装 软件包 samba

Samba 服务的配置文件是 /etc/samba/smb.confsmb.conf(5)提供了详细的文档。

samba 软件包没有提供此文件,启动 smb.service 前需要先创建这个文件。从 这里 可以获取到示例文件。

从上面获取的默认配置文件里把日志log file设置到一个不能写的地方, 这会引起错误。下面的办法可以解决这个问题:

  • 把日志文件放到可写的路径: log file = /var/log/samba/%m.log
    • 把日志存到非文件后端的解决方案里: 配合 , 或者使用

如果需要的话; 在部份中指定的 workgroup 需要对应windows工作组的名称 (默认是 ).

提示: 修改 smb.conf 文件后,运行 testparm(1) 命令看看有没有语法错误。

配置防火墙

如果使用了 防火墙,请记得打开需要的端口(通常是 137-139 + 445). 完整列表请查看 Samba 端口使用

添加用户

Samba 需要 Linux 账户才能使用 - 可以使用已有账户或 创建新用户.

虽然用户名可以和 Linux 系统共享,Samba 使用单独的密码管理,将下面的 替换为选择的 Samba 用户:

# smbpasswd -a samba_user

根据 服务器角色 的差异,可能需要修改已有的 文件权限和属性

要让新创建的用户仅能访问 Samba 远程文件服务器,可以禁用其它登录选项

  • 禁用 shell -
  • 禁用 SSH logons - /etc/ssh/sshd_config, option

参阅Security

查询用户

用 命令查询现有用户:

# pdbedit -L -v

更改 samba 用户的密码

用 修改 samba 用户的密码:

# smbpasswd samba_user

创建共享

请确保 smb.conf.defaultShare Definitions 部分正确设置了共享。

启动服务

为了能够使用 SMB 进行基本的文件共享,start/enable 和 服务。更多信息参阅 smbdnmbd 的 man 手册。

并不总是需要启用。
提示: 除了在启动时启动服务,可以选择启用 smbd.socket,禁用 smb.service。这样的话会在第一次收到连接请求是启动后台进程。

建立 Usershare 路径

Usershares 让不具有 root 权限的用户可以进行添加、修改和删除自己的文件夹的操作。

以下操作将会在 添加 usershares 目录:

#mkdir /var/lib/samba/usershare

以下操作将会建立 sambashare 用户组:

#groupadd sambashare

以下操作将会将刚刚建立的文件夹的权限:拥有者更改为 root,群组更改为 sambashare:

# chown root:sambashare /var/lib/samba/usershare

以下的操作将会让 sambashare 群组中的用户拥有读取,写入和执行此文件夹中内容的权限:

# chmod 1770 /var/lib/samba/usershare

修改 配置文件中的以下变量:

将用户添加到群组 sambashare 中。其中,替换 为实际的用户名:

# usermod -a -G sambashare your_username

重启 和 服务。

注销后重新登陆,此时您应该就可以使用 GUI 程序配置您的 samba 共享服务了。例如,在 Thunar 中您可以右键点击任何一个文件夹将它在局域网中共享。如果你想共享自己主目录内的路径,需要主目录的内容让其它用户可以列出。

在命令行中,请使用下面命令, 替换掉 sharename, user, ... :

# net usershare add sharename abspath [comment] [user:{R|D|F}] [guest_ok={y|n}]
# net usershare delete sharename
# net usershare list wildcard-sharename
# net usershare info wildcard-sharename

Set and forcing permissions

Permissions may be applied to both the server and shares:

/etc/samba/smb.conf
[global]
  ;inherit owner = unix only ; Inherit ownership of the parent directory for new files and directories
  ;inherit permissions = yes ; Inherit permissions of the parent directory for new files and directories
  create mask = 0664
  directory mask = 2755
  force create mode = 0644
  force directory mode = 2755
  ...

[media]
  comment = Media share accessible by ''greg'' and ''pcusers''
  path = ''/path/to/media''
  valid users = ''greg @pcusers''
  force group = ''+pcusers''
  public = no
  writable = yes
  create mask = 0664
  directory mask = 2775
  force create mode = 0664
  force directory mode = 2775

[public]
  comment = Public share where ''archie'' has write access
  path = ''/path/to/public''
  public = yes
  read only = yes
  write list = ''archie''
  printable = no

[guests]
  comment = Allow all users to read/write
  path = ''/path/to/guests''
  public = yes
  only guest = yes
  writable = yes
  printable = no

See smb.conf(5) for a full overview of possible permission flags and settings.

Restrict protocols for better security

Append and in /etc/samba/smb.conf to force usage of a minimum and maximum protocol:

See in smb.conf(5) for an overview of supported protocols.

For compatibility with older clients and/or servers, you might need to set client min protocol = CORE or , but please note that this makes you vulnerable to exploits in SMB1 including ransomware attacks.

Clients using may need to specify the correct , e.g.:

# mount -t cifs //SERVER/sharename /mnt/mountpoint -o username=username,password=password,iocharset=utf8,vers=3.1.1

See for more information.

Restrict protocols for better security

Append and in /etc/samba/smb.conf to force usage of a minimum and maximum protocol:

See in smb.conf(5) for an overview of supported protocols.

For compatibility with older clients and/or servers, you might need to set client min protocol = CORE or , but please note that this makes you vulnerable to exploits in SMB1 including ransomware attacks.

Clients using may need to specify the correct , e.g.:

# mount -t cifs //SERVER/sharename /mnt/mountpoint -o username=username,password=password,iocharset=utf8,vers=3.1.1

See for more information.

Use native SMB transport encryption

Native SMB transport encryption is available in SMB version 3.0 or newer. Clients supporting this type of encryption include Windows 8 and newer, Windows server 2012 and newer, and smbclient of Samba 4.1 and newer.

To use native SMB transport encryption by default, set the parameter globally and/or by share. Possible values are , enabled (default value), , or :

/etc/samba/smb.conf
[global]
  smb encrypt = desired

See smb.conf(5) for more information, especially the paragraphs Effects for SMB1 and Effects for SMB2.

Disable printer sharing

By default Samba shares printers configured using CUPS.

If you do not want printers to be shared, use the following settings:

Block certain file extensions on Samba share

Samba offers an option to block files with certain patterns, like file extensions. This option can be used to prevent dissemination of viruses or to dissuade users from wasting space with certain files. More information about this option can be found in smb.conf(5).

Improve throughput

The default settings should be sufficient for most users. However setting the 'socket options' correct can improve performance, but getting them wrong can degrade it by just as much. Test the effect before making any large changes.

Read the smb.conf(5) man page before applying any of the options listed below.

The following settings should be append to the section of /etc/samba/smb.conf.

SMB3 multi-channel may improve performance, however it may result in data corruption under some race conditions. Future releases may improve this situation:

server multi channel support = yes

Setting a deadtime is useful to stop a server's resources being exhausted by a large number of inactive connections:

deadtime = 30

The usage of sendfile may make more efficient use of the system CPU's and cause Samba to be faster:

use sendfile = yes

The write cache allows Samba to batch client writes into a more efficient write size for RAID disks (i.e. writes may be tuned to be the RAID stripe size) and can improve performance on systems where the disk subsystem is a bottleneck but there is free memory for userspace programs:

write cache size = 262144

Setting min receivefile size allows zero-copy writes directly from network socket buffers into the filesystem buffer cache (if available). It may improve performance but user testing is recommended:

min receivefile size = 16384

Reading/writing files asynchronously may improve performance instead of using synchronously writes:

aio read size = 1
aio write size = 1

Increasing the receive/send buffers size and socket optimize flags might be useful to improve throughput. It is recommended to test each flag separately as it may cause issues on some networks:

socket options = IPTOS_LOWDELAY TCP_NODELAY IPTOS_THROUGHPUT SO_RCVBUF=131072 SO_SNDBUF=131072

客户端配置

如果不需要查询公开的共享,可以安装轻量级的 软件包,使用 /usr/bin/mount.cifs 命令挂载共享.

要使用类似 ftp 的命令行界面,请安装软件包 。常用命令请参考 。

桌面环境 可能提供了图形界面,参考#File manager configuration.

显示可用共享

下面命令会显示服务器上的可用共享:

$ smbclient -L hostname -U%

smbtree 可用显示共享目录树,不建议再有大量计算机的网络上使用此功能。可用它检查共享名是否可用。

$ smbtree -b -N
() 使用广播模式, (-no-pass) 不询问密码.

WINS 主机名

提供了一个用 WINS 解析主机名的驱动,要启用它,将 “wins” 添加到  /etc/nsswitch.conf 的 “hosts” 行。

手动挂载

创建共享挂载点:

# mkdir /mnt/mountpoint

使用 作为挂载类型 ,下面列出的选项并不是全部都需要:

# mount -t cifs //''SERVER''/''sharename'' /mnt/''mountpoint'' -o user=''username'',password=''password'',uid=''username'',gid=''group'',workgroup=''workgroup'',ip=''serverip'',iocharset=''utf8''

要允许用户挂载到自己可以访问的目录,请使用 挂载选项。

使用 和 挂载选项时,请注意 文件权限,否则会出现 I/O 错误。}}

SERVER

服务器名.

sharename

共享目录.

mountpoint

本地的挂载点.
详情请参考 .

保存共享密码

不建议将密码保存在所有人都可读的文件中,一个更安全的方式是创建密码文件:

username=myuser,password=mypass 替换为 .

修改密码文件的权限:

# chmod 600 /path/to/credentials/share

As mount entry

This is a simple example of a mount entry that requires authentication:

As systemd unit

Create a new .mount file inside , e.g. . See for details.

What= path to share

path to mount the share
share mounting options

To use , start the unit and enable it to run on system boot.

automount

To automatically mount a share, one may use the following automount unit:

Disable/stop the unit, and enable/start mnt-myshare.automount to automount the share when the mount path is being accessed.

smbnetfs

First, check if you can see all the shares you are interested in mounting:

$ smbtree -U remote_user

If that does not work, find and modify the following line in /etc/samba/smb.conf accordingly:

domain master = auto

Now restart and .

If everything works as expected, install from the official repositories.

Then, add the following line to /etc/fuse.conf:

user_allow_other

Now copy the directory to your home directory:

$ cp -a /etc/smbnetfs/.smb ~

Then create a link to :

$ ln -sf /etc/samba/smb.conf ~/.smb/smb.conf

If a username and a password are required to access some of the shared folders, edit to include one or more entries like this:

It is also possible to add entries for specific hosts to be mounted by smbnetfs, if necessary. More details can be found in .

If you are using the Dolphin or GNOME Files, you may want to add the following to to avoid "Disk full" errors as smbnetfs by default will report 0 bytes of free space:

When you are done with the configuration, you need to run

$ chmod 600 ~/.smb/smbnetfs.*

Otherwise, smbnetfs complains about 'insecure config file permissions'.

Finally, to mount your Samba network neighbourhood to a directory of your choice, call

$ smbnetfs mount_point
Daemon

The Arch Linux package also maintains an additional system-wide operation mode for smbnetfs. To enable it, you need to make the said modifications in the directory .

Then, you can start and/or enable the daemon as usual. The system-wide mount point is at .

autofs

See Autofs for information on the kernel-based automounter for Linux.

GNOME Files, Nemo, Caja, Thunar and PCManFM

In order to access samba shares through GNOME Files, Nemo, Caja, Thunar or PCManFM, install the gvfs-smb package, available in the official repositories.

Press and enter in the location bar to access your share.

The mounted share is likely to be present at or in the filesystem.

KDE

KDE has the ability to browse Samba shares built in. To use a GUI in the KDE System Settings, you will need to install the package.

If you get a "Time Out" Error when navigating with Dolphin, you should uncomment and edit the following line in smb.conf:

name resolve order = lmhosts bcast host wins

as shown in this page.

Other graphical environments

There are a number of useful programs, but they may need to have packages created for them. This can be done with the Arch package build system. The good thing about these others is that they do not require a particular environment to be installed to support them, and so they bring along less baggage.

  • is available in the official repositories.
  • LinNeighborhood, RUmba, xffm-samba plugin for Xffm are not available in the official repositories or the AUR. As they are not officially (or even unofficially supported), they may be obsolete and may not work at all.

Tips and tricks

Discovering network shares

If nothing is known about other systems on the local network, and automated tools such as smbnetfs are not available, the following methods allow one to manually probe for Samba shares.

1. First, install the and packages.

2. checks which ports are open:

# nmap -p 139 -sT "192.168.1.*"

In this case, a scan on the 192.168.1.* IP address range and port 139 has been performed, resulting in:

$ nmap -sT "192.168.1.*"
Starting nmap 3.78 ( http://www.insecure.org/nmap/ ) at 2005-02-15 11:45 PHT
Interesting ports on 192.168.1.1:
(The 1661 ports scanned but not shown below are in state: closed)
PORT     STATE SERVICE
'''139/tcp  open  netbios-ssn'''
5000/tcp open  UPnP

Interesting ports on 192.168.1.5:
(The 1662 ports scanned but not shown below are in state: closed)
PORT     STATE SERVICE
6000/tcp open  X11

Nmap run completed -- 256 IP addresses (2 hosts up) scanned in 7.255 seconds

The first result is another system; the second happens to be the client from where this scan was performed.

3. Now that systems with port 139 open are revealed, use to check for NetBIOS names:

Regardless of the output, look for <20>, which shows the host with open services.

4. Use to list which services are shared on PUTER. If prompted for a password, pressing enter should still display the list:

Remote control of Windows computer

Samba offers a set of tools for communication with Windows. These can be handy if access to a Windows computer through remote desktop is not an option, as shown by some examples.

Send shutdown command with a comment:

$ net rpc shutdown -C "comment" -I IPADDRESS -U USERNAME%PASSWORD

A forced shutdown instead can be invoked by changing -C with comment to a single -f. For a restart, only add -r, followed by a -C or -f.

Stop and start services:

$ net rpc service stop SERVICENAME -I IPADDRESS -U USERNAME%PASSWORD

To see all possible net rpc command:

$ net rpc

Troubleshooting

Failed to start Samba SMB/CIFS server

Possible solutions:

  • Check on syntactic errors with .
  • Set correct permissions for and restart :
# chmod 0755 /var/cache/samba/msg

Permission issues on AppArmor

If using a share path located outside of a home-directory, whitelist it in /etc/apparmor.d/local/usr.sbin.smbd. E.g.:

No dialect specified on mount

The client is using an unsupported SMB/CIFS version that is required by the server.

See #Restrict protocols for better security for more information.

Unable to overwrite files, permissions errors

Possible solutions:

  • Append the mount option to the entry.
  • Add to the section of the server's /etc/samba/smb.conf.

Windows clients keep asking for password even if Samba shares are created with guest permissions

Set map to guest inside the section of /etc/samba/smb.conf:

map to guest = Bad User

From Samba 4.10.10 you should use instead .

Windows 7 connectivity problems - mount error(12): cannot allocate memory

A known Windows 7 bug that causes "mount error(12): cannot allocate memory" on an otherwise perfect cifs share on the Linux end can be fixed by setting a few registry keys on the Windows box as follows:

  • (set to 1)
  • (set to )

Alternatively, start Command Prompt in Admin Mode and execute the following:

reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" /v "LargeSystemCache" /t REG_DWORD /d 1 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters" /v "Size" /t REG_DWORD /d 3 /f

Do one of the following for the settings to take effect:

  • Restart Windows
  • Restart the Server service via services.msc
  • From the Command Prompt run: 'net stop lanmanserver' and 'net start lanmanserver' - The server may automatically restart after stopping it.

Original article.

Windows 10 1709 and up connectivity problems - "Windows cannot access" 0x80004005

This error affects some machines running Windows 10 version 1709 and later. It is not related to SMB1 being disabled in this version but to the fact that Microsoft disabled insecure logons for guests on this version for some, but not others.

To fix, open Group Policy Editor (). Navigate to Computer configuration\administrative templates\network\Lanman Workstation > Enable insecure guest logons and enable it. Alternatively,change the following value in the registry:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters]
"AllowInsecureGuestAuth"=dword:1

Error: Failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL

If you are a home user and using samba purely for file sharing from a server or NAS, you are probably not interested in sharing printers through it. If so, you can prevent this error from occurring by adding the following lines to your /etc/samba/smb.conf:

Restart the samba service, , and then check your logs:

# cat /var/log/samba/smbd.log

and the error should now no longer be appearing.

Sharing a folder fails

It means that while you are sharing a folder from Dolphin (file manager) and everything seems ok at first, after restarting Dolphin the share icon is gone from the shared folder, and also some output like this in terminal (Konsole) output:

‘net usershare’ returned error 255: net usershare: usershares are currently disabled

To fix it, enable usershare as described in #建立 Usershare 路径.

"Browsing" network fails with "Failed to retrieve share list from server"

And you are using a firewall (iptables) because you do not trust your local (school, university, hotel) network. This may be due to the following: When the smbclient is browsing the local network it sends out a broadcast request on udp port 137. The servers on the network then reply to your client but as the source address of this reply is different from the destination address iptables saw when sending the request for the listing out, iptables will not recognize the reply as being "ESTABLISHED" or "RELATED", and hence the packet is dropped. A possible solution is to add:

iptables -t raw -A OUTPUT -p udp -m udp --dport 137 -j CT --helper netbios-ns

to your iptables setup.

Protocol negotiation failed: NT_STATUS_INVALID_NETWORK_RESPONSE

The client probably does not have access to shares. Make sure clients' IP address is in line in /etc/samba/smb.conf.

Another problem could be, that the client uses an invalid protocol version. To check this try to connect with the where you specify the maximum protocol version manually:

$ smbclient -U <user name> -L //<server name> -m <protocol version: e. g. SMB2> -W <domain name>

If the command was successful then create a configuration file:

~/.smb/smb.conf
[global]
  workgroup = <domain name>
  client max protocol = SMB2

Connection to SERVER failed: (Error NT_STATUS_UNSUCCESSFUL)

You are probably passing a wrong server name to . To find out the server name, run on the server and look at "Transient hostname" line

Connection to SERVER failed: (Error NT_STATUS_CONNECTION_REFUSED)

Make sure that the server has started. The shared directories should exist and be accessible.

Protocol negotiation failed: NT_STATUS_CONNECTION_RESET

Probably the server is configured not to accept protocol SMB1. Add option in /etc/samba/smb.conf. Or just pass argument to .

Password Error when correct credentials are given (error 1326)

Samba 4.5 has NTLMv1 authentication disabled by default. It is recommend to install the latest available upgrades on clients and deny access for unsupported clients.

If you still need support for very old clients without NTLMv2 support (e.g. Windows XP), it is possible force enable NTLMv1, although this is not recommend for security reasons:

If NTLMv2 clients are unable to authenticate when NTLMv1 has been enabled, create the following file on the client:

/home/user/.smb/smb.conf
[global]
  sec = ntlmv2
  client ntlmv2 auth = yes

This change also affects samba shares mounted with mount.cifs. If after upgrade to Samba 4.5 your mount fails, add the sec=ntlmssp option to your mount command, e.g.

mount.cifs //server/share /mnt/point -o sec=ntlmssp,...

See the man page: ntlmssp - Use NTLMv2 password hashing encapsulated in Raw NTLMSSP message. The default in mainline kernel versions prior to v3.8 was sec=ntlm. In v3.8, the default was changed to sec=ntlmssp.

Mapping reserved Windows characters

Starting with kernel 3.18, the cifs module uses the "mapposix" option by default. When mounting a share using unix extensions and a default Samba configuration, files and directories containing one of the seven reserved Windows characters are listed but cannot be accessed.

Possible solutions are:

  • Use the undocumented mount option for cifs
 # mount.cifs //server/share /mnt/point -o nomapposix
  • Configure Samba to remap ("SFM", Services for Mac) style characters to the correct native ones using fruit
  • Manually remap forbidden characters using catia

The latter approach (using catia or fruit) has the drawback of filtering files with unprintable characters.

Folder shared inside graphical environment is not available to guests

This section presupposes:

  1. Usershares are configured following previous section
  2. A shared folder has been created as a non-root user from GUI
  3. Guests access has been set to shared folder during creation
  4. Samba service has been restarted at least once since last /etc/samba/smb.conf file modification

For clarification purpose only, in the following sub-sections is assumed:

  • Shared folder is located inside user home directory path ()
  • Shared folder name is MySharedFiles
  • Guest access is read-only.
  • Windows users will access shared folder content without login prompt

Verify correct samba configuration

Run the following command from a terminal to test configuration file correctness:

$ testparm

Verify correct shared folder creation

Run the following commands from a terminal:

$ cd /var/lib/samba/usershare
$ ls

If everything is fine, you will notice a file named mysharedfiles

Read the file contents using the following command:

$ cat mysharedfiles

The terminal output should display something like this:

Verify folder access by guest

Run the following command from a terminal. If prompted for a password, just press Enter:

$ smbclient -L localhost

If everything is fine, MySharedFiles should be displayed under column

Run the following command in order to access the shared folder as guest (anonymous login)

$ smbclient -N //localhost/MySharedFiles

If everything is fine samba client prompt will be displayed:

smb: \>

From samba prompt verify guest can list directory contents:

smb: \> ls

If error displayed, probably there is something to be solved at directory permission level.

Run the following commands as root to set correct permissions for folders:

# cd /home
# chmod -R 755 /home/yourUser/Shared

Access shared folder again as guest to be sure guest read access error has been solved.

Mount error: Host is down

This error might be seen when mounting shares of Synology NAS servers. Use the mount option to solve it.

Software caused connection abort

File managers that utilizes gvfs-smb can show the error Software caused connection abort when writing a file to a share/server. This may be due to the server running SMB/CIFS version 1, which many routers use for USB drive sharing (e.g. Belkin routers). To write to these shares specify the CIFS version with the option . E.g.:

This can also happen after updating Samba to version 4.11, which deactivates SMB1 as default, and accessing any Samba share. You can reenable it by adding

Connection problem (due to authentification error)

Be sure that you do not leave any space characters before your username in Samba client configuration file as follows:

The correct format is:

See also

This article is issued from Archlinux. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.