Ubuntu зайти в сетевую папку windows

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.

Настройка файлового обмена между Windows и Ubuntu.

В данной статье расскажу о настройке файлового обмена между Windows и Ubuntu. Мы научимся расшаривать папки (каталоги) в Ubuntu и подключаться к ним из Windows 10 и наоборот. В этой статье все действия мы будем выполнять без использования терминала.

Этой статьей я хочу развеять предрассудки, что шарить папки на Ubuntu очень сложно. Так как же расшарить папку в Ubuntu?

Открываем файловый менеджер (Nautilus). Выбираем папку, которую хотим расшарить другим пользователям в локальной сети. Кликаем по ней правой кнопкой мыши, в контекстном меню выбираем «Свойства» и переходим на вкладку «Общедоступная папка по локальной сети»:

Свойства папки

Если проставить галочку «Опубликовать эту папку» и нажать кнопку «Применить», то наша папка станет доступна другим пользователям в локальной сети. И у эта папка будет подсвечена значком общего доступа:

Значок общего доступа

Но есть нюансы. Не спешите закрывать статью.

Если мы это сделаем в первый раз, то система нам радушно предложит установить «Службу общего доступа к папкам»:

Служба общего доступа к папкам

Соглашаемся и жмём «Установить службу», появится окно, непосредственно, с установкой пакета Samba:

Установить службу

Устанавливаем и соглашаемся на перезапуск сеанса:

Перезапуск сеанса

Давайте разберёмся подробнее с открытием общего доступа к папке.

Создадим какую-нибудь папку, к примеру, назовём её LinuxFiles. Проставим галочку «Опубликовать эту папку» и нажать «Применить»:

Опубликовать эту папку

В поле «Наименование» можно вписать имя сетевого ресурса, как оно будет отображаться у нас в сети.

К примеру, мы создаём название каталога с пробелами и прочими символами, а здесь, в поле «Наименование» указываем нормальное название сетевого ресурса латинскими буквами.

Как подключиться к расшаренной папке Ubuntu из Windows?

Для этого нам надо узнать наш ip или название устройства (hostname).

Это можно сделать в графическом интерфейсе через «Параметры» системы.

В пункте «Сеть» посмотреть подробности вашего подключения:

Параметры сети

В пункте «Подробности» (О системе):

О системе

Тоже самое можно посмотреть и в терминале, выполнив следующие команды:

ifconfig
hostname

После чего в Windows подключаемся, введя в адресной строке Проводника два обратных слеша \\, а затем ip адрес или имя устройства Ubuntu:

Проводник Windows

Отобразятся все расшаренные каталоги на Ubuntu машине. Но если мы попытаемся зайти в нашу папку LinuxFiles, то получим ошибку доступа:

Ввод сетевых учетных данных

Есть два пути решения данной проблемы.

Если хотите, чтобы любой имел доступ к вашей расшаренной папке, то надо в свойствах её общего доступа проставить галочку «Гостевой доступ» и нажать «Применить»:

Гостевой доступ

Если хотите подключаться к папке с помощью учетной записи вашего текущего пользователя Ubuntu, то придется задать ему Samba пароль и это сделать можно в терминале (да, я вас обманул, один раз придется в терминал зайти):

sudo smbpasswd -a $USER

smbpasswd

Теперь можно в Windows зайти в нашу расшаренную папку. Либо с вводом имени пользователя и пароля (вашего Ubuntu пользователя). Либо, если проставили галочку «Гостевого входа», то сразу.

Расшаренный каталог

Но если в Windows вы попытаетесь создать, изменить или удалить файл/папку, то получите ошибку:

Необходимы разрешения на выполнение операции

У вас нет доступа на изменение в этом каталоге.

Если это проблема, и вы хотите, чтобы пользователи в локальной сети могли изменять файлы в этой папке, то для решения этой проблемы нужно в свойствах общего доступа папки проставить галочку «Разрешить другим пользователям изменять содержимое папки» и нажать «Применить»:

Выдача прав на изменений файлов

После чего у вас будет запрошено подверждение на изменение прав на папку:

Подтверждение на изменени прав на папку

Соглашаемся на изменение прав на каталог.

Теперь пользователи локальной сети смогут изменять файлы внутри вашей расшаренной папки.

Стоит упомянуть, что не только пользователи Windows смогут подключаться к вашей расшаренной папке, но и пользователи Ubuntu или других дистрибутивов Linux, аналогично, как они бы подключались к расшаренной папке Windows.

Давайте теперь расшарим папку на Windows и подключимся к ней из Ubuntu.

Настройка общего доступа папки в Windows и подключение к ней из Ubuntu.

Создаём папку в Windows где-нибудь, кликаем правой кнопкой мыши, выбираем «Свойства» — «Доступ» и жмём «Расширенная настройка»:

Расширенная настройка папки Windows

Далее проставляем галочку «Открыть общий доступ к этой папке» и нажимаем «Применить»:

Всё, мы расшарили папку в Windows и к ней можно подключаться.

Как подключиться к расшаренной папке Windows из Ubuntu?

Нам нужно знать ip адрес или имя устройства (hostname).

Полный сетевой путь к расшаренной папке написан на вкладке «Доступ» в Свойствах папки:

Открываем файловый менеджер (Nautilus) в Ubuntu и слева выбираем пункт «Подключиться». Вводим smb и сетевой путь к папке Windows, не забывая развернуть слеши в другую сторону, и нажимаем «Подключиться»:

Подключение к папке Windows через smb

После попытке подключения, если адрес ввели правильно, то будет запрошена авторизация:

Запрошена авторизация для подключения к папке Windows

В Windows есть несколько нюансов с настройкой общего доступа.

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

Если кто не знал, то в Windows 10 есть сетевые и локальные учетные записи. С сетевой учетной записью мы не сможем подключиться.

В расширенных настройках общего доступа папки Windows в «Разрешениях» по умолчанию выбрана группа «Все»:

Настройка разрешений для папки

Но авторизация у нас запрашивается, и если мы попытаемся подключиться «Анонимно», то ничего не выйдет.

Как же подключиться без ввода пароля к Windows папке из Ubuntu?

Нужно в Windows открыть «Центр управления сетями и общим доступом», выбрать «Изменить дополнительные параметры общего доступа»:

Центр управления сетями и общим доступом

В пункте «Все сети» в самом низу будет пункт «Общий доступ с парольной защитой»:

Общий доступ с парольной защитой

Надо отключить общий доступ с парольной защитой и «Сохранить изменения».

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

Для удобства и быстрого доступа к сетевому ресурсу, можно добавить его в закладки файлового менеджера (Nautilus) Ubuntu:

Добавить в закладки

А если нужно защитить папку, то надо удалить группу «Все» и добавить своего пользователя в «Разрешения»:

Вот и всё. В этой статье мы не правили никакие конфиги Samba и не пользовались терминалом. Простому пользователю этого более чем достаточно.


А в ближайших статьях мы более подробно разберем Samba, научимся конфигурировать эту службу.

В этой статье мы рассмотрим, как в Linux смонтировать общую сетевую папку, расположенную на хосте Windows. В Windows для доступа к общим сетевым папкам используется протокол SMB (Server Message Block), который ранее назывался CIFS (Сommon Internet File System). В Linux для доступа к сетевым папкам Windows по протоколу SMB можно использовать клиент cifs-utils или Samba.

    Содержание:

  • Смонтировать сетевую папку в Linux с помощью cifs-util
  • Автоматическое монтирование сетевой папки в Linux
  • Linux: подключиться к сетевой папке с помощью клиента samba

Совет. Для доступа к сетевым папкам по SMB/CIFS используется порт TCP/445. Для разрешения имени используются порты UDP 137, 138 и TCP 139. Если эти порты закрыты, вы сможете подключиться к сетевой папке Windows только по IP адресу.

Смонтировать сетевую папку в Linux с помощью cifs-util

Вы можете смонтировать сетевую папку, находящуюся на Windows хосте, с помощью утилит из пакета cifs-util. Для установки пакета выполните команду:

  • В Ubuntu/Debian: $ sudo apt-get install cifs-utils
  • В CentOS/Oracle/RHEL: $ sudo dnf install cifs-utils

Создайте точку монтирования:

$ sudo mkdir /mnt/share

Теперь вы можете смонтировать сетевую папку с компьютера Windows под пользователем User03с помощью команды:

$ sudo mount.cifs //192.168.31.33/backup /mnt/share -o user=User03

Укажите пароль пользователя Windows для подключения к сетевой папке.

mount.cifs подключить сетевую папку smb в linux

При подключении сетевой SMB папки можно задать дополнительные параметры:

$ sudo mount -t cifs -o username=User03,password=PasswOrd1,uid=1000,iocharset=utf8 //192.168.31.33/backup /mnt/share

  • //192.168.31.33/backup – сетевая папка Windows
  • /mnt/share – точка монтирования
  • -t cifs – указать файловую систему для монтирования
  • -o опции монтирования (эту опцию можно использовать только с правами root, поэтому в команде используется sudo)
  • username=User03,password=PasswOrd1 – имя и пароль пользователя Windows, у которого есть права доступа к сетевой папке. Можно указать имя пользователя guest, если разрешен анонимный доступ к сетевой папке
  • iocharset=utf8 – включить поддержку кодировки UTF8 для отображения имен файлов
  • uid=1000 – использовать этого пользователя Linux в качестве владельца файлов в папке

команда mount cifs в linux

По умолчанию шары Windows монтируются в Linux с полными правами (0755). Если вы хотите изменить права по-умолчанию при монтировании, добавьте в команду опции:

dir_mode=0755,file_mode=0755

Если вы хотите использовать имя компьютера при подключении сетевого каталога Windows, добавьте в файл /etc/hosts строку:

IP_АДРЕС    ИМЯ_КОМПЬЮТЕРА

Чтобы не указывать учетные данные пользователя Windows в команде монтирования сетевой папки, их можно сохранить в файле.

Например:

$ mcedit ~/.windowscredentials

Добавьте в файл:

username=User03
password=PasswOrd1

Для подключения к папке под анонимным пользователем:

username=guest
password=

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

domain = vmblog.ru

Измените права на файл:

$ chmod 600 ~/.windowscredentials

Теперь при подключении сетевой папки вместо явного указания имени пользователя и пароля можно указать путь к файлу:

$ sudo mount -t cifs -o credentials=/home/sysops/.windowscredentials,uid=1000,iocharset=utf8 //192.168.31.33/backup /mnt/share

Отмонтировать сетевую SMB папку:

$ sudo umount /mnt/share

Автоматическое монтирование сетевой папки в Linux

Можно настроить автоматическое монтирование сетевой папки Windows через /etc/fstab.

$ sudo mcedit /etc/fstab

Добавьте в файл следующую строку подключения SMB каталога:

//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev 0 0
  • rw – смонтировать SBM папку на чтение и запись
  • nofail – продолжить загрузку ОС если не удается смонтировать файловую систему
  • _netdev – указывает что подключается файловая система по сети. Linux не будет монтировать такие файловые системы пока на хосте не будет инициализирована сеть.

Вы можете указать версию протокола SMB, которую нужно использовать для подключения (версия SMB 1.0 считается небезопасной и отключена по-умолчанию в современных версиях Windows). Добавьте в конец строки с настройками подключения параметр vers=3.0.

//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev,vers=3.0 0 0

Если на стороне хоста Windows используется несовместимая (старая версия) SMB, при подключении появится ошибка:

mount error(112): Host is downилиmount error(95): Operation not supported

Чтобы сразу смонтировать сетевую папку, выполните:

$ mount -a

Linux: подключиться к сетевой папке с помощью клиента samba

Установите в Linux клиент samba:

  • В Ubuntu/Debian: $ sudo apt-get install smbclient
  • В CentOS/Oracle/RHEL: # dnf install smbclient

Для вывода всех SMB ресурсов в локальной сети:

$ smbtree -N

Вывести список доступных SMB папок на удаленном хосте Windows:

smbclient -L //192.168.31.33 -N

Если в Windows запрещен анонимный доступ, появится ошибка:

session setup failed: NT_STATUS_ACCESS_DENIED

В этом случае нужно указать учетную запись пользователя Windows, которую нужно использовать для подключения:

smbclient -L //192.168.31.33 -U User03

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

smbclient -L //192.168.31.33 -U User03 –W Domain

smbclient вывести список общих папок на компьютере windows

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

smbclient //192.168.31.33/backup -U User03 -W Domain

или

smbclient //192.168.31.33/backup -U User03

Для анонимного доступа:

smbclient //192.168.31.33/backup -U Everyone

После успешного входа появится приглашение:

smb: \>

Вывести список файлов в сетевой папке:

dir

smbclient вывести список файлов в сетевой папке linux

Скачать файл из сетевой папки Windows:

get remotefile.txt /home/sysops/localfile.txt

Сохранить локальный файл из Linux в SMB каталог:

put /home/sysops/localfile.txt  remotefile.txt

Можно последовательно выполнить несколько команд smbclient:

$ smbclient //192.168.31.33/backup -U User03 -c "cd MyFolder; get arcive.zip /mnt/backup/archive.zip"

Полный список команд в smbclient можно вывести с помощью команды help. Команды smbclient схожи с командами ftp клиента.

При использовании команды smbclient может появиться ошибка:

Unable to initialize messaging contextsmbclient: Can't load /etc/samba/smb.conf - run testparm to debug it.

Чтобы исправить ошибку, создайте файл /etc/samba/smb.conf.

Если на хосте Windows отключен протокол SMB 1.0, то при подключении с помощью smbclient появится ошибка:

Reconnecting with SMB1 for workgroup listing.
protocol negotiation failed: NT_STATUS_CONNECTION_RESET
Unable to connect with SMB1 -- no workgroup available.

#
# Пример файла конфигурации Samba для Debian GNU/Linux.
#
#
# Это основной конфигурационный файл Samba. Чтобы понять значение
# указанных здесь опций, прочитайте man-руководство smb.conf(5).
# У Samba есть большое количество опций настройки, большинство
# из которых здесь не показаны.
#
# Некоторые опции, который часто стоит настроить, показаны как
# закомментированные примеры в этом файле.
#  - Когда такие опции закомментированы с помощью ";", то эта
#    предложенная настройка включает опцию, которая отличается
#    от поведения по умолчанию Samba.
#  - Когда комментарий начинается с "#", то эта предложенная
#    настройка соответствует поведению по умолчанию Samba,
#    однако опция достаточно важна, чтобы быть упомянутой.
#
# ЗАМЕЧАНИЕ: всякий раз, когда Вы изменили этот файл, нужно
# проверить корректность сделанных настроек с помощью запуска
# команды "testparm" - она покажет базовые ошибки синтаксиса.
 
#==================== Глобальные настройки ====================
 
[global]
 
## Браузинг/идентификация ###
 
# Поменяйте это имя так, чтобы оно соответствовало рабочей
# группе / домену NT, куда сервер Samba будет входить как часть
# сетевого окружения:
   workgroup = WORKGROUP
 
# server string это эквивалент поля NT Description (описание сервера):
        server string = %h server (Samba, Ubuntu)
 
# Секция поддержки службы Windows Internet Name Serving:
# WINS Support - Tells the NMBD component of Samba to enable its WINS Server
#   wins support = no
# WINS Server - сообщает WINS-клиенту компоненты NMBD.
# Замечание: Samba может быть либо сервером WINS, либо клиентом WINS,
# но не может выполнять обе эти роли одновременно.
;   wins server = w.x.y.z
 
# Эта опция предотвратит для nmbd поиск NetBIOS-имен через DNS.
   dns proxy = no
 
 
#### Сетевые настройки ####
 
# Специфический набор интерфейсов / сетей для привязки службы.
# Это может быть либо имя интерфейса, либо IP-адрес/маска;
# обычно предпочитают имена интерфейсов.
;   interfaces = 127.0.0.0/8 eth0
 
# Привязка только и именованным интерфейсам и/или сетям; для её применения
# Вы должны использовать вышеуказанную опцию 'interfaces'. Рекомендуется
# разрешить эту функцию, если Ваша машина с Samba не защищена файерволом
# или сама является файерволом. Однако эта опция не может корректно
# обрабатывать динамические или не широковещательные интерфейсы.
;   bind interfaces only = yes
 
 
#### Отладка / учет ####
 
# Говорит Samba использовать отдельный log-файл для каждой машины, которая
# подключится:
   log file = /var/log/samba/log.%m
 
# Предел размера отдельных лог-файлов (в килобайтах).
   max log size = 1000
 
# Если Вы хотите, чтобы Samba писала только в системный лог (syslog),
# то установите следующий параметр как 'yes'.
#   syslog only = no
 
# Мы хотим свести к минимуму количество информации, сохраняемой в syslog.
# Вместо этого все должно идти в /var/log/samba/log.{smbd,nmbd}. Если Вы
# хотите писать именно в syslog, то должны установить следующий параметр
# в какое-то большее число.
   syslog = 0
 
# Сделать что-нибудь значимое, когда Samba упала: отправить письмо
# backtrace админу:
   panic action = /usr/share/samba/panic-action %d
 
 
####### Аутентификация #######
 
# Роль сервера. Определяет, в каком режиме будет работать Samba. Возможные
# значения "standalone server", "member server", "classic primary
# domain controller", "classic backup domain controller", "active
# directory domain controller".
#
# Большинство пользователей предпочитают "standalone sever" или "member server".
# Запуск в качестве "active directory domain controller" сначала потребует
# запуска "samba-tool domain provision" чтобы вычистить базы данных и создать
# новый домен.
   server role = standalone server
 
# Если Вы хотите использовать зашифрованные пароли, то Samba должна знать,
# какую базу данных паролей Вы используете.
   passdb backend = tdbsam
   obey pam restrictions = yes
 
# Этот двоичный параметр (yes/no) управляет, будет ли Samba делать попытки
# синхронизировать пароль Unix с паролем SMB, когда изменен шифрованный 
# пароль SMB password в базе passdb.
   unix password sync = yes
 
# Для синхронизации пароля Unix, работающей на системе Debian GNU/Linux,
# должны быть установлены следующие параметры (благодаря Ian Kahan 
<< kahan@informatik.tu-muenchen.de> для отправки корректного чат-скрипта
# программе passwd в Debian Sarge).
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:*
    %n\n *password\supdated\ssuccessfully* .
 
# Эта двоичная опция управляет, будет ли использоваться PAM для изменений
# пароля, когда запрашивается SMB-клиент вместо программы, перечисленной
# d'passwd program'. Значение по умолчанию 'no'.
   pam password change = yes
 
# Эта опция управляет, как не успешные попытки аутентификации будут отображаться
# на анонимные подключения:
   map to guest = bad user
 
 
########## Домены ###########
 
#
# Следующие установки дают эффект только если установлено 'server role = primary
# classic domain controller', 'server role = backup domain controller', или
# 'domain logons'.
#
 
# Задает место нахождения директории профиля пользователя с точки зрения
# клиента). Следующий пример требует наличия настроенной на сервере Samba
# шары [profiles] (см. ниже):
;   logon path = \\%N\profiles\%U
# Другой общий выбор - сохранение профиля в домашней директории пользователя
# (это вариант по умолчанию для Samba):
#   logon path = \\%N\%U\profile
 
# Следующая установка дает эффект только если установлено 'domain logons'.
# Задает место нахождения домашней директории пользователя (с точки зрения
# клиента):
;   logon drive = H:
#   logon home = \\%N\%U
 
# Следующая установка дает эффект только если установлено 'domain logons'.
# Задает скрипт, запускаемый при логоне. Скрипт должен быть сохранен в шаре
# [netlogon].
# Замечание: файл скрипта должен иметь имя формата 'DOS'.
;   logon script = logon.cmd
 
# Это позволяет создавать пользователей Unix на контроллере домена через SAMR
# RPC pipe. Пример команды создает учетную запись пользователя  с запрещенным
# паролем Unix; пожалуйста адаптируйте этот пример под свои нужды:
; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u
 
# Это позволяет учетным записям машины быть созданными на контроллере домена
# через SAMR RPC pipe. Следующий пример настройки подразумевает, что группа
# "machines" существует на системе:
; add machine script  = /usr/sbin/useradd -g machines -c "%u machine account"
 -d /var/lib/samba -s /bin/false %u
 
# Это позволяет группам Unix быть созданными на контроллере домена
# через SAMR RPC pipe.
; add group script = /usr/sbin/addgroup --force-badname %g
 
 
############ Разное ############
 
# Использование следующей строки позволит Вам настроить пользовательскую
# конфигурацию на базе машин. Строка %m будет заменена именем netbios машины,
# которая подключается.
;   include = /home/samba/etc/smb.conf.%m
 
# Некоторые умолчания для winbind (убедитесь, что Вы не используете эти
# диапазоны для чего-то еще).
;   idmap uid = 10000-20000
;   idmap gid = 10000-20000
;   template shell = /bin/bash
 
# Настройка опций шар пользователя, чтобы разрешить не-root
# пользователям расшаривать папки командой net usershare.
# Максимальное количество шар пользователя. 0 (по умолчанию) означает,
# что функция usershare запрещена.
;   usershare max shares = 100
 
# Разрешает пользователям, которым даны привилегии usershare, создавать
# публичные шары, не только аутентификационные:
   usershare allow guests = yes
 
 
#======================= Определения шар =======================
 
# Раскомментируйте следующее (и настройте другие опции ниже по мере
# надобности), чтобы разрешить шары домашней директории по умолчанию.
# Это расшарит каждую домашнюю директорию пользователя как
# \\server\username:
;[homes]
;   comment = Home Directories
;   browseable = no
 
# По умолчанию домашние директории экспортируются только для чтения
# (read-only). Поменяйте следующий параметр на 'no', если хотите
# иметь возможность писать в них:
;   read only = yes
 
# Маска создания файла установлена на 0700 по соображениям безопасности.
# Если Вы хотите создавать файлы с разрешениями group=rw, то установите
# следующий параметр на 0775 (полный доступ для всех задается маской 0x777).
;   create mask = 0700
 
# Маска создания директории установлена на 0700 по соображениям безопасности.
# Если Вы хотите создавать каталоги с разрешениями group=rw, то установите
# следующий параметр на 0775 (полный доступ для всех задается маской 0x777).
;   directory mask = 0700
 
# По умолчанию к шарам \\server\username могут подключаться кто угодно,
# кто имеет доступ к серверу Samba. Раскомментируйте следующий параметр
# для гарантии, что только "username" может подключиться к шаре
# \\server\username. Это может потребовать подстройки, если используются
# схемы внешней аутентификации.
;   valid users = %S
 
# Раскомментируйте следующее, чтобы создать директорию netlogon для
# логонов домена (Domain Logons). Также потребуется сконфигурировать
# Samba, чтобы она функционировала как контроллер домена.
;[netlogon]
;   comment = Network Logon Service
;   path = /home/samba/netlogon
;   guest ok = yes
;   read only = yes
 
# Раскомментируйте следующее, чтобы создать директорию profiles для
# хранения профилей пользователей (см. выше опцию "logon path").
# Также потребуется сконфигурировать Samba, чтобы она функционировала
# как контроллер домена. Путь ниже должен быть записываемым для всех
# пользователей, чтобы могли быть созданы их директории, когда пользователи
# логинятся первый раз.
;[profiles]
;   comment = Users profiles
;   path = /home/samba/profiles
;   guest ok = no
;   browseable = no
;   create mask = 0600
;   directory mask = 0700
 
[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700
 
# Клиенты Windows видят это имя шары как источник загружаемых драйверов принтера:
[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no
# Раскомментируйте, чтобы позволить удаленное администрирование драйверов
# принтеров Windows. Вам может понадобиться заменить 'lpadmin' именем
# группы, членами которой являются Ваши пользователи с полномочиями
# администратора. Обратите внимание, что Вам нужно установить подходящие
# разрешения Unix для этих пользователей на директорию драйверов, чтобы
# они могли туда записывать:
;   write list = root, @lpadmin
 
# Эта шара для обмена файлами, в неё имеют полный доступ кто угодно
# без необходимости использования правильного пароля:
[share]
   path = /home/share/
   read only = No
   create mask = 0777
   directory mask = 0777
   browseable = yes
   public = yes

In the Windows operating system, there is a feature called file sharing. On one computer, you can set up windows-shared folder that will be accessible to all computers on the local network. This is done using the SMB protocol, which has several versions. In Linux, you can open and create shared folders using Samba.

The Samba server supports all versions of the SMB protocol. However, there are some compatibility issues. In this article, I will explain how to access a Windows Shared folder in Linux using popular desktop environments and the command line.

Table of Contents

  • Why It May Not Work?
  • Ensure that Everything is Set Up Correctly in Windows
  • Finding Shares in Linux Terminal
  • Open Shared Folder in KDE Dolphin
  • Open Share in GNOME Nautilus
  • Mounting a Shared Folder in the Terminal
  • Wrapping Up

Why It May Not Work?

In older versions of Linux distros and Windows 7 everything worked fine because they used the SMB1 protocol. However, there have been several changes recently. In 2017, the Wannacry virus emerged, which exploited vulnerabilities in the SMB1 protocol. As a result, modern versions of Windows have disabled support for SMB1 and now use SMB3 by default. Samba has also disabled SMB1 since version 4.11. However, SMB2 and SMB3 lack support for device discovery in the local network.

In general, this is no longer necessary because there is a network discovery protocol called Zeroconf. In Linux, its open-source implementation, Avahi, is used. Linux servers and NAS storage can publish themselves on the local network using this protocol. So that, there is no need to support it in SMB. However, Microsoft decided to use its own protocol called WS-Discovery, and that’s where the problems began.

At the time of writing this article, Linux system has issues with discovering shared folders in the local network. The Nautilus file manager in GNOME does not support WS-Discovery at all, and there are no production-ready terminal utilities for it either. You can track the current status of implementing WS-Discovery support in this GVFS issue. However, in 2020, the KDE team added support for this protocol in the Dolphin file manager using kdsoap-ws-discovery-client.

Later, a program for KDE called Smb4k appeared, which can discover network resources using Avahi and the WS-Discovery protocol, but it needs to be compiled with a special option. So that, in GNOME, you can only open a Windows shared folder by knowing the IP address of the computer where it is located. Whereas in KDE, it is a bit more convenient to do so.

Ensure that Everything is Set Up Correctly in Windows

Previously, it was enough to go to File Explorer and enable file sharing there. But it no longer works that way. First, you need to make your current network private in Windows. By default, only private networks are considered secure, and Windows machines can be discovered in them. To do this, open Settings -> Network & Internet -> Ethernet and select Network Profile Type -> Private Network:

If your current network is wireless, you should do the pretty same thing. Next, go back and select Advanced Sharing Settings. In this window, enable Network discovery and File and printer sharing:

Finally, you need to ensure that the firewall is configured correctly and allows SMB connections. To do this, go back to the main Settings menu, then open Privacy & Security -> Firewall & network protection. Click on Allow an app through the firewall:

Make sure that File and printer sharing and Network discovery are enabled for Private networks:

That’s it. Now you can go to your Linux machine.

Although there are no command-line tools for working with WS-Discovery, you can try to find devices with shared resources using Nmap. This program cannot search for resources like Avahi does, but it can help you find IP addresses with an open port 445. This port is used by SMB. To do this, you need to install the following packages (Ubuntu):

sudo apt install nmap smbclient

Or Fedora:

sudo dnf install nmap samba-client

Also, you need to find out the IP address range of your local network. You can take your IP address and mask and just replace the fourth digit with zero. For example:

ip -br a

The command for the search will look like this. Replace 192.168.124.0/24 with your local network address range and run it in the the terminal window with sudo privileges:

nmap -p 445 --open -n -Pn 192.168.124.0/24

The -p option specifies the port 445, -Pn option disables ICMP discovery and treats all IP addresses as alive, -n disables DNS hostname resolution. The command may take quite a while, but as a result, it will find hosts with open port 445 if such hosts exist in your local network:

This can’t be considered as normal network discovery, but it works. Now you can use smbclient to see which shared folders are on the server that you found. For example:

smbclient -L 192.168.124.63

The command will ask you to enter the share password. Usually, it is password for your Windows user, and then it will show all available shared folders:

Now let’s have a look at how to mount them.

To open a shared folder in KDE, you can use the Dolphin file manager. As I mentioned earlier, here you can see all available computers that have network drive on the local network. To do this, run Dolphin, then open Network, and then Shared Folders (SMB):

Click on one of the resources and enter the username and password to view the available folders:

This is what shared folders from Windows 11 look like. Here you can find windows files:

If network discovery does not work in your case, you can still enter the IP address of the resource in the text field at the top of the window and connect to it. For example, smb://192.168.124.63/

If you want to connect to a Windows shared folder in the GNOME graphical interface, you can use the Nautilus file manager. Open Other Locations and find at the bottom of the window the inscription Connect to Server and a field for entering an address.

There’s no point in opening the Windows Network item, because GVFS, which is used in GNOME for disk mounting, does not support the WS-Discovery protocol. To connect to a remote windows share located on a server with IP 192.168.124.63, enter this address and press the Connect button:

smb://192.168.124.63

In the next window, you need to enter a password and after that, you can view the files of the shared folder:

After this, you can browse your windows folders.

Additionally, you can use a shortcut on the left panel to access a remote share which is already mounted.

If you want to mount windows share in the terminal, you can use cifs-utils and the mount command. Firstly, install the cifs-utils package. The command for Ubuntu:

sudo apt install cifs-utils

In Fedora:

sudo dnf install cifs-utils

Now, you can execute the mount command specifying the cifs file system type and the username option. Note that you can’t mount the root of the cifs share, you need to add any folder in the path. For example, Users on 192.168.124.63:

sudo mount -t cifs -o username=losst //192.168.124.63/Users /mnt/

If you want to have write access to the windows share folder, you need to add the uid option with the identifier of your user. For the first user, it’s usually 1000:

sudo mount -t cifs -o username=losst,uid=1000 //192.168.124.63/Users /mnt/

You can find the identifier of the current user in the UID environment variable:

echo $UID

If you want to mount share automatically at system startup, you need to save the share username and password in a credentials file, for example, /etc/share/windows-credentials. For instance:

sudo mkdir -p /etc/share/

username=losst
password=password
domain=workgroup

And then add the following line to the /etc/fstab file:

//192.168.124.63/Users /mnt/share cifs credentials=/etc/share/windows-credentials,uid=1000,nofail 0 0

The nofail option is needed to allow your computer to boot even if the remote folder could not be mounted. After this, reload systemd settings:

sudo systemctl daemon-reload

Create the mount point directory:

sudo mkdir -p /mnt/share

You can check that everything is working using the following command:

sudo mount /mnt/share

If everything is ok, you could see contents of mounted share in the /mnt/share folder:

Wrapping Up

In this article, we looked at how to mount Windows network share in Linux using a graphical interface or in the terminal. Despite some difficulties, this can be used quite effectively. Do you know any other applications or scripts which can help with that? Share their names in the comments section below.

The article is distributed under Creative Commons ShareAlike 4.0 license. Link to the source is required .

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Драйвер hp deskjet 6122 для windows 7
  • Включить icmp windows server
  • Кодек пак для windows 7 x32
  • Драйвера adam 4561 windows 7
  • Гта 5 системные требования для windows 10