If you work with different operating systems, it’s handy to be able to share files between them. This article explains how to set up file access between Linux (Fedora 33) and Windows 10 using Samba and mount.cifs.
Samba is the Linux implementation of the SMB/CIFS protocol, allowing direct access to shared folders and printers over a network. Mount.cifs is part of the Samba suite and allows you to mount the CIFS filesystem under Linux.
Caution: These instructions are for sharing files within your private local network or in a virtualized host-only network between a Linux host machine and a virtualized Windows guest. Don’t consider this article a guideline for your corporate network, as it doesn’t implement the necessary cybersecurity considerations.
Access Linux from Windows
This section explains how to access a user’s Linux home directory from Windows File Explorer.
1. Install and configure Samba
Start on your Linux system by installing Samba:
dnf install samba
Samba is a system daemon, and its configuration file is located in /etc/samba/smb.conf
. Its default configuration should work. If not, this minimal configuration should do the job:
[global]
workgroup = SAMBA
server string = %h server (Samba %v)
invalid users = root
security = user
[homes]
comment = Home Directories
browseable = no
valid users = %S
writable = yes
You can find a detailed description of the parameters in the smb.conf section of the project’s website.
2. Modify LinuxSE
If your Linux distribution is protected by SELinux (as Fedora is), you have to enable Samba to be able to access the user’s home directory:
setsebool -P samba_enable_home_dirs on
Check that the value is set by typing:
getsebool samba_enable_home_dirs
Your output should look like this:
3. Enable your user
Samba uses a set of users and passwords that have permission to connect. Add your Linux user to the set by typing:
smbpasswd -a <your-user>
You will be prompted for a password. This is a completely new password; it is not the current password for your account. Enter the password you want to use to log in to Samba.
To get a list of allowed user types:
pdbedit -L -v
Remove a user by typing:
smbpasswd -x <user-name>
4. Start Samba
Because Samba is a system daemon, you can start it on Fedora with:
systemctl start smb
This starts Samba for the current session. If you want Samba to start automatically on system startup, enter:
systemctl enable smb
On some systems, the Samba daemon is registered as smbd
.
4. Configure the firewall
By default, Samba is blocked by your firewall. Allow Samba to access the network permanently by configuring the firewall.
You can do it on the command line with:
firewall-cmd --add-service=samba --permanent
Or you do it graphically with the firewall-config tool:
5. Access Samba from Windows
In Windows, open File Explorer. On the address line, type in two backslashes followed by your Linux machine’s address (IP address or hostname):
You will be prompted for your login information. Type in the username and password combination from step 3. You should now be able to access your home directory on your Linux machine:
Access Windows from Linux
The following steps explain how to access a shared Windows folder from Linux. To implement them, you need Administrator rights on your Windows user account.
1. Enable file sharing
Open the Network and Sharing Center either by clicking on the
Windows Button > Settings > Network & Internet
or by right-clicking the little monitor icon on the bottom-right of your taskbar:
In the window that opens, find the connection you want to use and note its profile. I used Ethernet 3, which is tagged as a Public network.
Caution: Consider changing your local machine’s connection profile to Private if your PC is frequently connected to public networks.
Remember your network profile and click on Change advanced sharing settings:
Select the profile that corresponds to your connection and turn on network discovery and file and printer sharing:
2. Define a shared folder
Open the context menu by right-clicking on the folder you want to share, navigate to Give access to, and select Specific people… :
Check whether your current username is on the list. Click on Share to tag this folder as shared:
You can display a list of all shared folders by entering \\localhost
in File Explorer’s address line:
Image by:
<p class=»rtecenter»><sup>(Stephan Avenwedde, <a href=»https://opensource.com/%3Ca%20href%3D»https://creativecommons.org/licenses/by-sa/4.0/» rel=»ugc»>https://creativecommons.org/licenses/by-sa/4.0/» target=»_blank»>CC BY-SA 4.0</a>)</sup></p>
3. Mount the shared folder under Linux
Go back to your Linux system, open a command shell, and create a new folder where you want to mount the Windows share:
mkdir ~/WindowsShare
Mounting Windows shares is done with mount.cifs, which should be installed by default. To mount your shared folder temporarily, use:
sudo mount.cifs //<address-of-windows-pc>/MySharedFolder ~/WindowsShare/ -o user=<Windows-user>,uid=$UID
In this command:
<address-of-windows-pc>
is the Windows PC’s address info (IP or hostname)<Windows-user>
is the user that is allowed to access the shared folder (from step 2)
You will be prompted for your Windows password. Enter it, and you will be able to access the shared folder on Windows with your normal Linux user.
To unmount the shared folder:
sudo umount ~/WindowsShare/
You can also mount a Windows shared folder on system startup. Follow these steps to configure your system accordingly.
Summary
This shows how to establish temporary shared folder access that must be renewed after each boot. It is relatively easy to modify this configuration for permanent access. I often switch back and forth between different systems, so I consider it incredibly practical to set up direct file access.
This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.
Contents
-
Client Access — Browsing SMB shares
- Ubuntu Clients
- Windows Clients (XP,Server,Vista, Win7)
-
Samba Client — Manual Configuration
- Connecting using CIFS
- Connecting using SMBFS (deprecated)
The samba package is a meta-package intended to be installed on file and printer sharing servers. Clients do not need this meta-package (you are acting as a client if you need to access files on another computer). For example, installing samba is not necessary if you only need your Ubuntu system to do any of the following:
-
Access shared folders, drives and printers on a Windows computer (that is, act as a client with Windows servers). To do this, you only need the smbfs plugin. See MountWindowsSharesPermanently for more information.
- Have your Windows computer use (via a network) a printer that is attached to a Linux computer. CUPS can be configured to make the printer accessible to the network.
-
Share directories between two Linux computers. You can use NFS or setup an SSH server on one computer and access it from other computers using an scp or sftp client, or Places -> Connect to Server… and choose «SSH» as the service type.
Ubuntu Clients
Ubuntu and Gnome make it easy to access files on a Windows network share. Open the Places Menu, then click on Network. You will see a Windows network icon. Double-click to open it. The next window shows all the domains/workgroups found on your network. Inside each domain/workgroup you will see all the computers on the domain/workgroup with sharing enabled. Double-click on a computer icon to access its shares and files.
-
If you want to be able to share folders with nautilus (the file browser), install the nautilus-share package (installed by default in Ubuntu 9.10 Desktop edition):
sudo apt-get install nautilus-share
Alternate: From the menu at the top select «Location» -> «Connect to a server». In the «Service type» pull down select «Windows share». Enter the server ip address in the «Server:» box and the share name in the «Share:» box. Click «Connect» and then «Connect» again on the second dialog box
Alternate 12.04: Double clicking on ‘Windows network’ did not work for me. So I went to ‘Go’ menu in the nautilus file browser and clicked ‘Location’. I got an address bar at the top of the window. I entered «smb://192.168.2.148» (substitute the IP address of your Samba server) — I was presented with user/password window — After typing in user/passwd I was able to see the samba shares on the server and browse the files/folders.
Note: The default installation of Samba does not synchronize passwords. You may have to run «smbpasswd» for each user that needs to have access to his Ubuntu home directory from Microsoft Windows.
Windows Clients (XP,Server,Vista, Win7)
Microsoft Windows clients connect and browse through their corresponding network interface.
Example: XP clients can open Windows Network Neighborhood or My Network Places to browse available SMB shares.
Samba Client — Manual Configuration
This section covers how to manually configure and connect to a SMB file server from an Ubuntu client. smbclient is a command line tool similar to a ftp connection while smbfs allows you to mount a SMB file share. Once a SMB share is mounted it acts similar to a local hard drive (you can access the SMB share with your file browser (nautilus, konqueror, thunar, other).
Connecting to a Samba File Server from the command line
Connecting from the command line is similar to a ftp connection.
List public SMB shares with
smbclient -L //server -U user
Connect to a SMB share with
smbclient //server/share -U user
Enter you user password.
You can connect directly with
smbclient //server/share -U user%password
but your password will show on the screen (less secure).
Once connected you will get a prompt that looks like this :
smb: \>
Type «help» , without quotes, at the prompt for a list of available commands.
Connecting using CIFS
CIFS is included in the smbfs package and is a replacement for smbfs (I know, the terminology here is a little confusing).
Reference : http://linux-cifs.samba.org/
As above, install by any method, smbfs, on Ubuntu 12.10, smbfs has been replaced by cifs-utils.
Allow non-root users to mount SMB shares
By default only root may mount SMB shares on the command line. To allow non-root users to mount SMB shares you could set the SUID, but I advise you configure sudo. You should configure sudo with visudo
You may either allow the group «users» to mount SMB shares, or add a group, samba, and add users you wish to allow to mount SMB shares to the samba group.
sudo groupadd samba sudo adduser user samba
Change «user» to the username you wish to add to the samba group.
sudo visudo
In the «group» section add your group you wish to allow to mount SMB shares
Add a line in the "group" section : ## Members of the admin group may gain root privileges %admin ALL=(ALL) ALL %samba ALL=(ALL) /bin/mount,/bin/umount,/sbin/mount.cifs,/sbin/umount.cifs
Change «%samba» to «%users» if you wish to allow members of the users group to mount SMB shares.
The following will mount the myshare folder on myserver to ~/mnt (it will be in your home directory):
mkdir ~/mnt sudo mount -t cifs //myserver_ip_address/myshare ~/mnt -o username=samb_user,noexec
Note: «samba_user» = the user name on the samba server (may be different from your log-in name on the client).
The «noexec» option prevents executable scripts running from the SMB share.
You will be asked for BOTH your sudo and then your samba_user password.
To umount,
sudo umount ~/mnt
Automagically mount SMB shares
In order to have a share mounted automatically every time you reboot, you need to do the following:
With any editor, create a file containing your Windows/Samba user account details:
gksu gedit /etc/samba/user
KDE users must use kdesu rather than gksu and instead of Gedit they can use Kwrite as editor.
… it should contain two lines as follows:
username=samba_user password=samba_user_password
Note: «samba_user» = the user name on the samba server (may be different from your log-in name on the client). «samba_user_password» is the password you assigned to the samba_user on the samba server.
Save the file and exit gedit.
Change the permissions on the file for security:
sudo chmod 0400 /etc/samba/user # permissions of 0400 = read only
Now create a directory where you want to mount your share (e.g. /media/samba_share):
sudo mkdir /media/samba_share
Now, using any editor, and add a line to /etc/fstab for your SMB share as follows:
sudo cp /etc/fstab /etc/fstab.bak gksu gedit /etc/fstab
Add a line for your SMB share:
//myserver_ip_address/myshare /media/samba_share cifs credentials=/etc/samba/user,noexec 0 0
The share will mount automatically when you boot. The «noexec» option prevents executable scripts running from the SMB share.
To mount the share now, without rebooting,
sudo mount /media/samba_share
You can unmount the share with :
sudo umount /media/samba_share
If you wish to increase security at the expense of convenience, use this line in /etc/fstab
//myserver_ip_address/myshare /media/samba_share cifs noauto,credentials=/etc/samba/user,noexec 0 0
The noexec» option prevents executable scripts running from the SMB share.
Edit /etc/samba/user, remove the password (leave just the samba user).
Now the share will NOT automatically mount when you boot and you will be asked for your samba password.
Mount the share with :
sudo mount /media/samba_share
CIFS may cause a shutdown error.
CIFS VFS: Server not responding.
There is a fix in the troubleshooting section of this forum post.
Back to top
Connecting using SMBFS (deprecated)
Note: This method still works, but as outlined under the «CIFS» section above is «deprecated» (no longer maintained and pending removal from the kernel).
Mounting a share on the local filesystem allows you to work around programs that do not yet use GnomeVFS to browse remote shares transparently. To mount a SMB share, first install smbfs:
sudo apt-get update sudo apt-get install smbfs
To allow non root accounts to mount shares, change the permissions on the smbmnt program thus:
sudo chmod u+s /usr/bin/smbmnt /usr/bin/smbumount
Note: This may be a security risk as after setting the SUID bit anyone can mount a SMB share. I advise you configure sudo, as above.
The working line in /etc/sudoers is as follows (see CIFS section above):
%samba ALL=(ALL) /bin/mount,/bin/umount,/sbin/mount.cifs,/sbin/umount.cifs,/usr/bin/smbmount,/usr/bin/smbumount
This allows any user in the samba group to mount SMB shares (you will need to create a samba group and add users).
The following will mount the myshare folder on myserver to ~/mnt (it will be in your home directory):
mkdir ~/mnt smbmount //myserver/myshare ~/mnt
To umount,
smbumount ~/mnt
In order to have a share mounted automatically every time you reboot, you need to do the following:
Open a shell as root
sudo -s
Create a file containing your Windows/Samba user account details:
vi /etc/samba/user
…it should contain two lines as follows:
username=george password=secret
Change the permissions on the file for security:
chmod 0600 /etc/samba/user
Now create a directory where you want to mount your share (e.g. /mnt/data):
mkdir /mnt/data
Now edit the file system table (/etc/fstab) and add a line as follows:
//server/share /mnt/data smbfs credentials=/etc/samba/user,rw,uid=bob 0 0
…where ‘bob’ is the non-root user you log into ubuntu with, ‘server’ is the name or address of the Windows machine and ‘share’ is the name of the share.
To mount the share now, just use the following command as root. It will mount automatically on subsequent reboots.
mount /mnt/data
to be continued…
Ubuntu Client
On the Ubuntu client using the menu at the top, go to «Places» -> «Network». You will see an icon «Windows network» and should be able to browse to your shared folder. You will be asked for a password, leave it blank. Click the «Connect button.
(no need for a password).
If you would like to mount your SMB share using your (server) hostname rather than the IP Address, edit /etc/hosts and add your samba server (syntax IP Address hostname).
192.168.1.100 hostname
Where «hostname» = the name of your samba server.
Windows Client
On Windows open «My Computer» and navigate to «My Network Places». Navigate to your Ubuntu server and your share will be available without a password.
Alternate : From the menu at the top select «Tools» -> «Map Network Drive». Select an available letter for your SMB share (Default is z: ). In the «Folder:» box enter \\samba_server_ipaddress\share. Tic (Select with the mouse) the option «Reconnect at login» if you want the share to be automatically mounted when you boot Windows. Click the «Finish» box. A dialog box will appear, enter your samba user name and password. Click «OK».
If you would like to mount your SMB share using your (server) hostname rather than the IP Address, edit C:\WINDOWS\system32\drivers\etc\hosts and add your samba server (syntax IP Address hostname).
192.168.1.100 hostname
Where «hostname» = the name of your samba server.
Updated: 03/12/2022 by
The easiest and most reliable way to share files between a Linux and Windows computer on the same local area network is to use the Samba file-sharing protocol. All modern versions of Windows come with Samba installed, and Samba is installed by default on most distributions of Linux.
Create a shared folder on Windows
First, create a shared folder on your Windows computer.
Note
Following the steps below, creates a shared folder on your Windows computer that lets you access files in that folder on your Linux computer. With the right permissions you can also copy, edit, and delete files in that folder from your Linux computer.
- Open the Control Panel.
- Select the Network and Sharing Options or Network and Sharing Center option.
- Click the Change advanced sharing settings link in the left navigation menu.
- Click the Turn on Network Discovery and Turn on File and Print Sharing options.
- Click the Save changes button at the bottom of the Advanced sharing settings window.
Now, create a new folder to share or choose an existing folder that you want to share.
- Right-click the folder and select Properties.
- Go to the Sharing tab.
- To share the folder with another Windows account, click the Share button, add the account to grant permission to access the shared folder, and click the Share button.
Note
If you shared the folder with another Windows account, you need to click the Advanced Sharing button, then click the Permissions button. Select the account, check the Allow box for the Change or Modify permission, and click OK.
- Click the Advanced Sharing button.
- On the Advanced Sharing window, check the box for Share this folder and click OK.
- The network path for the folder is now displayed above the Share button, indicating that it is now a shared folder. For example, it may look like \\YOURCOMPUTERNAME\Users\YourUserName\ShareFolderName. Make a note of this network folder path to use later on your Linux machine.
Access a Windows shared folder from Linux using Konqueror
Many Linux distributions use the KDE (K Desktop Environment) and the Konqueror file manager/browser. If you’re using this, you can follow these steps to access your Windows shared folder.
- Click the K menu icon.
- Select Internet -> Konqueror.
- In the Konqueror window that opens, click the Network Folders link, or type remote:/ in the address bar and press Enter.
- Click the Samba Shares icon.
- Click the icon of your Windows Home workgroup.
- Click the Workgroup icon.
- Click the icon for your computer.
- When prompted, enter the username and password for the Windows account that created the share.
- Click OK.
Access a Windows shared folder from Linux using Nautilus
Many Linux distributions, especially those that use the GNOME desktop environment, use the Nautilus file manager. If you’re using this, you can follow these steps to access your Windows shared folder.
- Open Nautilus.
- From the File menu, select Connect to Server.
- In the Service type drop-down box, select Windows share.
- In the Server field, enter the name of your computer.
- Click Connect.
Alternatively, in the Nautilus address bar, you can type smb://ComputerName/ShareName and press Enter. For example, when you created your Windows Share if the share name was listed as:
\\YOURCOMPUTERNAME\Users\YourUserName\ShareFolderName
Type smb://YOURCOMPUTERNAME/Users/YourUserName/ShareFolderName and press Enter. Note the smb: at the beginning, in Linux, use forward slashes instead of backslashes.
Access a Windows shared folder from Linux using the command line
You can also access your Windows shared folder from the Linux command line using the smbclient program.
- Open a terminal.
- Type smbclient at the command prompt.
- If you receive a «Usage:» message, smbclient is installed, and you can skip to the next step. However, if the command is not found, you need to install smbclient. Follow these steps to install it.
- If you use the apt package manager, the default on Linux systems such as Ubuntu or Debian, you can use the sudo apt-get install smbclient command.
- If you use the yum package manager, the default on Linux systems, such as CentOS, you can use the sudo yum install samba-client command.
- You can also download the Samba client directly at www.samba.org/samba/download/, which might be useful to you if you need or want to compile the program from the source code.
- With smbclient installed, you can connect to your Windows share using the command smbclient //ComputerName/ShareName -U Username. For instance, if your Windows username is Fred, and your Windows share network name is \\YOURCOMPUTERNAME\Users\YourUserName\ShareFolderName, use the command smbclient //YOURCOMPUTERNAME/Users/YourUserName/ShareFolderName -U Fred. Notice that the Linux command uses forward slashes instead of backslashes).
- Enter your password.
- Once authenticated, you are placed at an smb: \> prompt.
- Here, you can use the ls or dir command to list files.
- Use the command get filename.ext to transfer a file named filename.ext from your Windows share to your Linux machine, for example. If the file name contains spaces, make sure to enclose it in double quotes, for example: get «My new file.txt».
- Type help for a listing of further commands.
- Type quit or exit to return to the command prompt.
Your home network might have a few Windows machines on the ground floor, a Mac in an upstairs bedroom, a PocketPC on a nightstand, and a Linux box or two in the basement, all networked with a generic router. For all the devices in this familiar family setup, or even a scenario with thousands of users, the Samba suite is an ideal solution for file and print sharing.
Several cross-platform file and print-sharing solutions exist, but Samba and the SMB/CIFS protocol may be the easiest to implement in a home networking environment. Windows machines and Macs come with the functionality to work with with Samba out of the box, and you should only need to install a single Samba package for Linux machines. GNOME and KDE offer Samba client functionality built in to their default file managers, Nautilus and Konqueror, respectively.
We’ll focus on configuring and using Samba for file and print-sharing in a typical home network with Linux and Windows machines. You can choose from several Samba configuration GUIs, but we’ll go the old-fashioned route and point our text editors to smb.conf. The configuration file is commonly found at /etc/samba/smb.conf or /usr/local/samba/lib/smb.conf. Note that you will need to be root to edit these, or use sudo.
Samba will run on nearly any Unix-like system and can be found in the repositories of just about every Linux distribution. Begin by using your distribution’s package manager to make sure it is installed.
Configuring Samba
Samba is a very mature and complex package, so its configuration file can be long and complicated. You will have to trust that your distribution supplied you with a reasonably sound default configuration and focus on changing just a few lines in smb.conf to make sure they are appropriate for the purposes of a home network. If you want to know more about any line, consult man smb.conf
.
Remember that any line in the configuration file preceded by a semicolon (;) or hash mark (#) is a comment and will not be recognized as an active setting. To activate the line, remove the semicolon or hash. It’s a good idea to add your own comments preceded by one of these characters so that you will remember the logic behind your configuration the next time you load smb.conf.
The first option to consider is Samba’s security level. This line will appear under the [global]
section of smb.conf, where all Samba-wide configuration is done. The other sections, addressed later in this article, relate to specific Samba services (shared resources). The security level will most likely be set to the value user
and look like this:
security = user
For a home network, you may want to consider setting this to share
. The main difference is that with the user
setting you will be required to log into the Samba server before you can browse its resources. This is a wise precaution on untrusted networks, but will be inconvenient when using resources you would like your entire household to have access to, such as a printer. With share
enabled, you can still require users to authenticate themselves with a password to access particular resources.
While still in the [global] section, let’s move on to printers. If you use the Common UNIX Printing System (CUPS) (which most distributions default to), the only thing you need to do to have Samba recognize your printers is set the following lines accordingly:
printing = cups
printcap name = cups
Since you may be configuring these printers (and perhaps other resources) to be accessible without user authentication, it is very important that you restrict access to only known and trusted hosts – the computers in your household. Consult your router’s manual for instructions on assigning specific IP addresses to each computer in your home network. Once you have a list of trusted hosts, enter them into the following lines in the [global]
section:
hosts allow = computer1 computer2 computerN
hosts deny = ALL
Although you have specified that ALL
hosts be denied, any host listed on the hosts allow
line will still be given access. The format of the IP addresses assigned to each computer by your router will vary. For instance, if machines on your local network are given addresses of the format 192.168.0.x
, the following lines will restrict Samba access to local hosts:
hosts allow = 192.168.0.
hosts deny = ALL
Note that the final digit of the IP address was left off on the hosts allow
line. This specifies that any IP address in that range be allowed. For additional security against external access, look into blocking Samba ports with a firewall.
Sharing directories and printers
It’s time to move beyond [global]
and configure specific shared resources. Begin with the [homes]
section. By default, your distribution may have this section configured to allow users to access their home directory on the machine running the Samba server.
If you have security = share
set, this feature may not work as expected and users may be presented with home directories without logging in. If you are the only one with a home directory on the machine running the Samba server anyway, which is likely in a home network environment, it is advisable to remove or comment out (using hash marks or semicolons) the [homes]
section and add any useful directories as shared resources individually later on.
Now you can begin sharing specific directories. Use this as a template for a publicly shared folder for which it is not necessary for users to be authenticated:
[Share Name]
path = /location/of/directory
guest ok = yes
browseable = yes
read only = no
Share Name
is whatever title you choose (to the client accessing your server, this will appear to be the name of the shared directory). The guest ok = yes
line is what specifies this share as publicly accessible. The browseable = yes
line will make the share appear available to all users. Set browseable = no
to force users to manually type in the share name to access it. Of course, you can set read only = yes
to restrict users from make changes to the directory remotely.
Use this as a template for private shares that users must enter a password to access:
[Share Name]
path = /location/of/directory
valid users = user
read only = yes
browseable = no
Here, user
is the user name on the machine running the Samba server of the person with access privileges to the share. Use these two templates to add shares for all the files users may want to access from the server machine.
Your server should be fully configured now. With what you added to the defaults provided by your distribution, your completed smb.conf should look something like this:
[global] security = share workgroup = HOME server string = %h server log file = /var/log/samba/log.%m max log size = 1000 dns proxy = No hosts allow = 192.168.0. hosts deny = ALL printing = cups printcap name = cups [printers] path = /var/spool/samba printable = Yes browseable = No [print$] path = /var/lib/samba/printers [Public Directory] path = /Public/Files guest ok = yes read only = no browseable = yes [Private Directory] path = /private/files/ valid users = me read only = yes browseable = no
Before you leave the server machine you have a few more quick chores. First, enter any users that will be accessing the Samba server into the following command:
smbpasswd -a user
You will be prompted to enter a Samba password for each user. You can change the password at any time by logging in as the desired user and running smbpasswd
. Now restart your Samba server using this command:
/etc/init.d/samba restart
Accessing Samba shares from Windows clients
Head over to a Windows machine to try out your new setup. Your new server should appear in Windows’ My Network Places (look for the shortcut on your desktop, by default). Alternatively, open the Start menu and click “Run…”, then enter:
\server
Replacing server
with the name or IP address of the machine running your Samba server. A Windows Explorer window with the browseable shares from your server should open up. If you’ve made a non-browseable share, access it using this link:
\servershare name
Is is easy to make shared directories more accessible. In Windows XP, right click on the share in Explorer and choose “Map Network Drive…” You will be able to assign them a drive letter, such as Z:, so that they may be easily found in My Computer, even after a reboot.
In my testing on Windows XP with the security level set to share
, printers are automatically be detected and available to use from the Windows machine. With user
level security set, it was necessary to log into the server in a Windows Explorer window before trying to print. Your experience on other versions of Windows may vary.
Accessing SMB/CIFS shares from other Linux machines
Samba and Windows shares can be easily accessed from the default file managers of both Gnome and KDE. We’ll begin with accessing shares from Nautilus in Gnome. Open Nautilus and go to File -> Connect to Server.
Choose “Windows share” from the listbox and enter the server name or IP address of your Samba server. You can also click the “Browse Network” button and look in the “Windows Network” directory to search for the server manually. Click “Connect” and a Nautilus window will open with the browseable resources of your Samba server.
Accessing Samba shares with Konqueror is just as simple. To browse for your server, enter the URL remote:/ in Konqueror. For direct access, type the URL of the server in directly in this format:
smb://user@server/share
Note that user and share are optional criteria.
Configuring printers over Samba is similarly easy in both these desktop environments. In Gnome, go to System -> Administration -> Printing. In the printer configuration application, select Printer -> Add printer. You will be prompted for your password. In the add printer wizard, select “Network Printer” and then “Windows Printer SMB” from the listbox. You will be prompted for a user name and password on your Samba server. Identify your Host and Printer on the Samba server and then move on to the next screen. Select your printer model and then click Apply.
To do the same in KDE, open the configuration center by launching the command kcontrol
. Navigate to the Printers module and go to Add -> Add Printer/Class… In the resulting dialog, click Next and then select “SMB shared printer (Windows).” Click Next again and configure the username and password of a “Normal account,” if using user
level security. Click Next another time and then Scan to browse for your Samba server.
Alternatively, enter the server details manually. On the next screen, select your printer model from the list. Click through the next few screens and give your networked printer a title to finish up.
Troubleshooting
If you’ve experienced any problems getting any of this functionality to work, turn to the Samba troubleshooting checklist. A quick trick borrowed from that document for testing your Samba configuration file for obvious errors is to run the following command:
testparm smb.conf
Again, the exact path of your smb.conf may vary by distribution.
We have only explored basic Samba functionality here, tailored for a home network. More extreme usage scenarios are addressed in detail in the Samba by example guide.
Для работы бывает необходимо подключаться из Linux к общей папке Windows, чтобы забрать или передать файлы. В организациях в 99% используются компьютеры под управлением Windows, поэтому приходится подключаться из Linux к Windows.
Установка Samba клиента в Linux
sudo apt-get update
sudo apt-get install samba-client
sudo apt-get install cifs-utils
Для удобства просмотра сетевого окружения в GUI удобен файловый менеджер Nautilus с дополнением Nautilus-share
sudo apt-get install nautilus nautilus-share
Просмотр общих сетевых ресурсов с помощью командной строки
Вызов клиента Samba для просмотра ресурсов сервера из командной строки:
1) просмотр общих папок, предоставленных в общий доступ по сети для локальных пользователей сервера
smbclient -L //192.168.100.10 -U Username%Password
либо
smbclient -L //servername -U Username%Password
где: 192.168.100.10 — IP адрес сервера, servername — имя сервера, Username — локальный пользователь сервера, Password — пароль пользователя Username
2) просмотр общих папок, предоставленных в общий доступ по сети для пользователей домена
smbclient -L //192.168.100.10 -U Domain/Username%Password
либо
smbclient -L //192.168.100.10 -U Username%Password -W Domain
или по имени
smbclient -L //servername -U Username%Password -W Domain
где Domain — имя домена Active Directory.
Либо (чтобы каждый раз не сообщать пароль в параметрах команды) создать файл ~/.smbcredentials
с данными входа:
username=имя_пользователя
password=пароль
domain=имя_standalone_сервера_или_домена
Тогда, присоединение к сетевому каталогу:
smbclient //server/share --authentication-file=/home/vladimir/.smbcredentials
Подключение к общей папке Samba в интерактивном режиме
То же самое, но без ключа -L, но с параметром — именем общей папки, в данном случае «share»
smbclient //192.168.100.10/share -U Domain/Username%Password
либо
smbclient //servername/share -U Domain/Username%Password
либо
smbclient //servername/share -U Username%Password -W Domain
После успешного входа появится приглашение
smb: \>
можно вводить команды, например, help или dir. Интерфейс для управления smbclient с помощью команд напоминает ftp клиент.
Подключение к общим папкам с помощью файлового менеджера Nautilus
После запуска nautilus, выберите в левой части окна «+ Другие места» — откроется просмотр локальной сети, где можно просматривать компьютеры в сети, у которых имеются общие папки.
Решение проблемы с подключением: избавляемся от ошибки -13 Access Denied, либо NT_STATUS_ACCESS_DENIED
Ошибка: CIFS: VFS: cifs_mount failed w/return code = -13"
Данную ошибку можно решить только настройкой прав на сервере. Чтобы открыть общую папку на просмотр, нужны три условия:
1) Пользователь указан среди пользователей сервера или домена (либо доступ типа guest разрешён)
2) Предоставлен (не ограничен) доступ к файловой системе.
3) Дан доступ к конкретной сетевой папке — например, пользователь входит в группу пользователей, к которой дан доступ к общей папке.
Последнее, третье условие самое строгое. Нужно, чтобы Администратор сервера предоставил права пользователю (включил его в группу пользователей общей папки).
Самое интересное, что права Администратора не гарантируют даже ему полных прав доступа к общей папке, т.к. необходимо, чтобы пользователь «Администратор» входил в группу, которой предоставлены права к данной сетевой папке. В этом плане администратор не отличается от группы other/nobody: получит ошибку mount error(13): Permission denied, потому что он не входит в группу пользователей сетевой папки.
Использование команды «mount»
Вместо smbclient
можно использовать команду mount
.
Вначале нужно создать точки монтирования и дать права доступа к папке, например:
sudo mkdir /mnt/cifs
sudo chmod 0777 /mnt/cifs
Примеры использования команды mount с сетевым папками:
sudo mount -t cifs //192.168.20.222/share /mnt/cifs -o user=Vlad,pass=Str0ngPa$$word
ls /mnt/cifs
sudo umount //192.168.20.222/share
ls /mnt/cifs
Либо то же самое с файлом .smbcredentials :
sudo mount -t cifs //192.168.20.222/share /mnt/cifs -o credentials=/home/vladimir/.smbcredentials
Если имя сетевой папки содержит пробелы («share with spaces in name»), нужно вводить следующим образом:
sudo mount -t cifs //192.168.20.222/share\ with\ spaces\ in\ name /mnt/cifs -o credentials=/home/vladimir/.smbcredentials
Примечание: Чтобы после выполнения команды mount примонтированная папка работала бы не только на чтение, но и на запись в удалённую общую папку, нужно сопоставить удаленного пользователя с локальным пользователем Linux, при помощи параметров uid=1000,gid-1000. Где 1000 — заменить на uid и gid пользователя Linux (выводятся командой id
).
Либо добавить в параметры -o noperm,iocharset=utf8.
В ключах команды можно задать версию Samba, которую используем для подключения. Например,
для SMB2: vers=2.0 или для SMB3 vers=3.0.
Примеры:
sudo mount -t cifs //192.168.20.222/share\ with\ spaces\ in\ name /mnt/cifs -o user=username,pass=password,uid=1000,gid=1000
sudo mount -t cifs //192.168.20.222/share\ with\ spaces\ in\ name /mnt/cifs -o credentials=/home/vladimir/.smbcredentials,vers=2.0,noperm
Если заданная версия Samba (например, SMB3) не поддерживается сервером, будет выведена ошибка "mount error(95): Operation not supported."
.
Добавление параметра «nofail» пригодится, когда не известно, включен ли удалённый компьютер (сервер) или нет.
Монтирование сетевой папки во время загрузки (файл /etc/fstab)
Синтаксис строки в /etc/fstab:
//[URL]/[sharename] /mnt/[mountpoint] cifs vers=3.0,credentials=/home/username/.sharelogin,iocharset=utf8,file_mode=0777,dir_mode=0777,uid=[username],gid=[username],nofail 0 0
где:
//[URL]/[sharename]
— имя сервера и сетевой папки
/mnt/[mountpoint]
— точка монтирования на локальном компьютере
vers=3.0
— принудительно установить версию протокола SMB3 (либо vers=2.0 — если клиент и сервер поддерживают лишь SMB2)
credentials=/home/username/.sharelogin
— указание файла с именем пользователя, паролем и доменом для входа
iocharset=utf8
— прямое указание набора символов utf8 (не обязательно, если без него работает)
file_mode=0777,dir_mode=0777
— права доступа при выполнении mount
uid=[username],gid=[username]
— данные uid и gid из результата вывода команды cat /etc/passwd | grep username
nofail
— загрузка ОС будет продолжена даже в случае недоступности сервера URL
Другие параметры:
defaults
— включает опции rw, suid, dev, exec, auto, nouser, and async. Обычно идёт первой, т.к. можно переопределить отдельные опции в строке позднее, например: defaults, noexec, ro — нет исполнения, только чтение.
rw
— очевидно, чтение-запись со стороны клиента (является противоположностью ro — только чтение (защита от записи).
suid
— запрещает использование бит полномочий SUID (Set-User-IDentifier — установка идентификатора владельца) или SGID (Set-Group-IDentifier). Грубо говоря, запрещает передачу части прав при помощи битов SUID и SGID — права должны быть заданы явно.
auto
— используется в /etc/fstab — разрешает автоматическое монтирование сетевых ресурсов при выполнении команды mount -a
noauto
— запрет для fstab монтировать папку автоматически при выполнении команды mount -a.
nouser
— прямой запрет на «ручное» монтирование всеми пользователями, кроме root (не влияет на монтирование во время загрузки ОС)
guest
— для доступа к «гостевым» общим папкам, которые доступны по сети без указания имени пользователя и пароля.
async
— запись данных в сетевую папку производится по мере возможности — значение по умолчанию. Повышает производительность.
sync
— немедленная запись на удаленный компьютер (без использования буферов), не рекомендуется.
noperm
— отключает встроенную в клиент проверку прав. Используют noperm в том случае, если права вроде бы есть, но создать файл на запись, например, программно, не получается, из-за несовместимости в реализации CIFS на клиенте и сервере.
noexec
— прямой запрет запуска исполнимых файлов из сетевой папки
noatime
— не обновлять время создания файла (повышает производительность, но понижает информативность)
nounix
— отключение расширений Linux: не использовать символические ссылки. Используется, чтобы отключить символьные ссылки для обеспечения совместимости с Windows.
mfsymlinks
— ключ для символьных ссылок в стиле Minshall+French. Этот стиль ссылок поддерживается Windows и Mac.
Примеры строки в fstab (где данные входа указаны в файле /etc/.smbcredentials):
//192.168.20.222/share_name rw,auto,nofail,credentials=/etc/.smbcredentials 0 0
Если в /etc/hosts или локальном DNS сервере прописаны имена машин, вместо IP-адреса можно подключать общую папку по имени: //server/share .
Команда для монтирования на основе fstab:
sudo mount -a
Будет перемонтированы все диски на основе /etc/fstab за исключением помеченных параметром «noauto».
Краткая информация по настройки Samba в Windows (протоколы SMB1, SMB2, SMB3)
Samba протокол имеет три версии 1, 2 и 3.
Протокол SMB1 включают, если в организации имеются машины под Windows XP. В остальных случаях стараются отключить SMB1 как небезопасный.
Включение и выключение в Windows 7 и Windows Server 2008r2 производится с помощью реестра, параметры
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters
параметры типа DWORD
SMB1=0
SMB2=1
В Windows 8, Windows 10, 11, Windows Server 2012, 2016 и выше используется командлет PowerShell
Get-SmbServerConfiguration | select EnableSMB1Protocol,EnableSMB2Protocol
Set-SmbServerConfiguration -EnableSMB2Protocol $true
Указанные командлеты не работают в ранний версиях Windows 7 и Windows Server 2008r2.
Также, SMB3 не работает в Win7 — подробнее см. здесь — сайт winitpro.ru.
Ссылки:
- man mount.cifs