- Как смонтировать общий ресурс Windows в Linux с помощью CIFS
- Установка пакетов утилит CIFS
- Монтирование общего ресурса CIFS Windows
- Автоматический монтаж
- Отключение общего ресурса Windows
- Выводы
- Как в Linux монтировать шару CIFS
- Подготовка
- Установка пакетов
- Сетевые порты
- Синтаксис
- Ручное монтирование
- Автоматическое монтирование CIFS через fstab
- Примеры использования опций
- Версии SMB
- Монтирование от гостевой учетной записи
- Права на примонтированные каталоги
- How to Mount CIFS Shares as an Automount on Oracle Linux ? (Doc ID 2603544.1)
- Applies to:
- Solution
- To view full details, sign in with your My Oracle Support account.
- Don’t have a My Oracle Support account? Click to get started!
- Oracle linux mount cifs
- 21.3.4В Accessing Samba Shares from an Oracle Linux Client
- ChapterВ 6В Shared File System Administration
- 6.1В About Shared File Systems
- 6.2В About NFS
- 6.2.1В Configuring an NFS Server
- 6.2.2В Mounting an NFS File System
- 6.3В About Samba
- 6.3.1В Configuring a Samba Server
- 6.3.2В About Samba Configuration for Windows Workgroups and Domains
- 6.3.2.1В Configuring Samba as a Standalone Server
- 6.3.2.2В Configuring Samba as a Member of an ADS Domain
- 6.3.2.3В Configuring Samba as a Member of a Windows NT4 Security Domain
- 6.3.3В Accessing Samba Shares from a Windows Client
- 6.3.4В Accessing Samba Shares from an Oracle Linux Client
Как смонтировать общий ресурс Windows в Linux с помощью CIFS
В операционных системах Linux и UNIX общий ресурс Windows можно cifs к определенной точке монтирования в локальном дереве каталогов с cifs опции cifs команды mount .
Common Internet File System (CIFS) — это сетевой протокол обмена файлами. CIFS — это форма SMB.
В этом руководстве мы объясним, как вручную и автоматически монтировать общие ресурсы Windows в системах Linux.
Установка пакетов утилит CIFS
Чтобы смонтировать общий ресурс Windows в системе Linux, сначала необходимо установить пакет утилит CIFS.
Установка утилит CIFS в Ubuntu и Debian:
Установка утилит CIFS на CentOS и Fedora:
Имя пакета может отличаться в зависимости от дистрибутива Linux.
Монтирование общего ресурса CIFS Windows
Подключение удаленного общего ресурса Windows аналогично монтированию обычных файловых систем.
Сначала создайте каталог, который будет точкой монтирования для удаленного общего ресурса Windows:
Выполните следующую команду от имени пользователя root или пользователя с привилегиями sudo, чтобы смонтировать общий ресурс:
Вам будет предложено ввести пароль:
В случае успеха вывод не производится.
Чтобы убедиться, что удаленный общий ресурс Windows успешно смонтирован, используйте команду mount или df -h .
После монтирования общего ресурса точка монтирования становится корневым каталогом смонтированной файловой системы. Вы можете работать с удаленными файлами, как если бы они были локальными.
Пароль также можно указать в командной строке:
Если пользователь находится в рабочей группе или домене Windows, вы можете установить его следующим образом:
Для большей безопасности рекомендуется использовать файл учетных данных, который содержит имя пользователя, пароль и домен общего ресурса.
Файл учетных данных имеет следующий формат:
Файл не должен быть доступен для чтения пользователям. Чтобы установить правильные разрешения и владение , запустите:
Чтобы использовать файл учетных данных, определите его следующим образом:
По умолчанию подключенный общий ресурс принадлежит пользователю root, а права доступа установлены на 777.
Используйте параметр dir_mode чтобы установить права file_mode к каталогу, и file_mode чтобы установить права file_mode к файлу:
Владение пользователем и группой по умолчанию можно изменить с помощью параметров uid и gid :
Чтобы установить дополнительные параметры , добавьте их в виде списка, разделенного запятыми, после параметра -o . Чтобы получить список всех параметров монтирования, введите в терминале man mount .
Автоматический монтаж
Когда общий ресурс монтируется вручную с помощью команды mount , он не сохраняется после перезагрузки.
Файл /etc/fstab содержит список записей, определяющих, где, как и какая файловая система будет монтироваться при запуске системы.
Чтобы автоматически монтировать общий ресурс Windows при запуске системы Linux, определите монтирование в /etc/fstab . Строка должна включать имя хоста или IP-адрес ПК с Windows, имя общего ресурса и точку монтирования на локальном компьютере.
Добавьте в файл следующую строку:
Выполните следующую команду, чтобы смонтировать общий ресурс:
Команда mount прочитает содержимое /etc/fstab и смонтирует общий ресурс.
В следующий раз, когда вы перезагрузите систему, общий ресурс Windows будет подключен автоматически.
Отключение общего ресурса Windows
Команда umount отсоединяет (размонтирует) смонтированную файловую систему от дерева каталогов.
Чтобы отсоединить смонтированный общий ресурс Windows, используйте команду umount за которой следует либо каталог, в котором он был смонтирован, либо удаленный общий ресурс:
Если для CIFS-монтирования есть запись в fstab , удалите ее.
Команда umount не сможет отсоединить общий ресурс, когда он используется. Чтобы узнать, какие процессы обращаются к общему ресурсу Windows, используйте команду fuser :
Как только вы найдете процессы, вы можете остановить их с помощью команды kill и отключить общий ресурс.
Если у вас все еще есть проблемы с —lazy ресурса, используйте параметр -l ( —lazy ), который позволяет вам отключить занятую файловую систему, как только она больше не будет занята.
Выводы
В Linux вы можете cifs к Windows с помощью команды mount с опцией cifs .
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
Как в Linux монтировать шару CIFS
Что такое Linux и CIFS простыми словами.
Работа с общими папками Windows происходит с использованием протокола CIFS (SMB). Все примеры в данном руководстве выполняются на Linux Ubuntu и CentOS.
Подготовка
Установка пакетов
Для монтирования общей папки необходимо установить набор утилит для работы с CIFS.
yum install cifs-utils
apt-get install cifs-utils
Сетевые порты
Если мы будем монтировать сетевую папку, сервер которой находится за брандмауэром, необходимо открыть следующие порты:
Синтаксис
* вместо mount.cifs можно написать mount -t cifs.
mount.cifs //192.168.1.1/public /mnt
* простой пример монтирования папки public на сервере 192.168.1.1 в локальный каталог /mnt.
Ручное монтирование
Теперь монтирование можно выполнить следующей командой:
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 указывать не обязательно, если аутентификация выполняется без него.
Теперь открываем конфигурационный файл 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 .
Источник
How to Mount CIFS Shares as an Automount on Oracle Linux ? (Doc ID 2603544.1)
Last updated on MAY 20, 2021
Applies to:
autofs control the operation of the automount daemons running on the Linux system. Usually autofs is invoked at system boot time with the start parameter and at shutdown time with the stop parameter. The autofs script can also manually be invoked by the system administrator to shut down, restart or reload the automounters.
This document briefly describes the procedure for automatically mounting CIFS shares using autofs.
Solution
To view full details, sign in with your My Oracle Support account.
Don’t have a My Oracle Support account? Click to get started!
In this Document
Goal |
Solution |
My Oracle Support provides customers with access to over a million knowledge articles and a vibrant support community of peers and Oracle experts.
Oracle offers a comprehensive and fully integrated stack of cloud applications and platform services. For more information about Oracle (NYSE:ORCL), visit oracle.com. пїЅ Oracle | Contact and Chat | Support | Communities | Connect with us | |
|
| Legal Notices | Terms of Use
Источник
Oracle linux mount cifs
OracleВ® Linux 6
The software described in this documentation is either in Extended Support or Sustaining Support. See https://www.oracle.com/us/support/library/enterprise-linux-support-policies-069172.pdf for more information.
Oracle recommends that you upgrade the software described by this documentation as soon as possible.
21.3.4В Accessing Samba Shares from an Oracle Linux Client
To be able to use the commands described in this section, use yum to install the samba-client and cifs-utils packages.
You can use the findsmb command to query a subnet for Samba servers. The command displays the IP address, NetBIOS name, workgroup, operating system and version for each server that it finds.
Alternatively, you can use the smbtree command, which is a text-based SMB network browser that displays the hierarchy of known domains, servers in those domains, and shares on those servers.
The GNOME and KDE desktops provide browser-based file managers that you can use to view Windows shares on the network. Enter smb: in the location bar of a file manager to browse network shares.
To connect to a Windows share from the command line, use the smbclient command:
After logging in, enter help at the smb:\> prompt to display a list of available commands.
To mount a Samba share, use a command such as the following:
where the credentials file contains settings for username , password , and domain , for example:
The argument to domain can be the name of a domain or a workgroup.
As the credentials file contains a plain-text password, use chmod to make it readable only by you, for example:
If the Samba server is a domain member server in an AD domain and your current login session was authenticated by the Kerberos server in the domain, you can use your existing session credentials by specifying the sec=krb5 option instead of a credentials file:
For more information, see the findsmb(1) , mount.cifs(8) , smbclient(1) , and smbtree(1) manual pages.
Copyright В© 2013, 2021, Oracle and/or its affiliates. Legal Notices
Источник
ChapterВ 6В Shared File System Administration
This chapter describes administration tasks for the NFS and Samba shared file systems.
6.1В About Shared File Systems
Oracle Linux supports the following shared file system types:
The Network File System (NFS) is a distributed file system that allows a client computer to access files over a network as though the files were on local storage. See Section 6.2, “About NFS”.
Samba enables the provision of file and print services for Microsoft Windows clients and can integrate with a Windows workgroup, NT4 domain, or Active Directory domain. See Section 6.3, “About Samba”.
6.2В About NFS
A Network File System (NFS) server can share directory hierarchies in its local file systems with remote client systems over an IP-based network. After an NFS server exports a directory, NFS clients mount this directory if they have been granted permission to do so. The directory appears to the client systems as if it were a local directory. NFS centralizes storage provisioning and can improves data consistency and reliability.
Oracle Linux 7 supports the following versions of the NFS protocol:
NFS version 3 (NFSv3), specified in RFC 1813.
NFS version 4 (NFSv4), specified in RFC 7530.
NFS version 4 minor version 1 (NFSv4.1), specified in RFC 5661.
NFSv3 relies on Remote Procedure Call (RPC) services, which are controlled by the rpcbind service. rpcbind responds to requests for an RPC service and sets up connections for the requested service. In addition, separate services are used to handle locking and mounting protocols. Configuring a firewall to cope with the various ranges of ports that are used by all these services can be complex and error prone.
NFSv4 does not use rpcbind as the NFS server itself listens on TCP port 2049 for service requests. The mounting and locking protocols are also integrated into the NFSv4 protocol, so separate services are also not required for these protocols. These refinements mean that firewall configuration for NFSv4 is no more difficult than for a service such as HTTP.
6.2.1В Configuring an NFS Server
To configure an NFS server:
Install the nfs-utils package:
Edit the /etc/exports file to define the directories that the server will make available for clients to mount, for example:
Each entry consists of the local path to the exported directory, followed by a list of clients that can mount the directory with client-specific mount options in parentheses. If this example:
The client system with the IP address 192.0.2.102 can mount /var/folder with read and write permissions. All writes to the disk are asynchronous, which means that the server does not wait for write requests to be written to disk before responding to further requests from the client.
All clients can mount /usr/local/apps read-only, and all connecting users including root are mapped to the local unprivileged user with UID 501 and GID 501.
All clients on the 192.168.1.0 subnet can mount /var/projects/proj1 read-only, and the client system named mgmtpc can mount the directory with read-write permissions.
There is no space between a client specifier and the parenthesized list of options.
For more information, see the exports(5) manual page.
Start the nfs-server service, and configure the service to start following a system reboot:
If the server will serve NFSv4 clients, edit /etc/idmapd.conf and edit the definition for the Domain parameter to specify the DNS domain name of the server, for example:
This setting prevents the owner and group being unexpectedly listed as the anonymous user or group ( nobody or nogroup ) on NFS clients when the all_squash mount option has not been specified.
If you need to allow access through the firewall for NFSv4 clients only, use the following commands:
This configuration assumes that rpc.nfsd listens for client requests on TCP port 2049.
If you need to allow access through the firewall for NFSv3 clients as well as NFSv4 clients:
Edit /etc/sysconfig/nfs and create port settings for handling network mount requests and status monitoring:
The port values shown in this example are the default settings that are commented-out in the file.
Edit /etc/sysctl.conf and configure settings for the TCP and UDP ports on which the network lock manager should listen:
To verify that none of the ports that you have specified in /etc/sysconfig/nfs or /etc/sysctl.conf is in use, enter the following commands:
If any port is in use, use the lsof -i command to determine an unused port and amend the setting in /etc/sysconfig/nfs or /etc/sysctl.conf as appropriate.
Shut down and reboot the server.
NFS fails to start if one of the specified ports is in use, and reports an error in /var/log/messages . Edit /etc/sysconfig/nfs or /etc/sysctl.conf as appropriate to use a different port number for the service that could not start, and attempt to restart the nfslock and nfs-server services. You can use the rpcinfo -p command to confirm on which ports RPC services are listening.
Restart the firewall service and configure the firewall to allow NFSv3 connections:
The port values shown in this example assume that the default port settings in /etc/sysconfig/nfs and /etc/sysctl.conf are available for use by RPC services. This configuration also assumes that rpc.nfsd and rpcbind listen on ports 2049 and 111 respectively.
Use the showmount -e command to display a list of the exported file systems, for example:
showmount -a lists the current clients and the file systems that they have mounted, for example:
To be able to use the showmount command from NFSv4 clients, MOUNTD_PORT must be defined in /etc/sysconfig/nfs and a firewall rule must allow access on this TCP port.
If you want to export or unexport directories without editing /etc/exports and restarting the NFS service, use the exportfs command. The following example makes /var/dev available with read and write access by all clients, and ignores any existing entries in /etc/exports .
For more information, see the exportfs(8) , exports(5) , and showmount(8) manual pages.
6.2.2В Mounting an NFS File System
To mount an NFS file system on a client:
Install the nfs-utils package:
Use showmount -e to discover what file systems an NFS server exports, for example:
Use the mount command to mount an exported NFS file system on an available mount point:
This example mounts /usr/local/apps exported by host01.mydoc.com with read-only permissions on /apps . The nosuid option prevents remote users from gaining higher privileges by running a setuid program.
To configure the system to mount an NFS file system at boot time, add an entry for the file system to /etc/fstab , for example:
For more information, see the mount(8) , nfs(5) , and showmount(8) manual pages.
6.3В About Samba
Samba is an open-source implementation of the Server Message Block (SMB) protocol that allows Oracle Linux to interoperate with Windows systems as both a server and a client. Samba can share Oracle Linux files and printers with Windows systems, and it enables Oracle Linux users to access files on Windows systems. Samba uses the NetBIOS over TCP/IP protocol that allows computer applications that depend on the NetBIOS API to work on TCP/IP networks.
6.3.1В Configuring a Samba Server
To configure a Samba server:
Install the samba and samba-winbind packages:
Edit /etc/samba/smb.conf and configure the sections to support the required services, for example:
The [global] section contains settings for the Samba server. In this example, the server is assumed to be a member of an Active Directory (AD) domain that is running in native mode. Samba relies on tickets issued by the Kerberos server to authenticate clients who want to access local services.
The [printers] section specifies support for print services. The path parameter specifies the location of a spooling directory that receives print jobs from Windows clients before submitting them to the local print spooler. Samba advertises all locally configured printers on the server.
The [homes] section provide a personal share for each user in the smbusers group. The settings for browsable and writable prevent other users from browsing home directories, while allowing full access to valid users.
The [apps] section specifies a share named apps , which grants Windows users browsing and read-only permission to the /usr/local/apps directory.
Configure the system firewall to allow incoming TCP connections to ports 139 and 445, and incoming UDP datagrams on ports 137 and 138:
Add similar rules for other networks from which Samba clients can connect.
The nmdb daemon services NetBIOS Name Service requests on UDP port 137 and NetBIOS Datagram Service requests on UDP port 138.
The smbd daemon services NetBIOS Session Service requests on TCP port 139 and Microsoft Directory Service requests on TCP port 445.
Start the smb service, and configure the service to start following a system reboot:
If you change the /etc/samba/smb.conf file and any files that it references, the smb service will reload its configuration automatically after a delay of up to one minute. You can force smb to reload its configuration by sending a SIGHUP signal to the service daemon:
Making smb reload its configuration has no effect on established connections. You must restart the smb service or the existing users of the service must disconnect and then reconnect.
To restart the smb service, use the following command:
For more information, see the smb.conf(5) and smbd(8) manual pages and https://www.samba.org/samba/docs/.
6.3.2В About Samba Configuration for Windows Workgroups and Domains
Windows systems on an enterprise network usually belong either to a workgroup or to a domain.
Workgroups are usually only configured on networks that connect a small number of computers. A workgroup environment is a peer-to-peer network where systems do not rely on each other for services and there is no centralized management. User accounts, access control, and system resources are configured independently on each system. Such systems can share resources only if configured to do so.
A Samba server can act as a standalone server within a workgroup.
More typically, corporate networks configure domains to allow large numbers of networked systems to be administered centrally. A domain is a group of trusted computers that share security and access control. Systems known as domain controllers provides centralized management and security. Windows domains are usually configured to use Active Directory (AD), which uses the Lightweight Directory Access Protocol (LDAP) to implement versions of Kerberos and DNS providing authentication, access control to domain resources, and name service. Some Windows domains use Windows NT4 security, which does not use Kerberos to perform authentication.
A Samba server can be a member of an AD or NT4 security domain, but it cannot operate as a domain controller. As domain member Samba server must authenticate itself with a domain controller and so is controlled by the security rules of the domain. The domain controller authenticates clients, and the Samba server controls access to printers and network shares.
6.3.2.1В Configuring Samba as a Standalone Server
A standalone Samba server can be a member of a workgroup. The following [global] section from /etc/samba/smb.conf shows an example of how to configure a standalone server using share-level security:
The client provides only a password and not a user name to the server. Typically, each share is associated with a valid users parameter and the server validates the password against the hashed passwords stored in /etc/passwd , /etc/shadow , NIS, or LDAP for the listed users. Using share-level security is discouraged in favor of user-level security, for example:
In the user security model, a client must supply a valid user name and password. This model supports encrypted passwords. If the server successfully validates the client’s user name and password, the client can mount multiple shares without being required to specify a password. Use the smbpasswd command to create an entry for a user in the Samba password file, for example:
The user must already exist as a user on the system. If a user is permitted to log into the server, he or she can use the smbpasswd command to change his or her password.
If a Windows user has a different user name from his or her user name on the Samba server, create a mapping between the names in the /etc/samba/smbusers file, for example:
The first entry on each line is the user name on the Samba server. The entries after the equals sign (=) are the equivalent Windows user names.
Only the user security model uses Samba passwords.
The server security model, where the Samba server relies on another server to authenticate user names and passwords, is deprecated as it has numerous security and interoperability issues.
6.3.2.2В Configuring Samba as a Member of an ADS Domain
In the Activity Directory Server (ADS) security model, Samba acts as a domain member server in an ADS realm, and clients use Kerberos tickets for Active Directory authentication. You must configure Kerberos and join the server to the domain, which creates a machine account for your server on the domain controller.
To add a Samba server to an Active Directory domain:
Edit /etc/samba/smb.conf and configure the [global] section to use ADS:
It might also be necessary to specify the password server explicitly if different servers support AD services and Kerberos authentication:
Install the krb5-server package:
Create a Kerberos ticket for the Administrator account in the Kerberos domain, for example:
This command creates the Kerberos ticket that is required to join the server to the AD domain.
Join the server to the AD domain:
In this example, the AD server is winads.mydom.com and password is the password for the Administrator account.
The command creates a machine account in Active Directory for the Samba server and allows it to join the domain.
Restart the smb service:
6.3.2.3В Configuring Samba as a Member of a Windows NT4 Security Domain
If the Samba server acts as a Primary or Backup Domain Controller, do not use the domain security model. Configure the system as a standalone server that uses the user security model instead. See Section 6.3.2.1, “Configuring Samba as a Standalone Server”.
The domain security model is used with domains that implement Windows NT4 security. The Samba server must have a machine account in the domain (a domain security trust account). Samba authenticates user names and passwords with either a primary or a secondary domain controller.
To add a Samba server to an NT4 domain:
On the primary domain controller, use the Server Manager to add a machine account for the Samba server.
Edit /etc/samba/smb.conf and configure the [global] section to use ADS:
Join the server to the domain:
In this example, the primary domain controller is winpdc.mydom.com and password is the password for the Administrator account.
Restart the smb service:
Create an account for each user who is allowed access to shares or printers:
In this example, the account’s login shell is set to /sbin/nologin to prevent direct logins.
6.3.3В Accessing Samba Shares from a Windows Client
To access a share on a Samba server from Windows, open Computer or Windows Explorer, and enter the host name of the Samba server and the share name using the following format:
If you enter \\ server_name , Windows displays the directories and printers that the server is sharing. You can also use the same syntax to map a network drive to a share name.
6.3.4В Accessing Samba Shares from an Oracle Linux Client
To be able to use the commands described in this section, use yum to install the samba-client and cifs-utils packages.
You can use the findsmb command to query a subnet for Samba servers. The command displays the IP address, NetBIOS name, workgroup, operating system and version for each server that it finds.
Alternatively, you can use the smbtree command, which is a text-based SMB network browser that displays the hierarchy of known domains, servers in those domains, and shares on those servers.
The GNOME and KDE desktops provide browser-based file managers that you can use to view Windows shares on the network. Enter smb: in the location bar of a file manager to browse network shares.
To connect to a Windows share from the command line, use the smbclient command:
After logging in, enter help at the smb:\> prompt to display a list of available commands.
To mount a Samba share, use a command such as the following:
In the previous command, the credentials file contains settings for username , password , and domain , for example:
The argument to domain can be the name of a domain or a workgroup.
As the credentials file contains a plain-text password, use chmod to make it readable only by you, for example:
If the Samba server is a domain member server in an AD domain and your current login session was authenticated by the Kerberos server in the domain, you can use your existing session credentials by specifying the sec=krb5 option instead of a credentials file:
For more information, see the findsmb(1) , mount.cifs(8) , smbclient(1) , and smbtree(1) manual pages.
Copyright В© 2020, 2021, Oracle and/or its affiliates. Legal Notices
Источник