Linux mounting windows shared folder

Ubuntu Wiki

This document describes how to mount CIFS shares permanently. The shares might be hosted on a Windows computer/server, or on a Linux/UNIX server running Samba. This document also applies to SMBFS shares, which are similar to CIFS but are deprecated and should be avoided if possible (link).

(This document does not describe how to host the shares yourself, only how to access shares that are hosted somewhere else. For hosting shares, use Samba.)

Prerequisites

  • Network connections have been configured properly.
  • Your local (Ubuntu) username is ubuntuusername.
  • Share username on Windows computer is msusername.
  • Share password on Windows computer is mspassword.
  • The Windows computer’s name is servername (this can be either an IP address or an assigned name).
  • The name of the share is sharename.
  • You want to mount the share in /media/windowsshare.

CIFS installation

sudo apt-get install cifs-utils
sudo apt-get install smbfs

Mounting unprotected (guest) network folders

First, let’s create the mount directory. You will need a separate directory for each mount.

sudo mkdir /media/windowsshare

Then edit your /etc/fstab file (with root privileges) to add this line:

//servername/sharename /media/windowsshare cifs guest,uid=1000,iocharset=utf8 0 0
  • guest indicates you don’t need a password to access the share,
  • uid=1000 makes the Linux user specified by the id the owner of the mounted share, allowing them to rename files,
  • iocharset=utf8 allows access to files with names in non-English languages. This doesn’t work with shares of devices like the Buffalo Tera Station, or Windows machines that export their shares using ISO8895-15.
  • If there is any space in the server path, you need to replace it by \040, for example //servername/My\040Documents

After you add the entry to /etc/fstab type:

This will (re)mount all entries listed in /etc/fstab.

Mount password protected network folders

The quickest way to auto-mounting a password-protected share is to edit /etc/fstab (with root privileges), to add this line:

//servername/sharename /media/windowsshare cifs username=msusername,password=mspassword,iocharset=utf8 0 0

This is not a good idea however: /etc/fstab is readable by everyone and so is your Windows password in it. The way around this is to use a credentials file. This is a file that contains just the username and password.

Читайте также:  Kali linux wi fi habr

Using a text editor, create a file for your remote servers logon credential:

Enter your Windows username and password in the file:

username=msusername password=mspassword

Save the file, exit the editor.

Change the permissions of the file to prevent unwanted access to your credentials:

Then edit your /etc/fstab file (with root privileges) to add this line (replacing the insecure line in the example above, if you added it):

//servername/sharename /media/windowsshare cifs credentials=/home/ubuntuusername/.smbcredentials,iocharset=utf8 0 0

Save the file, exit the editor.

Finally, test the fstab entry by issuing:

If there are no errors, you should test how it works after a reboot. Your remote share should mount automatically.

Special permissions

If you need special permission (like chmod etc.), you’ll need to add a uid (short for ‘user id’) or gid (for ‘group id’) parameter to the share’s mount options.

//servername/sharename /media/windowsshare cifs uid=ubuntuuser,credentials=/home/ubuntuuser/.smbcredentials,iocharset=utf8 0 0

Mount password protected shares using libpam_mount (Ubuntu 9.04)

  • Your username and password are the same on the Ubuntu machine and on the network drive.
sudo apt-get install libpam-mount

Edit /etc/security/pam_mount.conf.xml using your preferred text editor.

gksudo gedit /etc/security/pam_mount.conf.xml

First, we’re moving the user specific config bits to a file which users can actually edit themselves: remove the commenting tags () surrounding the section called . Save the file when done. With this in place, users can create their own ~/.pam_mount.conf.xml.

Troubleshooting

Login errors

  • Are you using a valid username and password? Does that account really have access to this folder?
  • Do you have whitespace in your credentials file? It should be password=mspassword, not password = mspassword.
  • Do you need a domain? For example, if you are told that your username is SALES\sally, then actually your username is sally and your domain is SALES. The fstab entry should read: . username=sally,password=pass,domain=SALES. Or: . credentials=/path/to/file,domain=SALES.
  • The security and version settings are interrelated. SMB1 is insecure and no longer supported by default. At first, try to not specify either security or version: do not specify sec= or vers=. If you still have authentication errors then you may need to specify either sec= or vers= or both. You can try the options listed at the mount.cifs man page. The man page list leaves out the option sec=lanman for some reason, but you should try that one as well (see discussion).
Читайте также:  Linux boot uefi bios

Unprotected network folder won’t automount

I’ve had a situation where an unprotected network folder wouldn’t automount during bootup, but after manually entering «sudo mount -a» was mounted correctly. I solved this by replacing the «guest» option by «username=guest,password=». If anyone has an explanation for this, please leave a comment.

//servername/sharename /media/windowsshare smbfs username=guest,password=,uid=1000,iocharset=utf8,codepage=unicode,unicode 0 0

Mount during login instead of boot

If for some reason/etc/rc0.d/S31umountnfs.sh (networking problems for example) the automatic mounting during boot doesn’t work, you can add the «noauto» parameter to your smbfs fstab entry and then have the share mounted at login.

//servername/sharename /media/windowsshare cifs noauto,credentials=/home/ubuntuusername/.smbpasswd 0 0
mount /media/windowsshare exit 0

Slow shutdown due to a CIFS/Network Manager bug

If you use Network Manager, and are getting really slow shutdowns, it’s probably because NM shuts down before unmounting the network shares. That will cause CIFS to hang and wait for 60 seconds or so. Here’s how to fix it:/etc/rc0.d/S31umountnfs.sh

sudo ln -s /etc/init.d/umountnfs.sh /etc/rc0.d/K14umountnfs.sh sudo ln -s /etc/init.d/umountnfs.sh /etc/rc6.d/K14umountnfs.sh

Ubuntu 12.04 already runs umountnfs.sh at reboot and shutdown by default (/etc/rc0.d/S31umountnfs.sh and /etc/rc6.d/S31umountnfs.sh) so this is no longer necessary.

CIFS Options Deprecated

Using dmask or fmask in the fstab file produces the following warnings: WARNING: CIFS mount option ‘dmask’ is deprecated. Use ‘dir_mode’ instead. WARNING: CIFS mount option ‘fmask’ is deprecated. Use ‘file_mode’ instead.

Instead use this format: file_mode=0777,dir_mode=0777 . Or in some cases you might need to use file_mode=0777,dir_mode=0777,nounix (see discussion)

Use of tilde in pathnames such as «credentials=~/.smbcredentials»

Curiously, using credentials=~/.smbcredentials in fstab didn’t work. I had to use the full path, i.e. /home/username/.smbcredentials

(This is likely because the tilde «~» is only a shell short-hand alias for «$HOME»; it isn’t something recognized system-wide by all programs, especially not in a system file table where the concept of «HOME» doesn’t really exist. -Ian!)

MountWindowsSharesPermanently (последним исправлял пользователь bigchipmunk 2022-08-08 03:20:46)

The material on this wiki is available under a free license, see Copyright / License for details.

Источник

Как в Linux монтировать шару CIFS

Обновлено

Обновлено: 01.05.2023 Опубликовано: 18.07.2016

Что такое Linux и CIFS простыми словами. Работа с общими папками Windows происходит с использованием протокола CIFS (SMB). Все примеры в данном руководстве выполняются на Linux Ubuntu и CentOS.

Читайте также:  Расшаривание принтера astra linux

Подготовка

Установка пакетов

Сетевые порты

Синтаксис

* вместо mount.cifs можно написать mount -t cifs.

mount.cifs //192.168.1.1/public /mnt

* простой пример монтирования папки public на сервере 192.168.1.1 в локальный каталог /mnt.

Если нам не известны расшаренные папки на сервере, мы можем воспользоваться утилитой smbclient. Для начала установим ее.

а) на RPM (Rocky Linux / РЕД ОС / Red Hat / CentOS / Fedora):

б) на Deb (Debian / Ubuntu / Astra Linux / Mint):

или, при необходимости авторизоваться на файловом сервере:

smbclient -L 192.168.1.1 -U username

Ручное монтирование

Теперь монтирование можно выполнить следующей командой:

mount.cifs //192.168.1.10/share /mnt -o user=dmosk

* в данном примере будет примонтирован каталог share на сервере 192.168.1.10 в локальную папку /mnt под учетной записью dmosk.

То же самое, с использованием домена:

mount.cifs //192.168.1.10/share /mnt -o user=dmosk,domain=dmosk.local

Автоматическое монтирование CIFS через fstab

Для начала создаем файл, в котором будем хранить данные авторизации при подключении к общей папке:

И добавляем в него данные следующего вида:

username=dmosk
password=dPassw0rd
domain=dmosk.local

* в этом примере создана пара логин/пароль — dmosk/dPassw0rd; domain указывать не обязательно, если аутентификация выполняется без него.

Задаем права на созданный файл, чтобы доступ был только у пользователя, скажем, root:

chown root:root /root/.smbclient

Теперь открываем конфигурационный файл fstab:

и добавляем в него следующее:

//192.168.1.10/share /mnt cifs user,rw,credentials=/root/.smbclient 0 0

* в данном примере выполняется монтирование общей папки share на сервере с IP-адресом 192.168.1.10 в каталог /mnt. Параметры для подключения — user: позволяет выполнить монтирование любому пользователю, rw: с правом на чтение и запись, credentials: файл, который мы создали на предыдущем шаге.

Чтобы проверить правильность настроек, вводим следующую команду:

Примеры использования опций

Версии SMB

Если на стороне Windows используется старая или слишком новая версия протокола SMB, при попытке монтирования мы можем получить ошибку mount error(112): Host is down. Чтобы это исправить, указываем версию:

mount.cifs //192.168.1.10/share /mnt/ -o vers=1.0

* монтирование по протоколу SMB1.0

Монтирование от гостевой учетной записи

Если сервер принимает запросы без логина и пароля, то клиент подключается, как гость:

mount.cifs //192.168.1.10/share /mnt -o guest

//192.168.1.10/share /mnt cifs guest 0 0

Права на примонтированные каталоги

При монтировании папки мы можем указать определенные права:

mount.cifs //192.168.1.10/share /mnt -o file_mode=0777,dir_mode=0777

Для указания владельца, который будет назначен для примонтированного каталога, используем:

mount.cifs //192.168.1.10/share /mnt -o uid=33,gid=33

* чтобы посмотреть идентификаторы пользователя, вводим id -u и id -g .

Источник

Оцените статью
Adblock
detector