- Smb ��� ������������ linux
- Ubuntu Documentation
- Client Access — Browsing SMB shares
- Ubuntu Clients
- Windows Clients (XP,Server,Vista, Win7)
- Samba Client — Manual Configuration
- Connecting to a Samba File Server from the command line
- Connecting using CIFS
- Allow non-root users to mount SMB shares
- Automagically mount SMB shares
- Connecting using SMBFS (deprecated)
- Ubuntu Client
- Windows Client
- Установка и настройка файлового сервера Samba на Ubuntu
- Подготовка сервера
- 1. Время
- 2. Брандмауэр
- Установка и запуск Samba
- Создание первой шары и предоставление к ней гостевого доступа (анонимного)
- Доступ к папке по логину и паролю
- Доступ к папке определенным пользователям и группам
Smb ��� ������������ linux
Машины с Linux (UNIX) могут также просматривать и монтировать SMB-ресурсы. Заметьте, что это может быть сделано когда сервером является либо машина с Windows, либо с сервером Samba!
Программа клиента SMB для UNIX-машин включена в дистрибутив Samba. Она обеспечивает ftp-подобный интерфейс командной строки. Вы можете использовать эту утилиту для переноса файлов между ‘сервером’ под управлением Windows и клиентом под Linux.
Большинство дистрибутивов Linux также включают полезный пакет smbfs, который позволяет монтировать и размонтировать SMB-ресурсы. Больше информации о smbfs можно получить дальше.
Для того, чтобы увидеть какие ресурсы доступны на данной машине, выполните команду:
где ‘host’ это имя машины, которую вы хотите видеть. Эта команда вернет список имен ‘сервисов’ — т.е. имен дисков или принтеров к которым может быть получен доступ. До тех пор, пока SMB сервер не будет настроен без управления доступом, он будет запрашивать у вас пароль. Введите в ответ на запрос пароль для пользователя ‘гость (guest)’ или ваш персональный пароль на этой машине.
Вывод этой команды должен выглядеть примерно так:
Browse list показывает другие SMB сервера в сети с доступными ресурсами.
Для использования клиента, выполните следующую команду:
где ‘service’ — имя машины и сервиса. Например, если вы пытаетесь обратиться к директории, которая доступна под именем ‘public’ на машине названной ‘zimmerman’, то имя сервиса должно звучать как \\zimmerman\public. Однако в следствии ограничений оболочки, вам необходимо спрятать обратный слэш, так что в итоге это командная строка выглядеть следующим образом:
где ‘mypasswd’ — символьная строка вашего пароля.
Вы получите приглашение smbclient:
Напечатайте ‘h’ чтобы получить помощь об использовании smbclient:
Если вы умеете использовать ftp, то вам не будут нужны справочные страницы о smbclient.
Хотя вы можете использовать smbclient для тестирования, вы скоро устанете использовать его в работе. Для работы вам скорее всего понадобится пакет smbfs. Smbfs поставляется с двумя простыми утилитами, smbmount и smbumount. Они работают подобно mount и umount для SMB-ресурсов.
Одно важное замечание: Чтобы использовать эти утилиты, у вас должна быть поддержка smbfs вкомпилированная в ядро!
Следующий пример показывает типичное использование smbmount для монтирования SMB-ресурса, названного «customers» с машины с именем «samba1»:
Запуск команды mount покажет вам, что ресурс смонтирован, точно также как и через экспорт NFS:
Пожалуйста прочитайте справочные страницы smbmount и smbumount для дополнительной информации о описанных выше операциях.
Источник
Ubuntu Documentation
Client Access — Browsing SMB shares
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):
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
Connect to a SMB share with
Enter you user password.
You can connect directly with
but your password will show on the screen (less secure).
Once connected you will get a prompt that looks like this :
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).
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.
Change «user» to the username you wish to add to the samba group.
In the «group» section add your group you wish to allow to mount SMB shares
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):
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.
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:
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:
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:
Now create a directory where you want to mount your share (e.g. /media/samba_share):
Now, using any editor, and add a line to /etc/fstab for your SMB share as follows:
Add a line for your SMB share:
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,
You can unmount the share with :
If you wish to increase security at the expense of convenience, use this line in /etc/fstab
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 :
CIFS may cause a shutdown error.
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:
To allow non root accounts to mount shares, change the permissions on the smbmnt program thus:
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):
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):
In order to have a share mounted automatically every time you reboot, you need to do the following:
Open a shell as root
Create a file containing your Windows/Samba user account details:
. it should contain two lines as follows:
Change the permissions on the file for security:
Now create a directory where you want to mount your share (e.g. /mnt/data):
Now edit the file system table (/etc/fstab) and add a line as follows:
. 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.
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).
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).
Where «hostname» = the name of your samba server.
Samba/SambaClientGuide (последним исправлял пользователь milamipha 2014-01-07 20:02:19)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Источник
Установка и настройка файлового сервера Samba на Ubuntu
Samba позволяет настроить файловое хранилище различных масштабов — от малых офисов для крупных организаций. В данной инструкции мы рассмотрим процесс настройки файлового сервера. Сначала мы выполним установку и базовую настройку с предоставлением гостевого доступа. После будет приведены примеры разграничения доступа по пользователям, группам и пользователям Active Directory.
Подготовка сервера
1. Время
Для корректного отображения дат, необходимо позаботиться о синхронизации времени. Для этого будем использовать демон chrony. Установим его:
apt-get install chrony
Разрешим автозапуск сервиса:
systemctl enable chrony
2. Брандмауэр
По умолчанию, в системах на базе Debian брандмауэр разрешает все соединения. Но если в нашем случае мы используем брандмауэр, необходимо открыть порты:
iptables -I INPUT -p tcp —dport 445 -j ACCEPT
iptables -I INPUT -p udp —dport 137:138 -j ACCEPT
iptables -I INPUT -p tcp —dport 139 -j ACCEPT
* где порт 445 используется для samba, а порты 137, 138 и 139 — для работы NetBIOS (использование имени компьютера для доступа).
apt-get install iptables-persistent
Установка и запуск Samba
Установка выполняется из репозитория одной командой:
apt-get install samba
Разрешаем автостарт сервиса:
systemctl enable smbd
И проверим, что сервис запустился:
systemctl status smbd
Проверяем, что сервер самба позволяет к себе подключиться. Для этого можно с компьютера обратиться к серверу по SMB, например, на компьютере с Windows это можно сделать из проводника, прописав путь к серверу с двух слэшей:
* в данном примере мы подключаемся к серверу Samba с IP-адресом 192.168.1.15.
Если мы настроили сервер правильно, система откроет пустую папку. На данном этапе проверка закончена и мы можем переходить к созданию первой шары.
Создание первой шары и предоставление к ней гостевого доступа (анонимного)
Разберем самый простой пример предоставления доступа к папке — анонимный доступ всем пользователям без запроса пароля.
Открываем на редактирование конфигурационный файл samba:
И добавляем настройку для общей папки:
[Общая папка]
comment = Public Folder
path = /data/public
public = yes
writable = yes
read only = no
guest ok = yes
create mask = 0777
directory mask = 0777
force create mode = 0777
force directory mode = 0777
- [Общая папка] — имя общей папки, которое увидят пользователи, подключившись к серверу.
- comment — свой комментарий для удобства.
- path — путь на сервере, где будут храниться данные.
- public — для общего доступа. Установите в yes, если хотите, чтобы все могли работать с ресурсом.
- writable — разрешает запись в сетевую папку.
- read only — только для чтения. Установите no, если у пользователей должна быть возможность создавать папки и файлы.
- guest ok — разрешает доступ к папке гостевой учетной записи.
- create mask, directory mask, force create mode, force directory mode — при создании новой папки или файла назначаются указанные права. В нашем примере права будут полные.
Создаем каталог на сервере и назначим права:
mkdir -p /data/public
chmod 777 /data/public
Применяем настройки samba, перезагрузив сервис:
systemctl restart smbd
Пробуем подключиться к папке. Мы должны зайти в нее без необходимости ввода логина и пароля.
Доступ к папке по логину и паролю
Теперь создадим каталог, в который вход будет разрешен только авторизованным пользователям.
Открываем конфигурационный файл samba:
Добавляем настройку для новой папки:
[Папка сотрудников]
comment = Staff Folder
path = /data/staff
public = no
writable = yes
read only = no
guest ok = no
create mask = 0777
directory mask = 0777
force create mode = 0777
force directory mode = 0777
* эти настройки, во многом, похожи на те, что использовались в примере выше. Вот основные различия:
- path = /data/staff — используем новый путь до папки.
- public = no — запрещаем публичный доступ.
- guest ok = no — не разрешаем гостевое подключение.
Создаем каталог для новой папки:
Задаем права на созданный каталог:
chmod 777 /data/staff
Создаем пользователя в системе Linux:
* где staff1 — имя пользователя.
Задаем пароль для пользователя:
Теперь создадим пользователя в samba:
smbpasswd -a staff1
systemctl restart smbd
Пробуем зайти на сервер — общую папку мы должны открыть без авторизации, а при попытке открыть папку сотрудников должно появиться окно ввода логина и пароля.
Если мы авторизованы на компьютере, с которого пытаемся подключиться к серверу, под той же учетной записью, что создали для доступа к папке, samba может и не потребовать аутентификации.
Доступ к папке определенным пользователям и группам
Теперь создадим папку, доступ к которой будут иметь ограниченное количество пользователей.
Открываем конфигурационный файл samba:
Добавляем настройку для новой папки:
[Приватная папка]
comment = Private Folder
path = /data/private
public = no
writable = no
read only = yes
guest ok = no
valid users = admin, staff2, staff3, @privateusers
write list = admin, staff2
create mask = 0777
directory mask = 0777
force create mode = 0777
force directory mode = 0777
inherit owner = yes
* стоит обратить внимание на следующие настройки:
- path = /data/private — используем новый путь до папки.
- writable = no и read only = yes — в данном примере мы разрешим запись в каталог только некоторым пользователям. Поэтому общие настройки, разрешающие запись в папку, должны быть запрещены.
- valid users — список пользователей, которым разрешено подключаться к каталогу. В данном примере разрешения работают для пользователей admin, staff2 и staff3, а также для всех, кто входим в группу privateusers.
- write list — список пользователей, которые имеют доступ к папке на чтение и запись. В данном примере мы разрешаем это только для пользователей admin и staff2.
- inherit owner — опция позволяем включить наследование владельца при создании папок и файлов.
* если мы хотим, чтобы доступ к каталогу был полный у определенных пользователей (без разделения на тех, кто может только читать и тех, кто может также писать в папку), то опцию write list можно не указывать, а опции writable и read only оставить как в примерах выше.
Источник