Failed to mount windows share permission denied

I've just set up a home server running Ubuntu 19.04 with a dedicated hard drive for file sharing (Ubuntu is installed on a separate drive). Both drives are formatted with ext4. On the dedicated hard

I’ve just set up a home server running Ubuntu 19.04 with a dedicated hard drive for file sharing (Ubuntu is installed on a separate drive). Both drives are formatted with ext4.

On the dedicated hard drive I’ve created a share, which looks like this…

share

On my workstation I can see the share listed. I’ve tried to access it using both Anonymous and Registered User methods…

login

…but no such luck…

denied

Any ideas?

asked Oct 9, 2019 at 21:55

Matthew Layton's user avatar

The two most common causes of your error message are:

[1] You are not passing the samba password when asked for the «registered user» credentials.

You create that password by adding the user to the samba password database — and I will use my own as an example:

sudo smbpasswd -a morbius

[2] Since the share that was created allows guest access the more likely case is the path to the shared directory does not allow access to the shared folder. The shared folder itself may allow access to guest but the path to that folder may not. For example if the folder is mounted to /media/morbius/Media then only morbius will have access to Media.

I would suggest that you edit your original question and add to it the output of the following command so the folks here can see where the folder is located:

net usershare info --long

answered Oct 10, 2019 at 18:49

Morbius1's user avatar

Morbius1Morbius1

6,5611 gold badge11 silver badges20 bronze badges

5

The path to the shared directory needs to allow «read access».
so if the path the samba shared directory is

/dir1/shared_dir

then do this

sudo chmod o+rx /dir1

In linux, a user needs Execute permission (+x) on a directory to traverse it on the way to the final directory.

answered Oct 6, 2021 at 4:01

Tim Richardson's user avatar

Tim RichardsonTim Richardson

2,0072 gold badges21 silver badges38 bronze badges

A couple of things to check out. I do something similar and you can test mount it directly using the mount command to make sure you have things setup right.

Permissions on credentials file

Make sure that this file is permissioned right.

$ sudo ls -l /etc/smb_credentials.txt 
-rw-------. 1 root root 54 Mar 24 13:19 /etc/smb_credentials.txt

Verbose mount

You can coax more info out of mount using the -v switch which will often times show you where things are getting tripped up.

$ sudo mount -v -t cifs //server/share /mnt 
    -o credentials=/etc/smb_credentials.txt

Resulting in this output if it works:

mount.cifs kernel mount options: ip=192.168.1.14,unc=\servershare,credentials=/etc/smb_credentials.txt,ver=1,user=someuser,domain=somedom,pass=********

Check the logs

After running the above mount command take a look inside your dmesg and /var/log/messages or /var/log/syslog files for any error messages that may have been generated when you attempted the mount.

Type of security

You can pass a lot of extra options via the -o .. switch to mount. These options are technology specific, so in your case they’re applicable to mount.cifs specifically. Take a look at the mount.cifs man page for more on all the options you can pass.

I would suspect you’re missing an option to sec=.... Specifically one of these options:

   sec=
       Security mode. Allowed values are:
       ·   none - attempt to connection as a null user (no name)
       ·   krb5 - Use Kerberos version 5 authentication
       ·   krb5i - Use Kerberos authentication and forcibly enable packet 
           signing
       ·   ntlm - Use NTLM password hashing
       ·   ntlmi - Use NTLM password hashing and force packet signing
       ·   ntlmv2 - Use NTLMv2 password hashing
       ·   ntlmv2i - Use NTLMv2 password hashing and force packet signing
       ·   ntlmssp - Use NTLMv2 password hashing encapsulated in Raw NTLMSSP
           message
       ·   ntlmsspi - Use NTLMv2 password hashing encapsulated in Raw 
           NTLMSSP message, and force packet signing

       The default in mainline kernel versions prior to v3.8 was sec=ntlm. 
       In v3.8, the default was changed to sec=ntlmssp.

You may need to adjust the sec=... option so that it’s either sec=ntlm or sec=ntlmssp.

References

  • Thread: mount -t cifs results gives mount error(13): Permission denied

Forum rules
Before you post please read how to get help. Topics in this forum are automatically closed 6 months after creation.

Boarnads

Samba | Failed to mount Windows share: Permission denied

Hi there,

I’ve been trying to setup samba via webmin and have run into several permission problems. I’m trying to setup several shares that require no authentication.
Below are the current problematic shared folders and their status:

‘/media/username/My Book’
Visible in network but get the following when trying to access it

Unable to mount location. Failed to mount Windows share: Permission denied

‘/home/username/Videos’
I can access this from the network but I cannot access any of the individual files, I can only browse through the folders.

smb.conf

Code: Select all

#
# Sample configuration file for the Samba suite for Debian GNU/Linux.
#
#
# This is the main Samba configuration file. You should read the
# smb.conf(5) manual page in order to understand the options listed
# here. Samba has a huge number of configurable options most of which 
# are not shown in this example
#
# Some options that are often worth tuning have been included as
# commented-out examples in this file.
#  - When such options are commented with ";", the proposed setting
#    differs from the default Samba behaviour
#  - When commented with "#", the proposed setting is the default
#    behaviour of Samba but the option is considered important
#    enough to be mentioned here
#
# NOTE: Whenever you modify this file you should run the command
# "testparm" to check that you have not made any basic syntactic 
# errors. 

#======================= Global Settings =======================

[global]

## Browsing/Identification ###

# Change this to the workgroup/NT-domain name your Samba server will part of
	workgroup = workgroup

# server string is the equivalent of the NT Description field
	server string = %h server (Samba, Linux Mint)

# Windows Internet Name Serving Support Section:
# WINS Support - Tells the NMBD component of Samba to enable its WINS Server
#   wins support = no

# WINS Server - Tells the NMBD components of Samba to be a WINS Client
# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
;   wins server = w.x.y.z

# This will prevent nmbd to search for NetBIOS names through DNS.
	dns proxy = no

#### Networking ####

# The specific set of interfaces / networks to bind to
# This can be either the interface name or an IP address/netmask;
# interface names are normally preferred
;   interfaces = 127.0.0.0/8 eth0

# Only bind to the named interfaces and/or networks; you must use the
# 'interfaces' option above to use this.
# It is recommended that you enable this feature if your Samba machine is
# not protected by a firewall or is a firewall itself.  However, this
# option cannot handle dynamic or non-broadcast interfaces correctly.
;   bind interfaces only = yes



#### Debugging/Accounting ####

# This tells Samba to use a separate log file for each machine
# that connects
	log file = /var/log/samba/log.%m

# Cap the size of the individual log files (in KiB).
	max log size = 1000

# If you want Samba to only log through syslog then set the following
# parameter to 'yes'.
#   syslog only = no

# We want Samba to log a minimum amount of information to syslog. Everything
# should go to /var/log/samba/log.{smbd,nmbd} instead. If you want to log
# through syslog you should set the following parameter to something higher.
	syslog = 0

# Do something sensible when Samba crashes: mail the admin a backtrace
	panic action = /usr/share/samba/panic-action %d


####### Authentication #######

# Server role. Defines in which mode Samba will operate. Possible
# values are "standalone server", "member server", "classic primary
# domain controller", "classic backup domain controller", "active
# directory domain controller". 
#
# Most people will want "standalone sever" or "member server".
# Running as "active directory domain controller" will require first
# running "samba-tool domain provision" to wipe databases and create a
# new domain.
	server role = standalone server

# If you are using encrypted passwords, Samba will need to know what
# password database type you are using.  
;	passdb backend = tdbsam

	obey pam restrictions = yes

# This boolean parameter controls whether Samba attempts to sync the Unix
# password with the SMB password when the encrypted SMB password in the
# passdb is changed.
	unix password sync = yes

# For Unix password sync to work on a Debian GNU/Linux system, the following
# parameters must be set (thanks to Ian Kahan <<kahan@informatik.tu-muenchen.de> for
# sending the correct chat script for the passwd program in Debian Sarge).
	passwd program = /usr/bin/passwd %u
	passwd chat = *Entersnews*spassword:* %nn *Retypesnews*spassword:* %nn *passwordsupdatedssuccessfully* .

# This boolean controls whether PAM will be used for password changes
# when requested by an SMB client instead of the program listed in
# 'passwd program'. The default is 'no'.
	pam password change = yes

# This option controls how unsuccessful authentication attempts are mapped
# to anonymous connections
	map to guest = bad user

########## Domains ###########

#
# The following settings only takes effect if 'server role = primary
# classic domain controller', 'server role = backup domain controller'
# or 'domain logons' is set 
#

# It specifies the location of the user's
# profile directory from the client point of view) The following
# required a [profiles] share to be setup on the samba server (see
# below)
;   logon path = \%Nprofiles%U
# Another common choice is storing the profile in the user's home directory
# (this is Samba's default)
#   logon path = \%N%Uprofile

# The following setting only takes effect if 'domain logons' is set
# It specifies the location of a user's home directory (from the client
# point of view)
;   logon drive = H:
#   logon home = \%N%U

# The following setting only takes effect if 'domain logons' is set
# It specifies the script to run during logon. The script must be stored
# in the [netlogon] share
# NOTE: Must be store in 'DOS' file format convention
;   logon script = logon.cmd

# This allows Unix users to be created on the domain controller via the SAMR
# RPC pipe.  The example command creates a user account with a disabled Unix
# password; please adapt to your needs
; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u

# This allows machine accounts to be created on the domain controller via the 
# SAMR RPC pipe.  
# The following assumes a "machines" group exists on the system
; add machine script  = /usr/sbin/useradd -g machines -c "%u machine account" -d /var/lib/samba -s /bin/false %u

# This allows Unix groups to be created on the domain controller via the SAMR
# RPC pipe.  
; add group script = /usr/sbin/addgroup --force-badname %g

############ Misc ############

# Using the following line enables you to customise your configuration
# on a per machine basis. The %m gets replaced with the netbios name
# of the machine that is connecting
;   include = /home/samba/etc/smb.conf.%m

# Some defaults for winbind (make sure you're not using the ranges
# for something else.)
;   idmap uid = 10000-20000
;   idmap gid = 10000-20000
;   template shell = /bin/bash

# Setup usershare options to enable non-root users to share folders
# with the net usershare command.

# Maximum number of usershare. 0 (default) means that usershare is disabled.
;	usershare max shares = 100

# Allow users who've been granted usershare privileges to create
# public shares, not just authenticated ones
	usershare allow guests = yes
	username map = /etc/samba/smbusers
	security = user
;	encrypt passwords = yes
	guest ok = yes
;	guest account = nobody

#======================= Share Definitions =======================

# Un-comment the following (and tweak the other settings below to suit)
# to enable the default home directory shares. This will share each
# user's home directory as \serverusername
;[homes]
;   comment = Home Directories
;   browseable = no

# By default, the home directories are exported read-only. Change the
# next parameter to 'no' if you want to be able to write to them.
;   read only = yes

# File creation mask is set to 0700 for security reasons. If you want to
# create files with group=rw permissions, set next parameter to 0775.
;   create mask = 0700

# Directory creation mask is set to 0700 for security reasons. If you want to
# create dirs. with group=rw permissions, set next parameter to 0775.
;   directory mask = 0700

# By default, \serverusername shares can be connected to by anyone
# with access to the samba server.
# Un-comment the following parameter to make sure that only "username"
# can connect to \serverusername
# This might need tweaking when using external authentication schemes
;   valid users = %S

# Un-comment the following and create the netlogon directory for Domain Logons
# (you need to configure Samba to act as a domain controller too.)
;[netlogon]
;   comment = Network Logon Service
;   path = /home/samba/netlogon
;   guest ok = yes
;   read only = yes

# Un-comment the following and create the profiles directory to store
# users profiles (see the "logon path" option above)
# (you need to configure Samba to act as a domain controller too.)
# The path below should be writable by all users so that their
# profile directory may be created the first time they log on
;[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 clients look for this share name as a source of downloadable
# printer drivers
[print$]
	comment = Printer Drivers
	path = /var/lib/samba/printers
;	browseable = yes
;	read only = yes
;	guest ok = no
# Uncomment to allow remote administration of Windows print drivers.
# You may need to replace 'lpadmin' with the name of the group your
# admin users are members of.
# Please note that you also need to set appropriate Unix permissions
# to the drivers directory for these users to have write rights in it
;   write list = root, @lpadmin


[Pictures]
	path = /home/username/Pictures
	valid users = username
;	writeable = No
;	browseable = yes

[Videos]
	guest ok = yes
	path = /home/username/Videos
;	writeable = No
;	browseable = yes



[WDShare]
	path = /media/username/My Book
	writeable = yes
;	browseable = yes
	guest ok = yes

‘ls -l’ gives me the following
drwx—— 1 username username 8192 Feb 17 02:18 My Book
drwxr-xr-x 9 username username 4096 Feb 18 04:48 Videos

I also tried chmod 777 for My Book prior to ls -l command, it appeared to complete successfully although the permissions dont seem to have changed.

Any help in resolving this issus would be greatly appreciated
Regards,
Boarnads

Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.

Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.

User avatar

Pjotr

Level 23
Level 23
Posts: 18553
Joined: Mon Mar 07, 2011 10:18 am
Location: The Netherlands (Holland) 🇳🇱
Contact:

altair4

Level 20
Level 20
Posts: 11021
Joined: Tue Feb 03, 2009 10:27 am

Re: Samba | Failed to mount Windows share: Permission denied

Post

by altair4 » Wed Feb 18, 2015 7:19 am

You might be able to fix both problems by forcing the remote quest to appear to be you — at least for your samba shares anyway:

Edit smb.conf and under the workgroup = workgroup line add this line:

I’m using your reference to «username» so change that to whatever your real user name is.

Then restart smbd:

Please add a [SOLVED] at the end of your original subject header if your question has been answered and solved.

altair4

Level 20
Level 20
Posts: 11021
Joined: Tue Feb 03, 2009 10:27 am

Re: Samba | Failed to mount Windows share: Permission denied

Post

by altair4 » Wed Feb 18, 2015 3:31 pm

Based on this posting I had assumed it was NTFS because of the permissions

drwx—— 1 username username 8192 Feb 17 02:18 My Book

That’s why I suggested «force user = username» since both shares are guest shares.

Please add a [SOLVED] at the end of your original subject header if your question has been answered and solved.

Boarnads

Re: Samba | Failed to mount Windows share: Permission denied

Post

by Boarnads » Wed Feb 18, 2015 9:45 pm

The hdd is NTFS but Ive gotten the shares to work before with NTFS drives without the ‘force user’, I just cant remember what I did.
However I’m now using ‘force user = username’ which seems to have fixed the problem, I’m just wondering are there any negatives to ‘force user’, would I be better off getting the permissions working, especially for the ‘Videos’ share?

Thank you all very much for your help.

altair4

Level 20
Level 20
Posts: 11021
Joined: Tue Feb 03, 2009 10:27 am

Re: Samba | Failed to mount Windows share: Permission denied

Post

by altair4 » Thu Feb 19, 2015 7:47 am

Warning: This is going to be an unbelievably long answer :)

Let’s take the worst case scenario and assume the client machine is running Windows and that the user on that machine is named «bob».

When bob tries to access your Mint machine Windows automatically passes his user name to Samba. If there is no match in the samba password database for «bob» the «map to guest = Bad User» parameter is invoked and changes «bob» to the default guest user in Mint which is literally «nobody».

«nobody» doesn’t have access to «/media/username/My Book» at all ( actually no one has access to that folder except «username» ) and only has read access to /home/username/Videos. «force user» makes «nobody» «username» so he now does have access to both. Depending on how you create the samba share definition it still has a gatekeeper function in that if you set it up to be read only the Windows client cannot write even though he is now «username».

If however the user name on the Windows machine is also «username» and his name does appear in the samba password database then he is no longer a «Bad User» and he comes across as «username» and the situation is resolved. If this is the case then you could add yourself ( username ) to the samba password database:

Now the Windows user is also the Linux user and he has access to both shares without the need for «force user». But this will only work for the Windows user «username». You would still need the «force user» if you have many windows clients.

If however the client machine is running Linux the situation changes.

The Linux samba client doesn’t pass a user name when it tries to access the Mint machine because … well …. Linux thinks that’s goofy. The Linux client will always come across as «nobody» unless the share requires credentials. In this scenario — for a guest share — «force user» is the easiest way to resolve the situation without changing the guest share to a private share requiring credentials.

Either way «force user» doesn’t give the remote user full access to your entire box only to the samba shares and only within the parameters set in the share definition for those shares.

Edited for spelling — I just can’t spell

Last edited by altair4 on Thu Feb 19, 2015 7:04 pm, edited 5 times in total.

Please add a [SOLVED] at the end of your original subject header if your question has been answered and solved.

deleted

Re: Samba | Failed to mount Windows share: Permission denied

Post

by deleted » Thu Feb 19, 2015 8:46 am

Setting up a Simple Samba Server is easy on Linux if you assume your samba share user have an account on your Linux workstation.
This will automatically share user homes

edit the original /etc/samba/smb.conf (don’t start with an empty smb.conf)

In the [global] section:
add

Code: Select all

    follow symlinks=yes
    wide links=yes
    unix extensions=no
    client lanman auth = yes
    client ntlmv2 auth = no

This allows samba clients (like Windows) to follow the symbolic links (symlinks) defined on your SolydXK samba server.

In the [homes] section:
change

and uncomment ( remove the leading ; )

restart samba to reload smb.conf
add your samba users using smbpasswd.

In your case where you want to share:
/media/username/My Book

just do:
ln -s /media/username/My Book /home/username/My Book

That will symbolically link /media/username/My Book to My Book in username’s home where samba can see it and follow the link.
-Hinto

altair4

Level 20
Level 20
Posts: 11021
Joined: Tue Feb 03, 2009 10:27 am

Re: Samba | Failed to mount Windows share: Permission denied

Post

by altair4 » Thu Feb 19, 2015 9:09 am

And my advice is to ignore the previous post. It won’t work.

Gosh, we have had this dance so many times before ……………..

[1] Mint is not SolydXK
[2] There is no [homes] share defined in Mint, the standard Ubuntu desktop, or any of it’s derivatives.
[3] You are forcing credentials being passed when all the user has is guest accessible shares.
[4] Even if the homes share were defined you are allowing access to the entire home directory not just the folders desired.
[5] Did I already mention that the user only has guess accessible shares?
[6] And this command:

ln -s /media/username/My Book /home/username/My Book

Will only result in a broken link since you forgot about the space.

Please add a [SOLVED] at the end of your original subject header if your question has been answered and solved.

deleted

Re: Samba | Failed to mount Windows share: Permission denied

Post

by deleted » Thu Feb 19, 2015 10:51 am

I did the exact same thing on Mint, RHEL, Fedora, Ubuntu, Debian, #!, Siduction, Suse, OpenSuse.
And there is a [homes] section, it’s commented out (so uncomment it, too)
No sweat.
The key is smb.conf mods.
It’s nothing mystical.
-H

altair4

Level 20
Level 20
Posts: 11021
Joined: Tue Feb 03, 2009 10:27 am

Re: Samba | Failed to mount Windows share: Permission denied

Post

by altair4 » Thu Feb 19, 2015 11:33 am

And I would encourage you to continue to use it — on your own systems. For Mint it will not work. And please read the original posts in a given topic so you get a sense of the user’s requirements.

Someone one said: «Insanity is doing the same thing over and over again and expecting a different result»

You keep posting this thing expecting this time it will work and I won’t comment.
Every time you post it I do in fact respond expecting you to fix it.

Ain’t we a pair. We’re going to end up in adjoining rooms at the asylum.

Last edited by altair4 on Thu Feb 19, 2015 11:37 am, edited 1 time in total.

Please add a [SOLVED] at the end of your original subject header if your question has been answered and solved.

deleted

Re: Samba | Failed to mount Windows share: Permission denied

Post

by deleted » Thu Feb 19, 2015 11:36 am

Actually it works on my 5 different mint 17.1 systems, but don’t tell them.
My idea is to take something *known* to work, then modify it for your purposes instead of starting from scratch every time.
On _any_ distro I hop to (which isn’t hard either) I make those mods and there are no problems, even on Mint. As a matter of fact, it was Mint that I actually flushed the steps out on.
-H

I am trying to mount windows machine directory in my ubuntu 10.04.3 server. When I try to see the shared directory in the windows server its showing properly using the below command. The windows mahcine is joined to local domain xyz.com

My doubt is, cant we mount the shared directory which is connected to local domain server?
I am getting this error in both smbfs / cifs.

 smbclient -L //192.168.39.152/ -U svnbackup

    Sharename       Type      Comment
    ---------       ----      -------
    ADMIN$          Disk      Remote Admin
    Android         Disk
    C$              Disk      Default share
    CENTOS          Disk
    E$              Disk      Default share
    G$              Disk      Default share
    IPC$            IPC       Remote IPC
    Nagios          Disk
    test            Disk

When I try to mount the test directory using below command Its show error saying permission denied as below.

  mount.smbfs //192.168.39.152/test /mnt/smbfs -o username=username,password=Svn1234,domain=xyz.com
  mount error(13): Permission denied Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

Please help me to solve the issue.

asked Mar 6, 2012 at 10:12

Caterpillar's user avatar

CaterpillarCaterpillar

1,1322 gold badges22 silver badges47 bronze badges

6

try:

mount -t cifs //address/sharename /mnt/whatever 
-o `**username=DomainName/username**,password=password`

if it doesnt work, try:

mount.cifs //address/Share /mnt/share/ -o username=address/username

dont add a password, it should prompt u for one and possible it’ll work, gl

rm-vanda's user avatar

rm-vanda

2478 silver badges18 bronze badges

answered Mar 7, 2012 at 10:04

3a2roub's user avatar

3a2roub3a2roub

2944 silver badges15 bronze badges

3

I’ve found solution on this site: Issue Mounting CIFS Share | ubuntuforums.org

Generally in Windows you should add this key in regedit. It works for me now.
Key goes in:
HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem

Key DWORD (32-bit): LocalAccountTokenFilterPolicy
Key Value : 1

mivk's user avatar

mivk

3,6471 gold badge37 silver badges32 bronze badges

answered Aug 12, 2014 at 20:10

dePablo's user avatar

dePablodePablo

1011 silver badge3 bronze badges

5

Try cifs. smbfs is deprecated by cifs-utils. smbfs is used in Debian <= 3.

mount -t cifs //192.168.39.152/test -o 
  username=username,password=Svn1234,domain=xyz.com /mnt/smbfs

Andrew Schulman's user avatar

answered Mar 6, 2012 at 10:30

user103373's user avatar

user103373user103373

1866 silver badges19 bronze badges

1

I want to access by termin a Windows share so on my Ubuntu 14.04 system I executed the following command:

sudo mount.cifs -o username=dana //192.168.1.4/Users  /mnt/

After entering the sudo password and the windwos user password I got these error

mount error(13): Permission denied Refer to the mount.cifs(8) manual
page (e.g. man mount.cifs)

asked Jun 29, 2014 at 13:21

Dan's user avatar

Make sure your account has permissions to mount. Use smbclient to try to access the drive — the smbclient command will give much more meaningful error messages why you cannot mount.

For example:

smbclient \machinenamefoldername -U [username] [password]

If it works, you will get an smb prompt like:

smb>

If not, you will get an error, such as NT_LOGON_FAILUIRE (password wrong) or if the login works but you do not have access on that folder, it will give you that error (which I can’t recall off the top of my head)

Check here for info on smbclient and smbclient syntax:
Mounting Windows Shares On Linux Using Samba/CIFS/SMBFS

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered Jul 1, 2014 at 17:21

ben's user avatar

mount(8) — Linux man page

Return Codes
mount has the following return codes (the bits can be ORed):
0: success
1: incorrect invocation or permissions
2: system error (out of memory, cannot fork, no more loop devices)
4: internal mount bug
8: user interrupt
16: problems writing or locking /etc/mtab
32: mount failure
64: some mount succeeded

This suggest that you have generated 3 errors:

  1. user interrupt
  2. internal mount bug
  3. incorrect invocation or permissions

answered Jun 29, 2014 at 13:55

LDC3's user avatar

LDC3LDC3

2,2121 gold badge13 silver badges15 bronze badges

First thing always check if user has access to share and not only permissions to folder also use domain option and use -v to check debug messages.

answered Jun 14, 2016 at 8:41

synchris's user avatar

use this for mounting Windows share to your local Linux machine:

sudo apt-get install cifs-utils
sudo mount -t cifs //hostname.your.windows.machine.hostname/Your_Share /home/user/shares/hostname/ -o vers=3.0,username=user,domain=hostname,uid=1000

Hope it’s help.

answered Jun 24, 2017 at 7:24

Vitalii Nesterenko's user avatar

In this tutorial, I show you how to fix the Mount CIFS Permission Denied error on Linux.

Table of Contents

  • Mount CIFS Permission Denied Error
  • Step 1 – Installing CIFS Utils
  • Step 2 – Creating a Mount Point
  • Step 3 – Editing the fstab file
  • Step 4 – Creating the .smbcredentials file
    • Step 5 – Mounting the Share
  • Wrapping up

⚠️Related Articles
Part 1 – How to install WSL 2 with Windows Terminal – Complete Guide
Part 2 – Windows Terminal Customization for WSL 2
Part 3 – In-Depth Windows Terminal Customization for WSL2

The error occurs mostly because you don’t provide sufficient credential information, specifically which Domain you are in. Most Tutorials out there only mention username and password when editing the .smbcredentials file. But let me take you through the process from the beginning.

Step 1 – Installing CIFS Utils

To mount a CIFS share on Linux, we first need to install cifs-utils. Let’s get started with that.

sudo apt-get install cifs-utils -y

Code language: JavaScript (javascript)

It should probably be pre-installed in most distros anyway.

Step 2 – Creating a Mount Point

Next, we need to create the directory where we want to Mount our Share in. You can later find the Share in this Directory. For this example, we will mount the imaginary “Photos” share.

sudo mkdir /media/share/Photos

Step 3 – Editing the fstab file

That we don’t have to mount our Share again after each reboot, we have to edit the fstab file to make the Share mount automatically after each reboot. But first, we make a backup of this file in case something goes wrong.

sudo cp /etc/fstab /etc/fstab.old

That done, we edit our fstab file.

sudo gedit /etc/fstab

And paste this line at the end of the file (all in one line)

//YourServer/Photos /media/share/Photos/ cifs vers=2.0,credentials=/home/YourLinuxUsername/.smbcredentials,iocharset=utf8,gid=1000,uid=1000,file_mode=0777,dir_mode=0777 0 0

Code language: JSON / JSON with Comments (json)

Of course, adjust accordingly to your own Server and YourLinuxUsername! We will create the .smbcredentials file next.

By default, you will have the gid=1000 and uid=1000. That’s your Group & User ID, but to make sure that those values are the same in your system, double-check it by typing:

id

mount cifs permission denied

If all is correct, hit CTRL+S to Save the fstab file and close it.

mount cifs permission denied

Step 4 – Creating the .smbcredentials file

We could enter our username directly into our fstab file, but that would not be safe as someone could clearly read our Username and Password in this unencrypted file. Therefore, we are going to create a separate file containing this information.

sudo gedit .smbcredentials

Code language: CSS (css)

And here is the key point to fixing the Mount CIFS Permission Denied error. Most guides simply state to enter Username and Password into this file, but you also have to enter your Domain!

So paste this into your .smbcredentials file:

username=yourusername password=yourpassword domain=yourdomain

Save & Close the file.

Now we just make the .smbcredentials file so that only the root user can read its contents.

sudo chmod 600 ~/.smbcredentials

Now when everything is done, try to mount the share by typing

sudo mount -a

And your share should now be successfully mounted!  If there are still some errors, try rebooting your system and see again if the Share was mounted. The share should be located in your media/share/Photos folder.

Wrapping up

It took me a while to figure out this error. I use a Synology NAS and had to set vers=2.0 in the fstab file. If you still encounter problems, try changing vers to 1.0 or 3.0. Let me know in the comments below if this solution worked for you!

This error was appeared in one of the Linux Ubuntu Server when I was trying to mount a Windows File Share to save some files.

The fix to the issue was quite an easy task, but can be a time consuming work when you are running with a busy schedule. I thought to share this with my followers and I hope this will help you to save some valuable time for your work.

I was trying to mount the File Share with the below command.

techc_admin@TCVM-01:~$ sudo mount -t cifs //techcrumblerg01diag.file.core.windows.net/tcfileshare-01 /mnt/TCFileShare/ -o vers=3.0,username=<username>,password=<password>,dir_mode=0777,file_mode=0777,serverino                            mount error(13): Permission denied
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

I forgot to add “sec=ntlmssp” parameter to the command, so the complete command would be something similar to this.

sudo mount -t cifs //techcrumblerg01diag.file.core.windows.net/tcfileshare-01 /mnt/TCFileShare/ -o vers=3.0,username=<username>,password=<password>,dir_mode=0777,file_mode=0777,serverino,sec=ntlmssp 

Sample Command which I executed when I connect Azure File Share to an Ubuntu Server.

mount error(13): Permission denied
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

What Is “sec=ntlmssp”

sec” is the security mode and it define how the passwords are encrypted between Client and the Server.

ntlmssp” stands for “NT LAN Manager Security Support Provider” is the binary messaging protocol for a Microsoft Security Support Provider Interface (MSSPI). It is the stream which provide the NTLM challenge-response authentication for the communication.

NTLMSSP is used when there is a SSPI authentication for SMB (Server Message Block) or CIFS (Common Internet File System) access in place.

Click to rate this post!

[Total: 22 Average: 4.9]

Aruna Lakmal

Associate Technical Specialist, Sri Lanka. Technology junky, enthusiast, a VMware vExpert and a blogger with more than 8 years of Experience in Virtualization and Cloud Native technologies.

Get Updates Directly To Your Inbox!

  • Печать

Страницы: [1]   Вниз

Тема: Не удается смонтировать windows share  (Прочитано 1074 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
garett

Добрый день! Возможно, банальный вопрос, но пока не смог разобраться  :idiot2: В общем, есть сервер на Убунте, там крутится Postgre, дампы баз каждый день бросаю в папку /backup (по дням недели). Теперь нужно бросать не локально, а на сервер с бэкапами (он на базе Windows). Есть расшаренный ресурс, winbackup, права выданы только админу домена. Делаю так:

sudo mount -t cifs //backup.domain.ru/winbackup /mnt/winbackup/ -o username=administrator@domain.ru,password=PASS

Думает и выдает:
mount error(13): Permission denied
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

Пароль точно правильный — несколько раз проверил. Заранее установил cifs-utils. Что тут не так? Заранее благодарен  :)


Оффлайн
ALiEN175

ASUS P5K-C :: Intel Xeon E5450 @ 3.00GHz :: 8 GB DDR2 :: Radeon R7 260X :: XFCE
ACER 5750G :: Intel Core i5-2450M @ 2.50GHz :: 6 GB DDR3 :: GeForce GT 630M :: XFCE


Оффлайн
garett

По smbtree вижу список машин домена:
DOMAIN
        \WIN7
        \MAIL
        \DC
        \DATA
        \BACKUP
        \1CSERVER

Вывод smbtree -d2:

И так далее по каждой из машин домена domain.ru. Что предпринять?

1.4. Листинги и содержимое текстовых файлов следует добавлять в сообщение с помощью тегов

Показать скрытое содержание
или [code]…[/code], либо прикреплять к сообщению в виде отдельного файла.


—toZen

« Последнее редактирование: 19 Января 2018, 10:56:03 от τοΖεη »


Оффлайн
AnrDaemon

Для начала попробуйте

sudo smbtree -d2, чтобы мусора меньше было.

Хотите получить помощь? Потрудитесь представить запрошенную информацию в полном объёме.

Прежде чем [Отправить], нажми [Просмотр] и прочти собственное сообщение. Сам-то понял, что написал?…


Оффлайн
garett

sudo smbtree -d2

1.4. Листинги и содержимое текстовых файлов следует добавлять в сообщение с помощью тегов

Показать скрытое содержание
или [code]…[/code], либо прикреплять к сообщению в виде отдельного файла.

Постарайтесь придерживаться Правил Форума пожалуйста.
—toZen

В общем-то, всё верно, и имена машин, и их IP-адреса. Но почему не удается смонтировать расшаренный каталог?

« Последнее редактирование: 19 Января 2018, 10:57:53 от τοΖεη »


Оффлайн
AnrDaemon

Попробуйте просто username=administrator
А вообще смотрите настройки связывания, в каком формате там задаётся домен.

Хотите получить помощь? Потрудитесь представить запрошенную информацию в полном объёме.

Прежде чем [Отправить], нажми [Просмотр] и прочти собственное сообщение. Сам-то понял, что написал?…


Оффлайн
garett

Действительно, помогло — если просто administrator указать  :) Попутно еще уточнить хотел — имеет ли смысл дописывать iocharset=utf8,file_mode=0777,dir_mode=0777 ? В примерах часто указывают.


Оффлайн
AnrDaemon

iocharset — да.
Моды — никогда не делайте таких ошибок.
Права должны управляться правами.
И всё таки смените пользователя на шаре.
Администратор домена должен использоваться только для одной цели — администрирования домена.
И единственное место, где допустимо хранить его пароль — в сейфе, в конвертике с надписью «вскрыть в случае моей смерти».

Хотите получить помощь? Потрудитесь представить запрошенную информацию в полном объёме.

Прежде чем [Отправить], нажми [Просмотр] и прочти собственное сообщение. Сам-то понял, что написал?…


Оффлайн
garett

Извините за беспокойство — не удается все-таки в смонтированный раздел забэкапить базу:

postgres pg_dump buh_actual > /mnt/winbackup/Thursday/buh_actual.sql
-bash: /mnt/winbackup/Thursday/buh_actual.sql: Permission denied

Посмотрел ls -lh:
drwxr-xr-x 2 root root    0 jan 25 17:14 Thursday

А надо выдать postgres postgres, использую chmod, но не удается права на каталог сменить. Как быть? Дамп сбрасывается только в каталог с правами postgres’a.

« Последнее редактирование: 25 Января 2018, 17:40:11 от garett »


Оффлайн
ALiEN175

какой-такой chmod на примонтированной шаре?  :o

в опциях монтирования добавьте

uid=postgres,gid=postgres

ASUS P5K-C :: Intel Xeon E5450 @ 3.00GHz :: 8 GB DDR2 :: Radeon R7 260X :: XFCE
ACER 5750G :: Intel Core i5-2450M @ 2.50GHz :: 6 GB DDR3 :: GeForce GT 630M :: XFCE


Оффлайн
garett

Что-то не того… Перемонтировал, вот так выглядит mount:
//backup.domain.ru/winbackup on /mnt/winbackup type cifs (rw,relatime,vers=1.0,cache=strict,username=administrator,domain=DOMAIN,uid=111,forceuid,gid=118,forcegid,addr=192.168.10.55,file_mode=0755,dir_mode=0755,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)

По ls -lh видно, что:
total 0
drwxr-xr-x 2 postgres postgres 0 jan 25 17:14 winbackup

Но дамп базы все равно не проходит:
postgres pg_dump buh_actual > /mnt/winbackup/Friday/buh_actual.sql
-bash: /mnt/winbackup/Friday/buh_actual.sql: Permission denied

Соответственно, crontab тоже не может записать ничего в этот каталог. Что еще я упустил?


Оффлайн
ALiEN175

garett,
1. на backup.domain.ru запись в папку разрешена?
2. точно права должны быть postgres:postgres? А не юзера, кто запускает команду?

C postgres не работал, понятия не имею что там и как.  :-

+ еще опций монтирования у вас как китайцев в китае. Правда все-все нужны?

ASUS P5K-C :: Intel Xeon E5450 @ 3.00GHz :: 8 GB DDR2 :: Radeon R7 260X :: XFCE
ACER 5750G :: Intel Core i5-2450M @ 2.50GHz :: 6 GB DDR3 :: GeForce GT 630M :: XFCE


Оффлайн
AnrDaemon

Хотите получить помощь? Потрудитесь представить запрошенную информацию в полном объёме.

Прежде чем [Отправить], нажми [Просмотр] и прочти собственное сообщение. Сам-то понял, что написал?…


  • Печать

Страницы: [1]   Вверх

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Official Flavours Support
  • General Help
  • [ubuntu] ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

  1. ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    I’ve been trying to share a folder, it’s actually an ‘external’ (permanent internal) HDD connected to another computer. I have a bunch of movies and TV shows, and I would like to access from other computers on my network.

    I went into properties and went to the share tab via nautilus file manager, and it shows up on my network, and the folder as well, but I get this error, whether I sign in or by guest/anonymous:

    Error when connected via sign-in:
    ‘Unable to mount location

    Failed to mount Windows share: Invalid argument’

    Error when connecting via guest/anonymous:
    ‘Unable to mount location

    Failed to mount Windows share: Permissions denied’

    I tried setting the permissions for that folder as ‘sambashare’.


  2. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    What OS is the computer the disk is physically attached to running?
    What OS are all the devices you want to provide access to the media running?


  3. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    If you follow this guide below to the tee and it still doesn’t work, your problem probably resides in how your remote shared drive is configured.
    https://wiki.ubuntu.com/MountWindowsSharesPermanently

    EDIT: This is of course assuming you are trying to connect to a remote share from an Ubuntu OS.


  4. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    Both computers are running Ubuntu 16.04 64-bit.


  5. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    Unix to Unix file sharing should use NFS. That is the native storage sharing protocol for Unix/Linux. It provides the same file/directory permissions as other Unix storage and it is faster than other methods.

    There is an nfs-server that needs to be installed (it is a kernel module) and some common nfs libraries for both sides. Configure the server to «export» the storage you want shared, how you want it shared; read-write, read-only, strict mounts, soft-mounts, etc. Then you mount it from the client using the /etc/fstab or a manual mount command. File and directory permissions work as you expect provided the numbers for the uid/gid match for all the files between all the involved systems. Normally, that means real people userids have the same uid (a number) and gid (also a number) between both systems.

    So you should decide which sort of file sharing you’d like to use between these systems. If you want to use NFS, I can help. If you want to use Samba (which is really cifs), I’ve never set that up using a GUI and cannot help. I have used samba with a few text file managed configurations, but have never used a Linux client to connect to a Linux Samba server.

    Someone else will have to help if you want to do that via a GUI. I’d check the «Ubuntu Desktop Guide» and «Ubuntu Server Guide» for how-tos for each part — client and server, respectively. There are probably other how-tos from respectable websites too, but those will make many assumptions that may or may not be true for your systems.


  6. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    The link below is to the official Ubuntu documentation on installing nfs server and client which also has example entries for your /etc/exports and /etc/fstab files. Interesting that you get the message in your thread when both computers are using Ubuntu?

    https://help.ubuntu.com/community/SettingUpNFSHowTo

    Last edited by yancek; January 26th, 2017 at 02:17 PM.


  7. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    If you are still interested in pursuing Samba, go to the machine where you created the share and post the output of the following commands:

    Code:

    net usershare info --long

    A «Failed to mount Windows share: Permissions denied» error is generally a Linux issue not a Samba issue but we really won’t know until we see how samba is set up on that machine.

    Just in case this is something else post your host name on that machine as well please:


  8. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    I think I might go with the Samba for now, it appears to be easier.

    testparm -s

    Code:

    Load smb config files from /etc/samba/smb.conf
    rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
    WARNING: The "syslog" option is deprecated
    Processing section "[printers]"
    Processing section "[print$]"
    Loaded services file OK.
    Server role: ROLE_STANDALONE
    
    
    # Global parameters
    [global]
        server string = %h server (Samba, Ubuntu)
        server role = standalone server
        map to guest = Bad User
        obey pam restrictions = Yes
        pam password change = Yes
        passwd program = /usr/bin/passwd %u
        passwd chat = *Entersnews*spassword:* %nn *Retypesnews*spassword:* %nn *passwordsupdatedssuccessfully* .
        unix password sync = Yes
        syslog = 0
        log file = /var/log/samba/log.%m
        max log size = 1000
        dns proxy = No
        usershare allow guests = Yes
        panic action = /usr/share/samba/panic-action %d
        idmap config * : backend = tdb
    
    
    
    
    [printers]
        comment = All Printers
        path = /var/spool/samba
        create mask = 0700
        printable = Yes
        browseable = No
    
    
    
    
    [print$]
        comment = Printer Drivers
        path = /var/lib/samba/printers

    net usershare info —long

    Code:

    [Videos]
    path=/media/alexa/6TBHDD/Videos
    comment=
    usershare_acl=Everyone:R,Unix Useralexa:F,
    guest_ok=y

    hostname

    Last edited by ThePowerpuffGirls; January 27th, 2017 at 03:19 AM.


  9. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    Quote Originally Posted by ThePowerpuffGirls
    View Post

    I think I might go with the Samba for now, it appears to be easier.

    Appearance is deceiving. NFS is extremely flexible (hence all the complex options), but a normal use is pretty trivial to configure provided the storage is all Linux/Unix formatted (not NTFS/vfat/fat32). Plus the storage is mounted for everyone, not just 1 userid.

    I know a little about samba. It appears that the config file posted doesn’t have any shares configured. Nothing is shared.
    I’ve never used the «usershare» stuff or seen the ACLs used in this way. That’s all new to me.

    First, the storage in /media/alexa isn’t a good place to have shared storage. That area is for automatic, temporary, storage that the OS mounts only as requested by a user. It isn’t there at boot. It isn’t mounted until a user requests it. There are other reasons to move the storage that I’ve learned over the years. Let’s say we move it to /Videos/6TBHDD (do this in the fstab).

    Then, I would add a stanza to the /etc/samba/smb.conf file that looks like this:

    Code:

    [Videos]
    path=/Videos/6TBHDD
    comment=6TBHDD Videos
    browseable = yes
    guest ok = yes

    This share will be available even if you don’t log into the system, provided the storage is mounted at boot via the fstab.

    Whatever you did to make the «usershare» would need to be removed/cleaned up too.

    HowToGeek had a usable samba how-to a few years ago that seemed to work.
    There is also howToForge with guides for all sorts of things. Both are fairly reputable.

    Anyway, that is what I would do if staying with samba.

    Wish I could help more. Sorry.

    Last edited by TheFu; January 27th, 2017 at 04:57 AM.


  10. Re: ‘Unable to mount location’ — ‘Failed to mount Windows Share: Permissions denied’

    Update: I got ti working, however it only works on mine., and half of the movies show up as like a code,
    Maybe I added ‘force user = alexa’
    I haven’t tried it on another computer yet, but will when I get up. Any idea why some of the movie files are showing up in ‘code’?

    http://i68.tinypic.com/2m7akxk.png

    Last edited by ThePowerpuffGirls; January 28th, 2017 at 02:23 AM.


Bookmarks

Bookmarks


Posting Permissions

Для работы бывает необходимо подключаться из Linux к общей папке Windows, чтобы забрать или передать файлы. В организациях в 99% используются компьютеры под управлением Windows, поэтому приходится подключаться из Linux к Windows.

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

sudo apt-get update
sudo apt-get install samba-client
sudo apt-get install cifs-utils

Для удобства просмотра сетевого окружения в GUI удобен файловый менеджер Nautilus с дополнением Nautilus-share

sudo apt-get install nautilus nautilus-share

Просмотр общих сетевых ресурсов с помощью командной строки

Вызов клиента Samba для просмотра ресурсов сервера из командной строки:

1) просмотр общих папок, предоставленных в общий доступ по сети для локальных пользователей сервера

smbclient -L //192.168.100.10 -U Username%Password

либо

smbclient -L //servername -U Username%Password

где: 192.168.100.10 — IP адрес сервера, servername — имя сервера, Username — локальный пользователь сервера, Password — пароль пользователя Username

2) просмотр общих папок, предоставленных в общий доступ по сети для пользователей домена

smbclient -L //192.168.100.10 -U Domain/Username%Password

либо

smbclient -L //192.168.100.10 -U Username%Password -W Domain

или по имени

smbclient -L //servername -U Username%Password -W Domain

где Domain — имя домена Active Directory.

Либо (чтобы каждый раз не сообщать пароль в параметрах команды) создать файл ~/.smbcredentials
с данными входа:

username=имя_пользователя
password=пароль
domain=имя_standalone_сервера_или_домена

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

smbclient //server/share --authentication-file=/home/vladimir/.smbcredentials 

Подключение к общей папке Samba в интерактивном режиме

То же самое, но без ключа -L, но с параметром — именем общей папки, в данном случае «share»

smbclient //192.168.100.10/share -U Domain/Username%Password

либо

smbclient //servername/share -U Domain/Username%Password

либо

smbclient //servername/share -U Username%Password -W Domain

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

smb: >

можно вводить команды, например, help или dir. Интерфейс для управления smbclient с помощью команд напоминает ftp клиент.

Подключение к общим папкам с помощью файлового менеджера Nautilus

После запуска nautilus, выберите в левой части окна «+ Другие места» — откроется просмотр локальной сети, где можно просматривать компьютеры в сети, у которых имеются общие папки.

Решение проблемы с подключением: избавляемся от ошибки -13 Access Denied, либо NT_STATUS_ACCESS_DENIED

Ошибка: CIFS: VFS: cifs_mount failed w/return code = -13"

Данную ошибку можно решить только настройкой прав на сервере. Чтобы открыть общую папку на просмотр, нужны три условия:
1) Пользователь указан среди пользователей сервера или домена (либо доступ типа guest разрешён)
2) Предоставлен (не ограничен) доступ к файловой системе.
3) Дан доступ к конкретной сетевой папке — например, пользователь входит в группу пользователей, к которой дан доступ к общей папке.

Последнее, третье условие самое строгое. Нужно, чтобы Администратор сервера предоставил права пользователю (включил его в группу пользователей общей папки).

Самое интересное, что права Администратора не гарантируют даже ему полных прав доступа к общей папке, т.к. необходимо, чтобы пользователь «Администратор» входил в группу, которой предоставлены права к данной сетевой папке. В этом плане администратор не отличается от группы other/nobody: получит ошибку mount error(13): Permission denied, потому что он не входит в группу пользователей сетевой папки.

Использование команды «mount»

Вместо smbclient можно использовать команду mount.

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

sudo mkdir /mnt/cifs
sudo chmod 0777 /mnt/cifs

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

sudo mount -t cifs //192.168.20.222/share /mnt/cifs -o user=Vlad,pass=Str0ngPa$$word
ls  /mnt/cifs
sudo umount //192.168.20.222/share
ls  /mnt/cifs

Либо то же самое с файлом .smbcredentials :

sudo mount -t cifs //192.168.20.222/share /mnt/cifs -o credentials=/home/vladimir/.smbcredentials

Если имя сетевой папки содержит пробелы («share with spaces in name»), нужно вводить следующим образом:

sudo mount -t cifs //192.168.20.222/share with spaces in name /mnt/cifs -o credentials=/home/vladimir/.smbcredentials

Примечание: Чтобы после выполнения команды mount примонтированная папка работала бы не только на чтение, но и на запись в удалённую общую папку, нужно сопоставить удаленного пользователя с локальным пользователем Linux, при помощи параметров uid=1000,gid-1000. Где 1000 — заменить на uid и gid пользователя Linux (выводятся командой id).
Либо добавить в параметры -o noperm,iocharset=utf8.
В ключах команды можно задать версию Samba, которую используем для подключения. Например,
для SMB2: vers=2.0 или для SMB3 vers=3.0.

Примеры:

sudo mount -t cifs //192.168.20.222/share with spaces in name /mnt/cifs -o user=username,pass=password,uid=1000,gid=1000

sudo mount -t cifs //192.168.20.222/share with spaces in name /mnt/cifs -o credentials=/home/vladimir/.smbcredentials,vers=2.0,noperm 

Если заданная версия Samba (например, SMB3) не поддерживается сервером, будет выведена ошибка "mount error(95): Operation not supported.".

Добавление параметра «nofail» пригодится, когда не известно, включен ли удалённый компьютер (сервер) или нет.

Монтирование сетевой папки во время загрузки (файл /etc/fstab)

Синтаксис строки в /etc/fstab:

//[URL]/[sharename] /mnt/[mountpoint] cifs vers=3.0,credentials=/home/username/.sharelogin,iocharset=utf8,file_mode=0777,dir_mode=0777,uid=[username],gid=[username],nofail 0 0

где:
//[URL]/[sharename] — имя сервера и сетевой папки
/mnt/[mountpoint] — точка монтирования на локальном компьютере
vers=3.0 — принудительно установить версию протокола SMB3 (либо vers=2.0 — если клиент и сервер поддерживают лишь SMB2)
credentials=/home/username/.sharelogin — указание файла с именем пользователя, паролем и доменом для входа
iocharset=utf8 — прямое указание набора символов utf8 (не обязательно, если без него работает)
file_mode=0777,dir_mode=0777 — права доступа при выполнении mount
uid=[username],gid=[username] — данные uid и gid из результата вывода команды cat /etc/passwd | grep username
nofail — загрузка ОС будет продолжена даже в случае недоступности сервера URL

Другие параметры:
defaults — включает опции rw, suid, dev, exec, auto, nouser, and async. Обычно идёт первой, т.к. можно переопределить отдельные опции в строке позднее, например: defaults, noexec, ro — нет исполнения, только чтение.
rw — очевидно, чтение-запись со стороны клиента (является противоположностью ro — только чтение (защита от записи).
suid — запрещает использование бит полномочий SUID (Set-User-IDentifier — установка идентификатора владельца) или SGID (Set-Group-IDentifier). Грубо говоря, запрещает передачу части прав при помощи битов SUID и SGID — права должны быть заданы явно.
auto — используется в /etc/fstab — разрешает автоматическое монтирование сетевых ресурсов при выполнении команды mount -a
noauto — запрет для fstab монтировать папку автоматически при выполнении команды mount -a.
nouser — прямой запрет на «ручное» монтирование всеми пользователями, кроме root (не влияет на монтирование во время загрузки ОС)
guest — для доступа к «гостевым» общим папкам, которые доступны по сети без указания имени пользователя и пароля.
async — запись данных в сетевую папку производится по мере возможности — значение по умолчанию. Повышает производительность.
sync — немедленная запись на удаленный компьютер (без использования буферов), не рекомендуется.
noperm — отключает встроенную в клиент проверку прав. Используют noperm в том случае, если права вроде бы есть, но создать файл на запись, например, программно, не получается, из-за несовместимости в реализации CIFS на клиенте и сервере.
noexec — прямой запрет запуска исполнимых файлов из сетевой папки
noatime — не обновлять время создания файла (повышает производительность, но понижает информативность)
nounix — отключение расширений Linux: не использовать символические ссылки. Используется, чтобы отключить символьные ссылки для обеспечения совместимости с Windows.
mfsymlinks — ключ для символьных ссылок в стиле Minshall+French. Этот стиль ссылок поддерживается Windows и Mac.

Примеры строки в fstab (где данные входа указаны в файле /etc/.smbcredentials):

//192.168.20.222/share_name rw,auto,nofail,credentials=/etc/.smbcredentials 0 0

Если в /etc/hosts или локальном DNS сервере прописаны имена машин, вместо IP-адреса можно подключать общую папку по имени: //server/share .

Команда для монтирования на основе fstab:

sudo mount -a

Будет перемонтированы все диски на основе /etc/fstab за исключением помеченных параметром «noauto».

Краткая информация по настройки Samba в Windows (протоколы SMB1, SMB2, SMB3)

Samba протокол имеет три версии 1, 2 и 3.
Протокол SMB1 включают, если в организации имеются машины под Windows XP. В остальных случаях стараются отключить SMB1 как небезопасный.

Включение и выключение в Windows 7 и Windows Server 2008r2 производится с помощью реестра, параметры
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetservicesLanmanServerParameters
параметры типа DWORD
SMB1=0
SMB2=1

В Windows 8, Windows 10, 11, Windows Server 2012, 2016 и выше используется командлет PowerShell

Get-SmbServerConfiguration | select EnableSMB1Protocol,EnableSMB2Protocol

Set-SmbServerConfiguration -EnableSMB2Protocol $true

Указанные командлеты не работают в ранний версиях Windows 7 и Windows Server 2008r2.
Также, SMB3 не работает в Win7 — подробнее см. здесь — сайт winitpro.ru.


Ссылки:

  • man mount.cifs

Похожие публикации

Понравилась статья? Поделить с друзьями:
  • Facebook для windows 7 скачать бесплатно на русском
  • Facebook skachat для компьютера windows 10 64 bit
  • Facebook messenger для windows скачать бесплатно
  • Facebook download for pc windows 7 64 bit
  • Failed to mount windows share invalid argument