Letysite.ru

IT Новости с интернет пространства
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Linux mount smb

How to Mount SMB Share on Linux

Samba is a service in Linux that provides seamless file and print service to SMB/CIFS clients. One of the main features of Samba is that it allows interoperability between Linux/Unix servers and Windows-based clients. In general, you can share resource-like files and printers over the network between Unix to Unix as well as Unix to Windows.

A samba user can log into samba server (Linux Server) and depending on the rights they are granted, copy files to and from parts of the UNIX file system, submit print jobs and even send you WinPopup messages. Unix users can either mount the shares directly as part of their file structure using the smbmount command or alternatively, can use a utility, smbclient installed with Samba to read the shares with a similar interface to a standard command line program. In this tutorial , I will cover how list and mount smb shares on linux.

Table of Contents

Mount SMB share

You manually mount the smb share using the mount command

# mount -t cifs //192.168.1.100/myshare /smbdata -o user,uid=500,rw,suid,username=aloft,password=aloft123

# mount -t smbfs //my_serv/F_Drive /mnt/fdrive -o credentials=/etc/sambapassfile,uid=sam,gid=users

Mount large smb share point

The general syntax is below to use smbmount command.

smbmount //Hostname/Username /local/mountpoint -o username=username,password=password,lfs

#smbmount //nastorage.domain.com/oracleshare /oraclefiles -o username=LOGINNAME,password=LOGINPASSWORD,lfs

Here NAS samba share is mounted with lfs (large file system) option enabled. This will avoid errors while copying a large file from NAS storage.

Adding SMB Entries in /etc/fstab

Below example, fstab entries show how to use smb share in fstab file.

# cat /etc/fstab
LABEL=/1 / ext3 defaults 1 1
devpts /dev/pts devpts gid=5,mode=620 0 0
tmpfs /dev/shm tmpfs defaults 0 0
proc /proc proc defaults 0 0
sysfs /sys sysfs defaults 0 0
LABEL=SWAP-sda2 swap swap defaults 0 0
//192.168.1.100/myshare /smbdata cifs user,uid=500,rw,suid, username=aloft,password=aloft123 0 0

In the above example, local user (uid=500) will become the owner of the mounted files. In similar way, you can specify credentials such as uid=uid number or name of the account/user or group.

The /etc/fstab is readable by everyone so it obviously wouldn’t be a good idea to have your Windows password in it. The way to get around this is, by using what is known as a credentials file. You would modify the line in the /etc/fstab file to look like below.

//servername/sharename /mountdirectory smbfs credentials=/home/myhomedirectory/.smbpasswd 0 0

Below echo command can be used to create the credentials file:

echo username=mywindowsusername > .smbpasswd
echo password=mywindowspassword >> .smbpasswd

chmod 600 .smbpasswd (Modify the permissions on the file so only you have permission to read and write to it)

Fstab options

: There are a variety of options that you can use for smb mounts. We can go through the important options that you need to know to setup fstab entry for smb mounts.

• username=

This specifies the username to connect as. If this is not given, then the environment variable USER (which may contain the username of the person using the client) is used.

• password=

This specifies the SMB password. If this option is not given then the environment variable PASSWD(which may contain the password of the person using the client) is used. If it cannot find password smbmount will prompt for a password.

• credentials=

Rather than giving username and password directly in fstab file, you can specify a file that contains a username and/or password. The format of the file is:
username=value
password=value

This sets the uid that will own all files on the mounted filesystem. It may be specified as either a username or a numeric uid.

This sets the gid that will own all files on the mounted filesystem. It may be specified as either a groupname or a numeric gid.

• fmask=

This sets the file mask. This determines the permissions that remote files have in the local filesystem. This is not a umask, but the actual permissions for the files. The default is based on the current umask.

• dmask=

This sets the directory mask. This determines the permissions that remote directories have in the local filesystem. This is not a umask, but the actual permissions for the directories. The default is based on the current umask.

• iocharset=

This sets the charset used by the Linux side for codepage to charset translations (NLS). The argument should be the name of a charset, like iso8859-1

List SMB Share

You find the shared resource on remote Samba Server using smbclient command.

# smbclient -L 192.168.1.100
Password:
Domain=[LOCALHOST] OS=[Unix] Server=[Samba 3.0.23c-2] Sharename Type Comment
——— —- ——-
myshare Disk Mary’s and Fred’s stuff
IPC$ IPC IPC Service (Samba Server)
root Disk Home Directories
Domain=[LOCALHOST] OS=[Unix] Server=[Samba 3.0.23c-2] Server Comment
——— ——-
Workgroup Master
——— ——-
MYGROUP

Connect Samba Share from terminal

Before trying to connect to samba share, you should have privileges to access to the particular share, should have account on that Samba Server and your password should mapped with Samba Password.

# smbclient //192.168.1.100/myshare -U aloft
Password:
Domain=[LOCALHOST] OS=[Unix] Server=[Samba 3.0.23c-2] smb: >

Монтирование расшаренных windows-ресурсов в Linux через CIFS

Иногда, при организации совместных сетей между Windwos и Linux системами, в последних может появиться необходимость монтирования расшаренных SMB-ресурсов прямо к файловой системе. Прежде всего такая необходимость появляется при использовании легковесных рабочих сред (XFCE, OpenBox, LXDE и др), файловые менеджеры которых не поддерживают прямой доступ к samba.

Например, в среде Gnome доступ к ресурсу Windows можно получить прямо из файлового менеджера Nautilus, введя в адресной строке путь вида smb://192.168.0.11/ (где вместо необходимого ip-адреса также может быть просто указано сетевое имя windows-системы). Но многие другие файловые менеджеры (к примеру, быстрый и удобный PCMan File Manager до определённой версии) не поддерживают такой возможности, поэтому универсальным решением становится монтирование SMB к конкретному пути вашей файловой системы, в результате вы получите доступ к расшаренному ресурсу удаленной системы точно так же, как вы его получаете к своим дискам. Для этой цели нам потребуется установленный пакет cifs-utils, в Ubuntu и Debian установить его можно командой:

sudo apt-get install cifs-utils

В Fedora, CentOS и других RedHat based дистрибутивах:

sudo yum install cifs-utils

Также, как заметили в комментариях, рекомендуется установить пакеты ntfs-3g и ntfs-config , если они у вас ещё не установлены.

Теперь для начала давайте разберем как монтировать расшаренные папки вручную. Потребуется создать путь куда будем монтировать SMB-папку, пусть это, к примеру, будет /media/sharefolder:

sudo mkdir /media/sharefolder

Вот такой командой можно примонтировать папку, требующую авторизации по логину и паролю:

sudo mount -t cifs //192.168.0.11/share /media/sharefolder -o username=windowsuser,password=windowspass,iocharset=utf8,file_mode=0777,dir_mode=0777

где вместо //192.168.0.11/share – ip-адрес и имя необходимой общей папки (если имя расшаренной папки содержит пробел, то необходимо заключить весь путь в кавычки, как это показано в следующем примере), /media/sharefolder – путь куда будет монтироваться ресурс, windowsuser – имя пользователя с необходимыми правами доступа к этому ресурсу Windows, windowspass – пароль этого пользователя.

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

sudo mount -t cifs «//192.168.0.11/общие документы» /media/sharefolder -o guest,rw,iocharset=utf8,file_mode=0777,dir_mode=0777

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

sudo mount -t cifs //192.168.0.11/общие /media/sharefolder -o guest,iocharset=utf8

При удачном выполнении этих команд не должно произойти никакого уведомления – можете смело проверять как примонтировалась папка перейдя по вашему пути (в нашем примере – /media/sharefolder).
Отмонтируется папка командой:

sudo umount /media/sharefolder

Для того чтобы осуществить автомонтирование таких папок нам придется отредактировать системный файл fstab. Также, если доступ к необходимому windows-ресурсу требует обязательной авторизации, то потребуется предварительно создать файл, в котором будут прописаны логин и пароль доступа (сделать это можно текстовым редактором nano):

sudo nano /root/.smbcredentials

В этот новый файл добавьте две строки:

где, соответственно, windowsuser – имя пользователя с необходимыми правами доступа к ресурсу Windows, windowspass – пароль этого пользователя. Измените права созданного файла так, что редактировать и смотреть его смог только root, то есть сама система:

sudo chmod 700 /root/.smbcredentials

Сохраните изменения и переходите к редактированию файла /etc/fstab:

sudo nano /etc/fstab

И здесь в самом конце добавьте строку типа:

//192.168.0.11/share /media/sharefolder cifs credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0777,dir_mode=0777 0 0

Если авторизации по имени и паролю не требуется, а требуется только гостевой доступ, то создавать файл .smbcredentials не потребуется, этот шаг можно было пропустить и сразу в /etc/fstab добавить строку:

//192.168.0.11/общие40документы /media/sharefolder cifs guest,rw,iocharset=utf8,file_mode=0777,dir_mode=0777 0 0

Обратите внимание, что здесь если ваша папка содержит пробелы, то вариант аналогичный командной строке – заключении пути в кавычки – не поможет, для того, чтобы fstab понял пробелы – их необходимо заменить на четыре символа: 40
И, соответственно, если требуется только лишь гостевой доступ в режиме чтения к windows-папке, то будет достаточно такой строки:

//192.168.0.11/общие /media/sharefolder cifs guest,iocharset=utf8 0 0

Для того, чтобы проверить корректно ли монтируется shared-папка из fstab без перезагрузки нужно выполнить такую команду:

Также к этому стоит добавить, что если вы хотите получать доступ к windows-шаре не через ip-адрес, а через имя машины, то вам потребуется установить winbind, в Debian-based:

sudo apt-get install winbind

Или в RedHat-based системах:

sudo yum install samba-winbind

После этого отредактируйте файл /etc/nsswitch.conf:

sudo nano /etc/nsswitch.conf

hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4

перед dns добавьте wins, то есть после редактирования она должна выглядеть вот так:

hosts: files mdns4_minimal [NOTFOUND=return] wins dns mdns4

После перезагрузки для получения доступа к windows-ресурсу через CIFS можно будет указывать не только ip, но и сетевое имя windows-ресурса (netbios name). Но мы всеже рекомендуем использовать непосредственно ip-адрес (как было описано в статье) – к нему обращение идет напрямую, быстрее.

Также стоит отметить, что таким образом можно монтировать только конкретные общие папки (например: //192.168.0.11/share), но не весь windows-ресурс целиком (то есть просто: //192.168.0.11).

How to Mount a Windows Share in Linux

In this tutorial we will be discussing different ways to connect to a Microsoft share form Linux. Before we dive in I think it is important to understand the different terminology used when talking about Samba, SMB and CIFS shares.

Table of Contents

SMB vs CIFS vs SAMBA

SMB (Server Message Block) is a protocol used for network file sharing. It was originally designed at IBM in the 1980’s.

CIFS (Common Internet File System) is a implementation of SMB that was created by Microsoft.

SAMBA is an open source software suite and set of utilities used by UNIX/Linux to communicate with Microsoft Windows systems.

From the average user stand point SMB and CIFS can be used interchangeably. As you will see below, we will connect to the same share using both SMB and CIFS.

Mount a Windows Share Using GUI (Files / Nautilus)

You can easily connect to a Windows share using the Files application (formerly known as Nautilus) that ships with Gnome. For the sake of clarity, we will call it Nautilus.

Open the Nautilus application and select «Other Location» from the left places panel.

At the bottom of the screen you will see «Connect to Server» with a box asking for you to enter the server address. Inside that box is a diamond with a question mark in it that you can click for some help.

As you can see in the pop-up, server addresses are made up of a protocol prefix and an address. On my Windows machine named «MyMuse» I created a share called «SharedDocs». So inside that entry box we will use:

We can also use the IP address:

This will bring up a dialog box asking for authentication credentials.

Select the «Registered User» radio button and enter your details. You have three options for storing your password.

  • Forget password immediately — This will log you in and and soon as your session is over you will be required to provide your credentials again.
  • Remember password until you logout — Remember your password until you explicitly logout.
  • Remember forever — This option will store the credentials and allow you to easily return to the share.

Once you are connected, Nautilus will show the location on the left panel allowing easy access to the share.

Be aware that once that connection is closed you will have to go back to «Other Locations» and use the drop down box to reconnect. If you want to make the share persistently accessible from the left menu you will need to add a bookmark.

NOTE: If you do not want to type your credentials every time ensure that you select «Remember Forever» when authenticating to the share.

To add a bookmark, connect to the share then right click it in the left panel and select «Add Bookmark».

If you have a lot of shares, or multiple shares on the same device, it will be hard to differentiate them. You can rename them to something more user friendly by right clicking on the bookmark and selecting «Rename. «.

Now we can easily navigate to our share as the name is clearly visible and easy to identify.

Mount A Windows Share Using Command Line

Using the mount.cifs Command

You can easily mount a cifs share from the command line using the mount.cifs command. Using the mount command requires root privileges.

First, create a directory to mount the share:

Use the mount.cifs command to mount the share at the created directory.

You can use the IP address as well.

Alternatively, you can use mount -t cifs with the same syntax.

Automatically Mount CIFS Share at Boot

Mount CIFS Share at Boot Using /etc/fstab

You can add your CIFS mount point in /etc/fstab and have the system mount it during boot. However, there are some considerations to make. If the share is not available at boot time the system will hang until the mount attempt times out, or worse, refuse to boot. This will cause a delay in accessing the system. To avoid this you can use autofs (next section). Also mounting it via fstab requires you to put your credentials somewhere in plain text. You have two options when using fstab to mount a CIFS share.

  1. Put the credentials in the fstab file itself — This is a huge security risk as fstab is readable by any user. Someone can simply cat the file and see your credentials. IT IS NOT RECOMMENDED!
  2. Use a credentials file — This entails saving your credentials in a separate file which can then be protected by permissions. Although your credentials will still be saved in plain text, someone would need root permissions to read them.

Because of the high risk of the first option, we will not even discuss how to do it. It is easy enough to use a credentials file.

First, create a hidden file in root’s home directory (/root/). You can call this file whatever you like. Most people call it .smbcreds or similar. In this file you need two lines, one containing «username= » and one containing «password= «.

Now set the permissions so it is only readable by root:

Now edit the /etc/fstab file and add the following information:

  • Remote server share address (//mymuse/shareddocs)
  • Local mount point (/mnt/cifs)
  • Filesystem type (cifs)
  • options (credentials file=/root/.smbcreds)
  • dump option (0)
  • check option (0)

Example fstab, last line showing the CIFS mount point.

Mount CIFS Share using AutoFS

The most obvious benefit of using autofs is that the share is only mounted when being accessed. If it is unavailable it will not effect your system when it boots.

Using autofs has the same credentials issues described above with fstab. It is also necessary to store your password in plain text when using autofs for cifs shares.

Installing autofs Package

Install autofs in CentOS 7, or Red Hat 7:

Install autofs in Ubuntu 18:

Let’s configure autofs to mount our Windows share.

Create Credentials File

First, ensure you create the credentials file as described above:

DO NOT forget to set the permissions:

Get UID for User

Now, let’s get our user accounts uid so we can tell autofs to mount the share as our user instead of root.

Edit auto.master Map File

Edit the /etc/auto.master configuration file. In this file we will provide a map of directories to shares for autofs to use. Add the following line to the file:

The first part of the above line is the directory we are using as a mount point (you can create a custom directory if you wish). The second is the file that autofs should look in for instructions on how to connect to the resource and mount it.

Create the Shares File

Next edit or create the /etc/auto.shareddocs file and add the following:

Restart the Service

Now we must restart the autofs service so it reads the new configuration.

Test and Verify

Now, let’s look in the /mnt directory.

The shareddocs directory doesn’t exist until you try to access it (auto fs). If everything above was followed, we should be to cd into that directory even though we do not see it. The directory will be dynamically created as it is accessed.

Bob’s your uncle.

Conclusion

In this article we covered 3 different ways to mount your Windows shares in Linux. You should now be able to mount an SMB share via the GUI, manually on the command line, automatically on boot and with autofs.

An important point I would like to stress is make sure you protect your credentials. I hope you enjoyed this tutorial, please leave feedback or questions in the comments below.

How to Mount SMB Shares on CentOS 7

Overview

In this tutorial, you will learn how to mount SMB shares on CentOS 7. You will be guided through the process for both desktop and server installations of the operating system.

CentOS provides support for mounting Microsoft CIFS or SMB shares. Not just limited to shares hosted from Microsoft Windows, we can also mount shares from any network device that uses the SMB protocol. This includes just about any NAS device on the market.

If you understand how to mount SMB shares on earlier versions of Red Hat Enterprise Linux or CentOS, the instructions are identical.

Share Configuration

For this tutorial, I prepared a share named Core Library on a Windows Server 2012 R2 server that is a member of an Active Directory domain.

For the share permission on WS12FS01, we grant Full Control to Everyone. Don’t be fooled into thinking this is insecure. Although everyone has access to the share, the NTFS permissions on the volume hosting the share overrule the share permissions. By leaving Everyone and granting full control, we save our selves work by only having to manage permissions on the file system itself.

FIG1Windows Share Permissions

For the NTFS permissions, we created an Active Directory account named _share_library_core and granted it Modify, Read & Execute, List folder contents, Read, and Write. The account will be used when we mount the share onto CentOS 7.

FIG2NTFS Share Permissions

We use an Active Directory account in this tutorial as an example of how someone would accomplish this in an enterprise environment.

However, an Active Directory account is not required. As long as the CentOS server has an account that can authenticate successfully on the host publishing the share, it doesn’t matter where the account actually exists – in Active Directory or locally on the file server itself.

Preparing CentOS 7 for Mounting SMB Shares

A default CentOS 7 build will not be able to mount SMBCIFS shares, unless you customized the install. We’ll need to install a package onto the server that allows it to understand the SMB protocol.

  1. Install the cifs-utils package from the default CentOS yum repository.
  2. Next, we need an account on the CentOS server that will map to the Windows account granted permission to the SMB share, _share_library_core. We’ll create a service account named svc_library_core with a user id (UID) of 5000.
  3. We also want a group on the CentOS server that will map to the share. This group will contain all of the Linux accounts that will need access to the share. Our account will be called share_library_core and it will have a group id (gid) of 6000.
  4. Finally, add any Linux accounts that require access to the SMB share to the newly created Linux group. I have an existing account named user1 that I will add to the share_library_core group.

Mounting an SMB Share

We are now ready to mount our SMB share. In the example below, we temporarily mount the SMB share onto our CentOS server. The share will remain mounted until the server is rebooted.

  1. Create a directory to mount the SMB share into. We’ll mount the share in a directory called lib_core.
  2. Using the mount.cifs command, mount the SMB share into lib_core using the Active Directory user account _share_library_core. We need to map the UID of our svc_library_core account (5000) and the gid of our share_library_core group (6000) to the SMB share.

The extra backslashes () are not typos. Backslashes are used to escape certain characters. Because of this, we have to double up on them when accessing Microsoft shares.

  • If no errors appeared, the share should successfully be mounted. The verify this, use the df command or the mount.
  • Hiding SMB USer Credentials

    In the example above, we’re forced to enter the username and password into the command-line. This is a major security issue, as someone could browse your bash history to obtain the credentials, or they can see them while you type them in. Thankfully, there’s a way to address this problem by using a credentials file.

    1. If not Root, SU into the Root account.
    2. Create a credentials file in Root’s home directory. I typically create this file in a sub-directory in Root’s home, for organizational reasons. But for this example, I will place it in /root.
    3. Modify the file’s permissions so that only the Root account is granted read permissions. No groups or other users should have access to the file.
    4. Open the file in a text editor. I like using VI, but you can use whichever you prefer.
    5. Add the following lines to the file. Remember to replace the username and password values so that they match your environment.

    Persistent SMB Mounts using FSTAB

    The downfall of the examples above is that the mounts are only temporary – the will not remount at system boot. The make the mount permanent we need to add it the fstab.

    1. Open /etc/fstab into a text editor.
    2. Add the following line to your fstab. Remember to replace the values with those that match your environment.
    3. Save your changes and exit the text editor.
    4. The SMB share will mount the next time the CentOS server is rebooted. To mount the share immediately, use the mount command.

    Post navigation

    Related Posts:

    Republish This Article

    We believe in the free flow of information. We use a Creative Commons license, so you can republish our articles for free, online or in print.

    RECOMMENDED BOOKS

    Continuous Delivery should be considered the bible for anyone in Ops, Dev, or DevOps. The book provides key strategies for improving system reliability, configuration management, and ensuring web applications can be delivered to production frequently, and easily. A recommended buy for anyone in IT.

    Tim Lehr

    Technical Director | Pipeline Developer

    Auto-mount Samba / CIFS shares via fstab on Linux

    I’ve been a happy Linux user for quite a while now, but even I cannot deny that it’s sometimes quite hard to get things running smoothly – especially in a Windows dominated environment with little control. One of the things that breaks once in a while on my workstation is the automatic network share mounting I set up via /etc/fstab. This is usually caused by some server-side update that doesn’t affect the setups of Windows and Mac users, but can break your fstab mounting commands in a heartbeat.

    Unfortunately, when things break, the feedback you get from running mount -a is often rather generic and of little help. A typical error:

    Not too helpful, is it? Debugging issues like this one can be quite tedious and time consuming, so I decided to write a little guide to mounting Windows (Samba) network shares on Linux (Fedora 26 in my case). There are a lot of guides out there already, but I found some things especially important and wanted to point those out. Let’s get started.

    1. Install dependencies

    Install the necessary “cifs-utils” with the package manager of your choice e.g. DNF on Fedora.

    2. Create mountpoints

    Create a directory (mountpoint) in /media for every network share you want to mount. If /media does not exist yet, create it first. This is the location where you commonly mount removable volumes in Linux. After the mount is successful, you access all files on your network share from that directory, so be sure to give it a good name. e.g. /media/mordor

    3. Create a credentials file (optional)

    Usually network shares have access protection, so you’ll want to store your user credentials in a local credentials file. If you don’t want this, you’ll have to specify the credentials everytime you want to mount, so I highly recommend it, as long as it’s your machine you are mounting on. The credential file should be in any location in your user directory, e.g. /home/tim/.smb, and should look similiar to this:

    4. Edit /etc/fstab

    Now you should be all set and ready to edit your /etc/fstab file to do some mount magic. Just open the file with a text editor of your choice and add the following lines to the bottom of the file.

    Important: Do not change or delete any other lines in the file! This can do serious harm to your system configuration and you might end up with a broken OS. You have been warned.

    Notice the small difference? If things do not work, it’s usually because the “vers” argument is not set or incorrect. It specifies the Samba version to be used and depending on your server setup this might range from “vers=1.0″ to “vers=3.0″. In my experience you best start of trying to mount the share without it and try-again with different settings if this doesn’t work out.

    For Windows server 2008 shares I can usually get away without it. In more recent versions like Windows Server 2016 it likely needs to be “vers=2.1″ or “vers=3.0″. However, my experience so far is limited to Fedora and a single network, so you might have to tweak the value some more.

    5. Manually mount the share for testing

    Although entries in /etc/fstab are automatically mounted when the system boots, it’s pretty annoying to debug your mount command this way. Here are two commands handy to manually mount and unmount all entries in fstab.

    If you run the first command and do not get any errors, the mounting seems to have worked out fine. Don’t forget to check your mountpoint to make sure you have read / write access!

    If you have any issues with your setup, feel free to leave a comment and I’ll try my best to help you out, although I’m far from being an expert on this topic. Good luck!

    Читать еще:  Linux сигналы процессов
    Ссылка на основную публикацию
    Adblock
    detector