- How to add or delete a samba user under Linux
- Adding a Linux user account
- Adding Samba user
- Allowing user to access samba share
- Deleting the Samba user
- Установка и настройка файлового сервера Samba на Ubuntu
- Подготовка сервера
- 1. Время
- 2. Брандмауэр
- Установка и запуск Samba
- Создание первой шары и предоставление к ней гостевого доступа (анонимного)
- Доступ к папке по логину и паролю
- Доступ к папке определенным пользователям и группам
- Samba Add a User
- Step # 1: Add a user joe to UNIX/Linux system
- Step # 2: Add a user to samba
- Step # 3: Add a user to a Samba share
- Step #4: Restart the samba
- A note about adding users on Samba version 4.x
How to add or delete a samba user under Linux
To add a new user to access a samba share you need to first create a server user account using “useradd” command and then use the same account to add the samba user. Follow the steps givenbelow to add user john and give him the access to a samba share.
Adding a Linux user account
One way for a user to browse a Samba share is have a UNIX account on the Samba server. This is done via the commands ‘useradd [username]‘ and ‘passwd [username]‘. If you already have the user account created on the system, skip the part below and proceed to add samba user directly.
Set the password for the new user created.
Adding Samba user
Once the user has a local account their corresponding Samba samba user can be added using smbpasswd -a command. The smbpasswd command when used with -a option adds the new samba user and also allows you to set the password for the new samba user. For example for the user john, use the command below:
The -a switch adds john to the Samba password list.
To modify an existing Samba user’s Samba password (using the example john user again):
Allowing user to access samba share
Configure the Samba share in the /etc/samba/smb.conf configuration file to allow the new user to browse the share:
Use testparm to show your updated share. Reload the smb.conf configuration file with below command.
For RHEL/CentOS 6
For RHEL/CentOS 7
Deleting the Samba user
In order to delete the samba user, use the steps below. make sure you delete the corresponding UNIX user from the server as well if required.
1. delete samba user(john) using smbpasswd command with -x option.
2. You can now delete the UNIX OS user john along with all the files associated with the user like home directory, using the ‘userdel -r’ command.
Источник
Установка и настройка файлового сервера 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 оставить как в примерах выше.
Источник
Samba Add a User
I am using Fedora Linux and I would like to add a user called joe to Samba. How do I add a user SMB share? How can I add a users to Samba?
[donotprint]
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Samba |
Est. reading time | 5m |
[/donotprint]The procedure is as follows to add a user to samba server:
NOTE : Unlike Samba 3, Samba 4 does not require a local Unix user for each Samba user that is created. Please see this note for more info.
Step # 1: Add a user joe to UNIX/Linux system
adduser command adds user to the system according to command line options and configuration information in /etc/adduser.conf. They are friendlier front ends to the low level tools like useradd.
Type any one of the following command:
# useradd joe
# passwd joe
OR
adduser joe
Step # 2: Add a user to samba
Now user joe has account on Linux/UNIX box. Use smbpasswd command to specifies that the username following should be added to the local smbpasswd file:
# smbpasswd -a joe
Step # 3: Add a user to a Samba share
By default user gets access to /home/joe from windows system. Let us say you want to give joe access to /data/accounts (make sure directory /data/accounts exists) directory. Open /etc/samba/smb.conf file and add/modify share called [accounts]:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Step #4: Restart the samba
# service smb restart
OR
# /etc/init.d/smb reload
A note about adding users on Samba version 4.x
Unlike Samba version 3.x and earlier, Samba version 4.x does not require a local Unix/Linux user for each Samba user that is created. The command is as follows for adding users into Samba Active Directory:
# /usr/local/samba/bin/samba-tool user add USERNAME-HERE
OR
# samba-tool user add USERNAME-HERE
Please see Samba AD DC howto for more info.
See also:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Good info; worked as expected under CentOS 5.5
Thanks!
Dear Nixcraft,
Would you pls tell me how to do this without prompting win users for a password? I have been banging my head on wall over this Gentleman. Following is my smb.conf.
[global]
workgroup = MYGROUP
server string = Samba Server Version %v
security = share
passdb backend = tdbsam
load printers = yes
cups options = raw
[homes]
comment = Home Directories
browseable = no
writable = yes
; valid users = %S
; valid users = MYDOMAIN\%S
[printers]
comment = All Printers
path = /var/spool/samba
browseable = no
guest ok = no
writable = no
printable = yes
[ux_share]
comment = ux_share
writable = yes
path = /home/ux_share/share
guest ok = yes
browseable = yes
I have added a user called ux_share in the system and created the /home/ux_share/share with the right permission. And created the smbuser ux_share too. Now when I try to access the share from a winbox it prompts for the passw. Please help out Nixcraft. This share is likely to access by several winusers and i have no idea about thier workgroup names whatsoever. This is just a simple share im trying to publish just like an annonymous vsftpd account.
please reply ,
sir/madam
q) what are the steps to be followed to share a folder in Ubuntu and access it from different machine in the network for different clients (eg ,root ,admin ,student..)
Samba permission problem
/home can’t be accessed from windows client for samba.
/tmp can be accessed but /home can’t be accessed.
@yubaraj :
1) restart winbind
2) chmod 777 -R /home
goodluck!
hello, i have a question here..
what a use of 2 user samba in same time….
example i have 2 user samba, John and Billy..
and i created a folder name is ” Work “..
and then, how John and Billy user can access that folder ” Work ” at the same time…
pls reply this..
thank’s a lot…
valid users=John, Billy
i have made two samba users…
harsh & gaurav
…
and made an entry for “valid user ” under [ IT ]
.
I ACCESSED IT FOLDER FROM WINDOWS….ALL WORK FINE TILL HERE….
BUT IF I NOW WANTED TO ACCESS THE SAME IT FOLDER WITH ANOTHER USER …NOW IT IS NOT ASKING FOR ANY PASSWORD….IT JUST GIVING THE PREVIOUS FOLDER SCREEN….
PLZ SORT OUT MY PROBLEM…
Your site make it easy! )
run this in command prompt
net use * /delete
This will clear all existing password cache and will prompt for password
thanks for your support this is very helpfull for my exam thanks
Perfect! Worked on Ubuntu 14.04 with latest SMB. Thank You Very Much!
Getting an error when trying to add a samba user:
$ sudo samba-tool user add timebandit
New Password:
Retype Password:
ERROR(): Failed to add user ‘timebandit’: – unable to parse dn string
File “/usr/lib/python2.7/dist-packages/samba/netcmd/user.py”, line 176, in run
uid=uid, uidnumber=uid_number, gidnumber=gid_number, gecos=gecos, loginshell=login_shell)
File “/usr/lib/python2.7/dist-packages/samba/samdb.py”, line 343, in newuser
dnsdomain = ldb.Dn(self, self.domain_dn()).canonical_str().replace(“/”, “”)
bob@bob-K55A:
Any idea what to do?
I am also getting this error, did you ever find a solutions?
Worked on Ubuntu version 14.04.. thanks dude!
Hallo. what is wrong with me? samba-tool user add temp2 –home-directory=’\\ubuntu\home\temp2 is not creating home directory!
smb.conf:
[Users]
directory_mode: parameter = 0700
read only = no
path = /Users
csc policy = documents
[homes]
comment = Home Directories
browseable = no
read only = no
create mask = 0700
directory mask = 0700
valid users = %S
[home]
path = /Users/home/
read only = no
That last command to restart Samba, for me on Debian Jessie, was:
/etc/init.d/smbd reload
–or–
sudo /etc/init.d/smbd reload
m doing file sharing using SMB protocol on centos linux and when m trying to map the network drive it is asking for username and password…but the problem is that after creating different user and password it never accepts any of those….it only accepts the root username and root as the password…why only root..pls tell me how to solve this problem.
Источник