Linux mount smb password

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

Обновлено

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

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

Подготовка

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

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

Синтаксис

* вместо 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

Читайте также:  Install linux on asus

//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 .

Источник

Introduction

SMB (stands for Server Message Block), sometimes known as CIFS (Common Internet File System), is a network file share protocol which is commonly used for publishing folders or entire drives across a network.

It’s most commonly used on Microsoft Windows, with Windows Server running the actual SMB server(s) for standard Windows clients to be able to access. However, it’s also possible to connect or serve SMB from other operating systems, such as Linux, BSD’s, and macOS — albeit most non-Windows implementations can experience performance issues or general compatibility bugs, due to the fact the official SMB server and client are closed source (both a part of Windows and Windows Server).

Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!

We have virtual servers starting from just US$0.99/mo, and dedicated servers starting from as low as US$50/mo

Unlike other hosts, we don’t ask for any personal details — only a name (can be an alias / username), and an e-mail address so we can send you your server details and renewal invoices.

We also accept several different cryptocurrencies with our own in-house payment processor — no third parties involved in processing your payments.

At the time of writing, we currently accept: Bitcoin (BTC), Litecoin (LTC), Monero (XMR), Dogecoin (DOGE), HIVE, and HBD

Order a server TODAY! Privacy is affordable™

Connecting to SMB server from client

Install SMB Client

First, install the SMB client programs if it’s not already installed, via apt / dnf / yum / whatever.

Debian / Ubuntu / Linux Mint / other Debian-based distros

apt update apt install cifs-utils smbclient 

Redhat (RHEL) / CentOS / Fedora / Oracle Linux / SuSE

On older Redhat-based distros, such as CentOS 7, older versions of Fedora/RHEL/Oracle, etc. — you may need to use yum instead of dnf

Become Root

If you aren’t already logged in as root — you should probably become root now.

Mount the share(s) you want

Create the directory where you want to mount the share onto, e.g. /mnt/myshare

Connecting to authenticated shares/SMB servers

If you’re connecting to a share or SMB server that requires a username and password to connect, then follow this segment, otherwise skip to the segment below which covers «guest shares»

Adjust the command below to match the details of the share you’re mounting.

  • Replace example.com with the domain/hostname/IP of the host which serves the share
  • Replace MyShare with the name of the share (the folder name seen in GUI clients) you want to mount
  • Replace johndoe with the username of your account that you’ll be connecting to the share with
  • Replace /mnt/myshare with the mountpoint where you’d like to mount your share mount -v -t cifs //example.com/MyShare -o username=johndoe /mnt/myshare

You’ll be asked to enter your password (if required), and if the server accepts your credentials, then the SMB share will now be accessible at the mountpoint you chose.

root@host ~ # ls /mnt/myshare important.txt photos/ docs/ README.md 

Connecting to guest/public shares (no username or password generally required)

Some SMB servers may make certain shares public to guests, meaning that anyone can access them — without needing login details.

Читайте также:  Linux kernel supported processors

To access a «guest» share, you must use the guest option in the mount options, otherwise you’ll be prompted for a username/password.

For example, to mount the public share publicstuff from the server example.com onto the mountpoint /mnt/public — you’d run the following command:

mkdir -p /mnt/public mount -v -t cifs //example.com/publicstuff -o guest /mnt/public 

Unattended SMB mounting (fstab)

First, add the mountpoint to fstab, as follows.

The credentials= option — points to a file that will contain the username and password needed to connect to the share.

If you are adding a guest/public share which doesn’t require any login, simply use the option guest instead of credentials=/etc/samba/myshare.cred

# SRC/DEVICE MOUNTPOINT FS TYPE OPTIONS # Below is a share which requires authentication. It reads the login details from /etc/samba/myshare.cred //example.com/MyShare /mnt/tmpstore cifs credentials=/etc/samba/myshare.cred 0 0 # Below is a public/guest share. It doesn't require any login details, so we specify 'guest' instead of credentials=/somefile //example.com/publicstuff /mnt/public cifs guest 0 0 

Open up the credentials file in whatever text editor.

Fill out the credentials file as follows, replacing USER with the actual SMB username for logging in, and PASSWORD with the actual password for the user account.

username=USER password=PASSWORD 

Your SMB shares will now be automatically mounted when your system boots, and can also be manually mounted with just the mountpoint, e.g. mount -v /mnt/public

Setting up an SMB server

As mentioned at the start of this article, it’s possible to run an SMB server on most OS’s, despite being primarily a Windows protocol.

On Linux, the most popular/common SMB server is called Samba — an open source SMB/CIFS server for Linux, which is very easy to configure, and supports most features of the SMB protocol, including file sharing, restricting shares and individual share permissions (read/write/browse) to specific users, printer sharing, and more!

Install Samba Server

Debian / Ubuntu / Linux Mint / other Debian-based distros

apt update apt install samba 

Redhat (RHEL) / CentOS / Fedora / Oracle Linux / SuSE

On older Redhat-based distros, such as CentOS 7, older versions of Fedora/RHEL/Oracle, etc. — you may need to use yum instead of dnf

Add shares to the config / adjust any config options you want

Once Samba is installed, you’ll likely want to add some shares to the config. While adding shares, you’re free to tweak some of the settings in the file if you’re comfortable doing so — however with most distros’ default Samba config, there’s no need to edit the config (other than for adding shares) unless you have a usecase where you need to do so.

Open up /etc/samba/smb.conf and add public / private SMB shares as required, along with any other config adjustments you might want.

Below are two example share config blocks

  • web is a public/guest share, which is read only by guests and users, but authorizes the SMB users chris and kale to be able to write to the share.
  • documents is a private share, which cannot be read, written, nor browsed by guests, but ANY logged in SMB user can read/write/browse the share.
#### # Example of a public share named 'web'. Guests can browse and read # files on the share, but they cannot create new files, or write to # existing files on the share. # The users 'chris' and 'kale' however, are whitelisted for write access, # so those two SMB users may create files and write to existing files. ### [web] comment = Privex Public Fileserver path = /filesrv/web read only = yes guest ok = yes browseable = yes write list = chris kale ### # # Example of a private share named 'documents'. # Guests may be able to see this share's name in the available share list, # but they cannot browse the share itself, nor read/write any files inside # of the share. # # Since there are no whitelisted/blacklisted users (other than guests), # all authenticated SMB users can browse/read/write to this share, # ONLY guests (unauthenticated users) are restricted from the share. # ### [documents] comment = PRIVATE Temporary Network Storage path = /filesrv/tmpstore read only = no browseable = yes guest ok = no 

Create and/or set passwords for SMB users

Samba expects each SMB username to actually exist as a system account. Despite this, the users will have a separate SMB password rather than using their Linux/UNIX login.

You’ll need to create an actual Linux system user for each SMB user using adduser (or useradd on some systems), and then set the users’ password using smbpasswd

### # Create the system user 'chris' - and set an SMB password for them ### # Create the Linux/UNIX system account 'chris', with their system login password disabled for security. adduser --disabled-password --gecos "" chris # Set the SMB (Samba) password for the user 'chris' smbpasswd -a chris ### # Create the system user 'kale' - and set an SMB password for them ### adduser --disabled-password --gecos "" chris smbpasswd -a kale 

Enable and (re)start the SMB service

The smbd service isn’t enabled by default (at least not on Ubuntu server), so you may need to enable it first.

Make sure to at least restart smbd after making the config / user changes.

systemctl enable smbd systemctl restart smbd 

Thanks for reading!

Looking to buy a Virtual or Dedicated server? Do you like privacy and low prices? Try Privex!

We have virtual servers starting from just US$0.99/mo, and dedicated servers starting from as low as US$50/mo

Unlike other hosts, we don’t ask for any personal details — only a name (can be an alias / username), and an e-mail address so we can send you your server details and renewal invoices.

We also accept several different cryptocurrencies with our own in-house payment processor — no third parties involved in processing your payments.

At the time of writing, we currently accept: Bitcoin (BTC), Litecoin (LTC), Monero (XMR), Dogecoin (DOGE), HIVE, and HBD

Источник

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