Как подключиться к samba серверу из windows

Пожалуй нет ни одного офиса, в котором не применялись бы общие ресурсы локальной сети, будь то папки или принтеры. Крупные и средние компании используют возможности Active Directory, компании поменьше – используют штатные средства ОС Windows или Samba, но на серверах под управлением ОС Linux. Рассмотрим все случаи, как настроить Samba.

Что такое Samba?

Samba – серверное приложение, реализующее доступ клиентских терминалов к папкам, принтерам и дискам про протоколу SMB/CIFS.

Описание структуры Samba

Настройка общих папок в Linux

Установка и настройка Samba-сервер для Ubuntu выполняется следующими этапами.

Обновляем информацию о репозиториях и устанавливаем обновления для существующих пакетов в системе:

apt-get update && apt-get upgrade

Устанавливаем пакет Samba:

apt-get install -y samba samba-client

Создадим резервную копию файла конфигурации:

cp /etc/samba/smb.conf /etc/samba/smb.conf_sample

Создадим директории для файлов, например в каталоге /media:

mkdir /media/samba

Важно! По умолчанию, директория /media располагается в корне системы /, для нее редко создается свой раздел. По этой причине возможно переполнение корневого раздела. Во избежание этой неприятной ситуации, рекомендуем монтировать отдельный жесткий диск в /media/samba.

Создаем каталог для всех пользователей:

mkdir /media/samba/public

Изменим права доступа к каталогу:

chmod -R 0755 /media/samba/public

Также следует воспользоваться командой chown для смены владельца и/или группы.

Создаем директорию для ограниченного круга лиц:

mkdir /media/samba/private

С помощью системных инструментов создадим группу пользователей:

groupadd smbgrp

Добавляем пользователей Samba:

useradd user1

Созданных пользователей добавляем в группу:

usermod -aG smbgrp user1

Изменим группу, которой принадлежит приватная директория:

chgrp smbgrp /media/samba/private

С помощью инструментов Samba создадим пароль для добавленного пользователя:

smbpasswd -a user1

С помощью текстового редактора, например, nano, редактируем конфигурационный файл samba:

nano /etc/samba/smb.conf

Удаляем все строки из файла. Вставляем следующие:

[global]
workgroup = WORKGROUP
security = user
map to guest = bad user
wins support = no
dns proxy = no
[public]
path = /media/samba/public
guest ok = yes
force user = nobody
browsable = yes
writable = yes
[private]
path = /media/samba/private
valid users = @smbgrp
guest ok = no
browsable = yes
writable = yes

Сохраняем используя сочетание Ctrl + X, затем нажимаем Y и Enter.

Объясним значения строк. конфигурационный файл состоит из трех секций:

global – данная секция отвечает за общие настройки Samba-сервера;

public и private – секции описания настроек директорий общего доступа.

В секции global присутствуют пять параметров:

  • workgroup – рабочая группа. Для упрощения работы пользователей WORKGROUP указывается, как группа по умолчанию. Если в вашей сети имя рабочей группы изменено, то следует изменить это значение и для Samba;
  • security – уровень безопасности сервера. Значение user означает авторизацию по паре логин/пароль;
  • map to guest – параметр определяет способ обработки запросов. Значение bad user означает, что запросы с неправильным паролем будут отклонены, даже если такое имя пользователя существует;
  • wins support – включить или выключить поддержку WINS;
  • dns proxy – возможность проксирования запросов к DNS.

Настройки директорий выполняются в соответствующих секциях:

path – полный путь до директории на жестком диске;

guest ok – возможность доступа к каталогу без пароля (гостевой);

browsable – показывать ли каталог (“шару”) на сервере среди прочих. Если параметр установлен как “no”, то доступ будет возможен по полному пути, например ip-addresshidden_directory;

force user – пользователь от которого ведется работа с каталогом. Для повышения безопасности сервера, обычно используют nobody. Главное, не использовать пользователя root – это небезопасно.

writable – установка значения как “yes” позволяет пользователю выполнять действия над файлами внутри каталога – переименование, добавление, удаление, перемещение в подкаталог и копирование;

valid users – список пользователей у которых есть доступ к каталогу. Если пользователей несколько, их имена указываются через запятую. Если необходим доступ для пользователей принадлежащих группе, перед именем группы устанавливается символ ”at” @ (“собака”).

Важно! Имя директории общего доступа, отображаемое пользователям, равно имени секции в которой оно описано.

Проверяем настройки с помощью команды:

testparm -s

Перезапускаем сервер:

service smbd restart

service nmbd restart

Настроим межсетевой экран. Для этого в правилах откроем TCP-порты 139 и 445, а также UDP-порты 137 и 138, но только для тех подсетей, которым доверяете. Для указания собственного диапазона адресов, замените значение после ключа “-s”:

iptables -A INPUT -p tcp -m tcp --dport 445 -s 10.0.0.0/24 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 139 -s 10.0.0.0/24 -j ACCEPT

iptables -A INPUT -p udp -m udp --dport 137 -s 10.0.0.0/24 -j ACCEPT

iptables -A INPUT -p udp -m udp --dport 138 -s 10.0.0.0/24 -j ACCEPT

Для сохранения правил и применения их после перезагрузки сервера следует воспользоваться пакетом iptables-persistent. Установим его:

apt-get install iptables-persistent

Входе установки пакета, программа предложит запомнить существующие правила iptables. Подтверждаем это действие.

Для проверки существующих правил используем:

iptables -L

Настройка общих папок в Windows

По аналогии с Linux, настроим общий доступ к папкам public и private, но в ОС Windows.

Для создания общего доступа к каталогу без парольной защиты, необходимо настроить ограничения защиты в панели управления. Для этого открываем:

Панель управления → Сеть → Центр управления сетями и общим доступом → Расширенные настройки общего доступа.

В обновленном окне открываем раздел “Все сети” и ищем секцию “Общий доступ с парольной защитой”. Устанавливаем параметр в положение “Отключить общий доступ с парольной защитой”. Для сохранения значений параметра кликаем по кнопке “Сохранить изменения”.

Отключаем общий доступ с парольной защитой

Теперь откроем доступ к самому каталогу. Кликаем по папке правой кнопкой мыши, в контекстном меню выбираем “Свойства”. Открываем вкладку “Доступ” и кликаем по “Расширенная настройка”.

Выбираем расширенную настройку

В открывшемся окне расширенных настроек общего доступа отмечаем галочкой “Открыть общий доступ к этой папке”, в поле “Имя общего ресурса” указываем название, которое будет отображено пользователям. Кликаем по кнопке “Разрешения”.

В открывшемся окне, в группах пользователей выбираем “Все”, а в разрешениях для группы, устанавливаем галку “Полный доступ”. Нажимаем “OK” в этом и остальных окнах.

Выбираем саму группу и разрешения для группы

В окне свойств папки public кликаем по кнопке “Общий доступ”.

Общий доступ к файлам в Samba | Serverspace

В открывшемся окне добавляем пользователя “Все”, а также делегируем права на “Чтение и запись”. Кликаем по кнопке “Поделиться”.

Выбираем права и делимся ими с пользователями

В обновленном окне нажимаем “Готово”.

Нажимаем готово

Настроим папку общего доступа, но для ограниченного круга лиц.

Кликаем правой кнопкой мыши по папке, выбираем “Свойства”.

В открывшемся окне переходим на вкладку “Доступ”. Кликаем по кнопке “Расширенные настройки”.

В новом открывшемся окне, устанавливаем галку “Открыть общий доступ к этой папке”. Затем кликаем по кнопке “Разрешения”.

Открываем общий доступ к этой папке

В открывшемся окне, в поле “Группы или пользователи” выбираем “Все” и нажимаем кнопку “Удалить”.

Удаляем пользователя

Таким образом установлен запрет на анонимный доступ к папке.

Окно обновится. Кликаем по кнопке “Добавить”.

В открывшемся окне кликаем по кнопке “Дополнительно”.

Выбираем дополнительные параметры

Окно изменится в размере. Кликаем по кнопке “Поиск”. Двойным кликом выбираем пользователя, которому необходим доступ к этому каталогу, например, buhgalter.

Добавляем пользователя которому нужен доступ к этому каталогу

В открывшемся окне, при желании, можем добавить еще одного пользователя через “Дополнительно” – “Поиск”. Аналогичным образом можно добавить группу пользователей, например, “Администраторы”, при этом следует понимать, что доступ будет предоставлен всем пользователям из этой группы.

При желании добавляем еще одного пользователя

Установим права доступа для пользователя “buhgalter”. Если требуется полный доступ к директории, устанавливаем галку в соответствующем месте.

Пример установки прав для группы пользователей

Нажимая кнопки “OK” возвращаемся к окну свойств папки, в котором кликаем по кнопке “Общий доступ”.

Возвращаемся обратно и выбираем общий доступ

В данном окне необходимо найти и добавить пользователя “бухгалтер”.

Ищем нашего пользователя и добавляем его

В окне выбора пользователей и групп кликаем по кнопке “Дополнительно”.

Выбираем дополнительные параметры

Окно снова изменит свои размеры. Кликаем по кнопке “Поиск”. В найденном ниже списке пользователей и групп выбираем искомого пользователя. Выбираем его двойным кликом.

Выбираем пользователей

В оставшемся окне проверяем правильно ли указан пользователи и нажимаем кнопку “OK”.

Проверяем выбранного пользователя

Устанавливаем требуемый уровень разрешений для пользователя и кликаем по кнопке “Поделиться”.

Добавляем права и делимся ими

Кликаем по кнопке “Готово”.

Теперь папка общего доступа доступна

Подключение к общим папкам из Linux

Для подключения к общим папкам из среды Linux требуется установка отдельного программного обеспечения – smbclient. Установим:

sudo apt-get install smbclient

Для подключения к серверу используется следующий формат команды:

smbclient -U <Имя_пользователя> <IP-адрес><Имя_каталога_на_сервере>

Пример:

smbclient -U buhgalter 10.0.0.1public

Для того, Чтобы не вводить эту команду каждый раз, можно настроить монтирование общей директории как сетевого диска. Для этого установим пакет cifs-utils:

sudo apt-get install cifs-utils

Монтирование выполняется по следующему шаблону:

mount -t cifs -o username=<Имя_пользователя>,password= //<IP-адрес>/<Общий каталог> <Точка монтирования>

Пример:

mount -t cifs -o username=Everyone,password= //10.0.0.1/public /media

Важно! Если требуется подключение к общим папкам расположенным на Windows-сервере, то в для не защищенных паролем директорий, в качестве имени пользователя, следует использовать “Everyone”. Для подключения к Linux-серверу рекомендуем использовать в качестве имени пользователя “nobody”. В случае доступа к защищенным директориям следует использовать те учетные данные, которые вы указали.

Подключение к общим папкам из Windows

Подключение к удаленным папкам из среды Windows выполняется немного иначе. Для этого в проводнике или окне запуска программ (Windows + R), следует использовать следующий шаблон:

<IP-адрес><имя_папки>

Указав просто IP-адрес сервера вы получите список общих папок.

Список общих папок

При подключении к Windows-серверу, система безопасности может потребовать ввод учетных данных. Для подключения к общей открытой папке используем Everyone, а поле пароля оставляем пустым.

Для подключения к общей папке выбираем Everyone и пустое поле для пароля

При подключении к Linux-серверу из ОС Windows, следует использовать указанный ранее шаблон:

<IP-адрес><имя_папки>

или просто адрес сервера:

<IP-адрес>

Как создать общий сетевой ресурс в Samba

Создайте директорию, которую в хотите сделать общей:

mkdir /home//

Создайте бэкап, если что-то пойдет не так:

sudo cp /etc/samba/smb.conf ~

Отредактируйте файл “/etc/samba/smb.conf”:

sudo nano /etc/samba/smb.conf

Добавьте следующее содержимое в файл:

[]
path = /home//
valid users =
read only = no

Заполните файл своими данными, сохраните его и затем закройте

Перезапустим Samba:

sudo service smbd restart

Использую данную команду проверьте вашу директорию smb.conf на ошибки:

testparm

Чтобы получить доступ к вашему общему сетевому ресурсу:

sudo apt-get install smbclient
# Просмотр всех общих ресурсов:
smbclient -L /// -U
# Подключение:
smbclient /// -U

Note 1: Чтобы подключиться к вашему общему сетевому ресурсу используйте имя вашего пользователя () и пароль, который находится “smb:////”
Учтите, что “” значение передается в “[]”,
другими словами, имя общего ресурса, которое вы ввели в “/etc/samba/smb.conf”.
Note 2: Группа пользователей samba по умолчанию это – “WORKGROUP”.

If you are searching for a compatible and open source software for accessing and sharing files, folders and other data, then come across the Samba share. It provides a cross-platform adaptable environment between Windows and other systems. In this tutorial, I have outlined every ins and outs on how to access Samba share from Windows. So, go over it, try accessing Samba share from your Windows and leverage the benefits of this interoperable service.

Key Takeaways

  • Learning basic commands of the command prompt, PowerShell.
  • Understanding the fact of accessing Samba shares from Windows.
  • Learning how to connect and disconnect Samba drives.

Requirements

  • Users must have Samba already installed and configured properly.
  • Users must have Samba connection on.

Process Flow Chart

[Windows Used Throughout the Tutorial: Windows 10]Flowchart-How to access Samba share from Windows

You can easily access samba share from Windows only employing some compact and effortless steps. Here, I am going to introduce two types of methods that will help you to access the Samba share.

You can read the Comparative Analysis of Methods to know more related terms regarding samba shares.

In the following section, I will show two cases of GUI (Graphical User Interface) for accessing Samba share from Windows.

To access Samba share using File Explorer follow the manual procedure shown below:

Steps to Follow >

➊ Press WIN+E or you can click on the Folder icon like the image below to open file explorer:Clicking on folder icon to open file explorer❷ Enter the path of the Samba share in the address bar like the format below and click ENTER:

\\192.168.231.128\sambashare

EXPLANATION

  • \\192.168.231.128: Represents Samba server IP address.
  • \sambashare: Indicates the shared folder.

Here, ‘192.168.231.128’ is my system’s IP address and ‘sambashare’ is the folder I want to share.

❸ Now, enter your network credentials when prompted to you and click OK.Entering credentials ❹ Once done with the connection, you can access all the shared files and folders inside the shared one.Accessing folders from Samba share using file explorer Following the above steps, I can access the new_samba folder inside the Samba share.

Map Network Drive is another way of accessing Samba share. Follow the steps to exercise it:

Steps to Follow >

➊ Go to file explorer and click on Map network drive under the Computer tab like the following image:clicking on 'Map network drive'❷ Now, choose a Drive, enter the path for the Samba share and click Finish.Choosing a drive and path for Samba share From the image, you can see that I have chosen drive B: for my desired Samba share.

❸ If there prompts the credential requirements, then provide your user name and Samba password.Entering credentials to accessAfter this, you can see that the Samba shared folder has been mapped to the selected drive.New Samba share drive created❹ Now, double click on the new drive and you can access the files and folders inside the Samba share.Accessing Samba share from mapped-driveFrom the snapshot above, you can see that I can access my new_samba folder inside sambashare.

Read More: Install, Configure and Connect Samba on Ubuntu Using GUI

Below I will demonstrate two different cases of ‘Command line shell’ for accessing Samba share from Windows.

To access the Samba shares’ contents from the command prompt follow the steps below:

Steps to Follow >

➊ Press WIN+R, type cmd and hit ENTER. You will prompt to the command line interface.

❷ Now, write the following command in the command prompt to connect to the Samba share:

net use P: \\192.168.231.128\sambashare /user:nadiba 1234

EXPLANATION

  • net use: Manages network connectivity.
  • P: Indicates the assigned drive letter for the Samba share. I have chosen ‘P’ drive.
  • \\192.168.231.128\sambashare: Represents Samba server IP address and the shared folder.
  • /user:nadiba: Specifies the Samba username. ‘nadiba’ is my Samba username.
  • 1234: Represents Samba user password. Here, my system’s Samba user password is ‘1234’.

Writing command in command prompt to access Samba shareIf the given credentials are correct, you will see ‘The command completed successfully.’ like the above image.

❸ You will find then that the Samba share has been mapped to the assigned drive letter like the following image:New Samba drive created using command promptThus, you can access the samba shares’ contents.

You can also access Samba shares from PowerShell by following the given steps:

Steps to Follow >

➊ First, open PowerShell and write the following command to create a new drive:

New-PSDrive -Name A -PSProvider FileSystem -Root \\192.168.231.128\sambashare -Credential (Get-Credential)

EXPLANATION

  • New-PSDrive: Creates a new PowerShell drive.
  • -Name A: Represents the letter of the drive you want to assign. I have preferred ‘A’ for my drive.
  • -PSProvider FileSystem: Filesystem provider is used for the new drive.
  • -Root \\192.168.231.128\sambashare: Specifies the path location of the Samba share.
  • -Credential: The requirements to access the Samba share.
  • (Get-Credential): Prompts you to provide the username and password to access Samba share.

Writing command in PowerShell to access Samba share ❷ Now, you will prompt to a new window to provide the Samba username and password. Provide the requirements and click OK.Inserting PowerShell credentialsYou can see in the following screenshot that the Samba share has been mapped to the specific drive you chose.New drive created using PowerShell❸ Now, you can navigate to the drive whenever you want by running the command below:

cd A:

EXPLANATION

  • cd A: Navigates to the drive A.

Navigating to new Samba drive using PowerShellAfter navigating to the new Samba drive you can interact with the contents in the Samba share.

Read More: How to Install, Configure and Connect Samba Client on Ubuntu

Comparative Analysis of Methods

While accessing Samba share from Windows, you have two options- using GUI or command line shell. Let’s make a comparative analysis between these two methods.

Methods Pros Cons
Method 1
  • User-friendly interface.
  • No syntax complexity.
  • Instant visual feedback.
  • Lacks advanced automation.
  • Limited custom options.
Method 2
  • Faster.
  • Automation utility.
  • More advanced options.
  • Requires proficient users.
  • Less visual response.

Overall, both methods are preferable with their individual specifications. Which method to choose totally depends on the user’s preference, experience level and individual perspective.

Complementary Information

Besides the previous discussion regarding access to Samba share, the below information might interest you.

How to Open PowerShell

There are several ways to open PowerShell in Windows. I have mentioned three easy processes below:

1. Open PowerShell Using File Explorer

Press WIN+E and type powershell in the address bar and tap ENTER.

2. Open PowerShell Using Run Dialog

Press WIN+R, write powershell and click OK.

Click on the Start menu at the bottom-left of the screen, scroll and expand the Windows PowerShell folder and then click on ‘Windows PowerShell’ option.Prompting to PowerShell windowAll of these three processes will open the PowerShell application in your Windows like the above image.

How to Perform Several Tasks on Samba Drive Using PowerShell

Using PowerShell you can view the listed contents, add new items or remove the whole Samba drive. Follow the detailed execution mentioned below:

List Contents

After navigating to the assigned Samba drive, you can list all the contents inside the Samba share using the command below:

Get-ChildItem

EXPLANATION

  • Get-ChildItem: Returns collection of contents within the shared path.

Seeing the content list inside Samba share using PowerShellYou can see from the image that I have navigated to drive A and can see the new_samba folder inside sambashare folder.

Create New Items

To create new files in a mounted Samba drive use the command below:

New-Item -ItemType File -Path A:\new_samba\samba.txt

EXPLANATION

  • New-Item: Creates new item.
  • -ItemType File: Specifies the item’s type as file.
  • -Path A:\new_samba\samba.txt: Indicates the location of the new file. I have created ‘samba.txt’ as a new file inside ‘A’ drive.

Creating new files in a mounted Samba drive using PowerShellYou can see a new file ‘samba.txt’ has been added to the new_samba folder inside Samba drive.

Remove Drive Mapping

Once done accessing Samba share, you can remove the mapped Samba drive using the following command:

Remove-PSDrive -Name A

EXPLANATION

  • Remove-PSDrive: Removes the assigned drive.
  • -Name A: Represents the letter of the drive you want to assign. I have preferred ‘A’ for my drive.

Also, you can check if the drive has successfully been removed or not by running the syntax below:

Get-PSDrive -Name A

EXPLANATION

  • Get-PSDrive: Displays information about the given drive.
  • -Name A: Represents the letter of the drive you want to assign.

Removing mapped Samba drive using PowerShellFrom the above image, it is clear that the drive ‘A’ is removed successfully.

Conclusion

Samba share integrates collaboration in mixed operating systems. So, to confirm seamless access to Samba share from Windows you must configure the Samba server and set permissions properly. Also, ensure that Windows and Linux machines are on the same network.

People Also Ask

Can I install Samba on Windows?

Yes, you can install Samba on Windows because it’s free and open-source software.

How to see SMB shares in CMD?

To view SMB shares click on the search box, then type cmd and press ENTER. At the prompt, write net share and hit ENTER.

How to find out my SMB IP Address?

Open the command prompt and type ipconfig and hit ENTER.

Do all Windows share use SMB file sharing protocol?

Yes, all Windows shares use SMB.

Can I block SMB traffic using Windows firewall?

You can block all inbound SMB traffic using Windows firewall configuration.

What is the security risk of SMB in Windows 10?

The SMB vulnerability lets an unauthenticated attacker execute any code as an application.

Related Articles 

  • How to Share Files between Linux and Windows
  • How to Configure NFS Server in Linux? [5 Steps]
  • How to Access Shared Folder in Ubuntu [2 Methods]
  • How to Install and Configure Samba Server in Ubuntu? [4 Steps]
  • How to Copy File from Windows to Linux Using SSH [2 Methods]
  • How to Share Files between Linux and Windows Dual Boot [3 Methods]

Image of Jack Wallen

on

How to connect to Linux Samba shares from Windows

If you’re having trouble figuring out how to connect Windows 10 or 11 to your data center Samba shares, Jack Wallen eases your concern with the simple steps to make this work.

Bangkok, Thailand - July 13, 2019 : Laptop user pressing Windows Key on Microsoft Windows keyboard.
Image: wachiwit/Adobe Stock

When Windows 10 was released, it seemingly broke the ability to easily connect to Linux Samba shares. It appeared one could not write to Linux share from Windows 10. Considering how many businesses rely on Samba for the sharing of folders, this was a bad move on the part of Microsoft. Fortunately, the ability to connect to Samba shares wasn’t actually removed from the Windows platform, it was merely tucked a bit out of sight.

I want to walk you through the process of making that connection between Windows 10/11 and your Linux shares.

For this tutorial, I will assume you have both Windows 10 or 11 installed on a machine (or multiple machines) and a Samba share at the ready from your data center. With that said: Let’s connect.

Connecting to your server

Open up File Explorer and then right-click on This PC (in the left pane). From the resulting context menu, select Add A Network Location (Figure A).

Figure A

A new wizard will open, one that will walk you through the process of creating a shortcut for a new network location within File Explorer. Click Next in the Welcome window. In the resulting screen (Figure B), click Choose A Custom Network Location (the only option) and then click Next.

Figure B

Next you must enter the IP address of your Samba server (Figure C) in the form of //SERVER_IP/SHARE, where SERVER_IP is the IP address of your Samba server and SHARE is the name of the share you want to add.

Figure C

Click Next to continue on. In the next window (Figure D), type a name for the network location. A default name will be picked up by the Samba server, you can either use that or enter a custom name that makes it easier for you to remember either where the share is or what is housed within the share.

Figure D

Click Next to reach the final screen of the wizard. Here (Figure E) click Finish and the share is now ready for you to use.

Figure E

And that is all there is to connecting a Windows 10 machine to a Samba share in your data center. It’s not quite as easy as it once was, but the feature is, in fact, still there.

How to connect from Windows 11

With Windows 11, it is much easier to make the connection. Simply open the file manager and in the address bar (Figure F) and type \\SERVER\SHARE, where SERVER is the IP address of the machine hosting the Samba share and SHARE is the name of the actual share.

Figure F

Connecting to a Samba share from Windows 11 is considerably easier than it was in Windows 10.

After hearing a number of people coming to me asking why they can not write to Linux share from Windows 10, I’m happy to tell you that it is not, in fact, broken. Although it’s a bit hidden away, you can still make that much needed desktop to data center connection.

Also See

  • How to protect Samba from the SambaCry exploit
    (TechRepublic)

  • How to set up Samba shares for groups
    (TechRepublic)

  • How to configure Ubuntu Linux server as a Domain Controller with samba-tool
    (TechRepublic)

  • Ethical Hacking Using Kali Linux From A to Z
    (TechRepublic Academy)

  • Data Centers

  • Microsoft

  • Open source

Contents

  1. Client Access — Browsing SMB shares

    1. Ubuntu Clients
    2. Windows Clients (XP,Server,Vista, Win7)
  2. Samba Client — Manual Configuration

    1. Connecting using CIFS
    2. Connecting using SMBFS (deprecated)

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):

sudo apt-get install nautilus-share

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

smbclient -L //server -U user

Connect to a SMB share with

smbclient //server/share -U user

Enter you user password.

You can connect directly with

smbclient //server/share -U user%password

but your password will show on the screen (less secure).

Once connected you will get a prompt that looks like this :

smb: \>

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

Reference : http://linux-cifs.samba.org/

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.

sudo groupadd samba
sudo adduser user samba

Change «user» to the username you wish to add to the samba group.

sudo visudo

In the «group» section add your group you wish to allow to mount SMB shares

Add a line  in the "group" section :
## Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
%samba   ALL=(ALL) /bin/mount,/bin/umount,/sbin/mount.cifs,/sbin/umount.cifs

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):

mkdir ~/mnt
sudo mount -t cifs //myserver_ip_address/myshare ~/mnt -o username=samb_user,noexec

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.

To umount,

sudo umount ~/mnt

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:

gksu gedit /etc/samba/user

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:

username=samba_user
password=samba_user_password

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:

sudo chmod 0400 /etc/samba/user # permissions of 0400 = read only

Now create a directory where you want to mount your share (e.g. /media/samba_share):

sudo mkdir /media/samba_share

Now, using any editor, and add a line to /etc/fstab for your SMB share as follows:

sudo cp /etc/fstab /etc/fstab.bak
gksu gedit /etc/fstab

Add a line for your SMB share:

//myserver_ip_address/myshare  /media/samba_share  cifs  credentials=/etc/samba/user,noexec  0 0

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,

sudo mount /media/samba_share

You can unmount the share with :

sudo umount /media/samba_share

If you wish to increase security at the expense of convenience, use this line in /etc/fstab

//myserver_ip_address/myshare  /media/samba_share  cifs  noauto,credentials=/etc/samba/user,noexec  0 0

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 :

sudo mount /media/samba_share

CIFS may cause a shutdown error.

CIFS VFS: Server not responding.

There is a fix in the troubleshooting section of this forum post.

Back to top

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:

sudo apt-get update
sudo apt-get install smbfs

To allow non root accounts to mount shares, change the permissions on the smbmnt program thus:

sudo chmod u+s /usr/bin/smbmnt /usr/bin/smbumount

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):

%samba   ALL=(ALL) /bin/mount,/bin/umount,/sbin/mount.cifs,/sbin/umount.cifs,/usr/bin/smbmount,/usr/bin/smbumount

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):


mkdir ~/mnt
smbmount //myserver/myshare ~/mnt

To umount,

smbumount ~/mnt

In order to have a share mounted automatically every time you reboot, you need to do the following:

Open a shell as root

sudo -s

Create a file containing your Windows/Samba user account details:

vi /etc/samba/user

…it should contain two lines as follows:

username=george
password=secret

Change the permissions on the file for security:

chmod 0600 /etc/samba/user

Now create a directory where you want to mount your share (e.g. /mnt/data):

mkdir /mnt/data

Now edit the file system table (/etc/fstab) and add a line as follows:

//server/share   /mnt/data   smbfs   credentials=/etc/samba/user,rw,uid=bob   0   0

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

mount /mnt/data

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

192.168.1.100    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).

192.168.1.100    hostname

Where «hostname» = the name of your samba server.

A way to copy files in windows from a Samba Share is by using  Windows Explorer. You can mount your Linux VPS disk in Windows using the SMB/CIFS protocol, this guide will show you how to do that by installing Samba on a VPS and then by mounting that directory on a Windows machine.

Create a specific user that will not be able to login via SSH and the Samba share will point to that user’s home directory, there should be no access outside of this directory.

Installation

The installation begins with the following command:

After the command is executed and the packages are successfully installed, let’s update the configuration.

First a copy of the configuration file as backup:

Then let’s open the config file with nano so we can edit the configuration:

The following configuration allows authentication of added Samba  users and give them access to save data in the user’s home directory. That is, each user added can access the server via Samba/SMB/CIFS and access the files in their home directory.

  [Global]
workgroup = workgroup
server string =% h server (Samba% v)
log file = /var/log/samba/log.%m
max log size = 1000
encrypt passwords = true
invalid users = root
socket options = TCP_NODELAY
security = user
unix extensions = yes

[Homes]
comment = Home Directories
browseable = no
valid users =%S
read only = no
create mask = 0600
directory mask = 0700

Save the config file and exit nano.

Then we restart the Samba server to load the updated configuration:

Create users and add to Samba

As a security measure we do not allow the samba users to login to the system, this way if a username/password combination gets out, only the files in that shared directory is accessible, not the rest of the VPS.

In this example, the username will be shareuser1:

adduser –disabled-login -shell /bin/false -home /home/shareuser1 shareuser1

Follow the on screen instructions and enter the information about the account you are creating.

When the user has been created, we add the user to the Samba database and assign a password.

This is the command which is used to add the user shareuser1 to the Samba database and enable access to the shared folder.

If you get this error message in return when trying to set the password:

This means that the user account is not found and the adduser command above failed. Go back and add the user again, watch for error messages.

Short note on some Samba commands that is good to know about

Some/all options are only available when running smbpasswd as root, so to make sure they are working, execute as root.

Add and activate user accounts (there must be a system user with that username)

This option specifies that the username following should be deleted from the local smbpasswd file.

This option specifies that the username following should be disabled in the local smbpasswd file

This option specifies that the username following should be enabled in the local smbpasswd file, if the account was previously disabled.

Time to get back to the guide and the last part, adding the Samba folder in Windows.

Map Network drive in Windows:

Press the WINDOWS + E keys on your keyboard to open Windows Explorer.

 Images shown here are from a Windows Server 2008 installation

mapshare

Click on the Computer menu and then on the Map Network Drive icon to open the Map Network Drive Dialog.

mapshare2

Select the Drive letter that you would like it to have on your local desktop and enter the network path in the Folder box.

Make sure you tick the Connect using different credentials box.

When clicking on the Finish button you will be presented with a login dialog where you enter the username and password that you used above.

Your network hard drive is successfully installed, configured and integrated into Windows.

If you can’t connect to your samba share, make sure you check other applications as your firewall and/or services that are disabled that is needed.

  • Как подключиться к ubuntu из windows по rdp
  • Как подключиться к openvpn серверу на windows 10
  • Как подключиться к mac os из windows по rdp
  • Как подключиться к mariadb windows
  • Как подключиться к ftp через проводник windows 10