Git Product home page Git Product logo

pysmbc's Introduction

SMB bindings for Python

PyPI Build Status GitHub license

These Python bindings are intended to wrap the libsmbclient API.

Prerequisites

Currently libsmbclient 3.2.x or later is required. Ubuntu Example:

# sudo apt install build-essential pkg-config smbclient libsmbclient libsmbclient-dev python-dev

Or python3-dev instead of python-dev depending on your needs.

Build

# make

Test

To run Python tests in tests/ you need python-nose See nose documentation http://readthedocs.org/docs/nose

To run all the tests execute

# nosetests

To run just one test, use

# nosetests file.py

To selectively run test methods, printing output to console

# nosetests -vs  test_context.py:test_Workgroup

NOTE: to run your tests, you need

  • a running samba server
  • one shared folder with
    • rw permissions
    • guest ok = no

Examples

Directory listing

>>> import smbc
>>> ctx = smbc.Context (auth_fn=my_auth_callback_fn)
>>> entries = ctx.opendir ("smb://SERVER").getdents ()
>>> for entry in entries:
...     print entry
<smbc.Dirent object "music" (File share) at 0x7fbd7c42b3a0>
<smbc.Dirent object "IPC$" (IPC share) at 0x7fbd7c42b148>
<smbc.Dirent object "Charlie" (Printer share) at 0x7fbd7c42b3c8>
>>> d = ctx.open ("smb://SERVER/music")

Shared Printer Listing

>>> import smbc
>>> ctx = smbc.Context()
>>> ctx.optionNoAutoAnonymousLogin = True
>>> ctx.functionAuthData = lambda se, sh, w, u, p: (domain_name, domain_username, domain_password)
>>> uri = 'smb://' + smb_server
>>> shared_printers = []
>>> entries = ctx.opendir(uri).getdents()
>>> 	for entry in entries:
>>> 		if entry.smbc_type == 4:
>>> 			shared_printers.append(entry.name)

Write file

>>> import smbc
>>> import os
>>> ctx = smbc.Context (auth_fn=my_auth_callback_fn)
>>> file = ctx.open ("smb://SERVER/music/file.txt", os.O_CREAT | os.O_WRONLY)
>>> file.write ("hello")

Read file

>>> import smbc
>>> ctx = smbc.Context (auth_fn=my_auth_callback_fn)
>>> file = ctx.open ("smb://SERVER/music/file.txt")
>>> print file.read()
hello

pysmbc's People

Contributors

aefalcon avatar cziebuhr avatar danchr avatar debjit-bhattacharjee avatar drgogeta86 avatar drorwolmer avatar frafra avatar fumiyas avatar hamano avatar ioggstream avatar jonathonreinhart avatar jpopelka avatar matt-m-mcdonald avatar philpep avatar sb0y avatar twaugh avatar vinodc avatar zdohnal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

pysmbc's Issues

lp_set_cmdline isn't in older libsmbclients

Hi,

In the latest version of pysmbc, you use 'lp_set_cmdline' to set the client max protocol, however this call fails on RHEL6:

ImportError: /usr/lib64/python2.6/site-packages/_smbc.so: undefined symbol: lp_set_cmdline

I'm guessing this is because lp_set_cmdline isn't in Samba 3.6 (RHEL6 has 3.6.23-43).

The docs page says the minimum version of libsmbclient is 3.2, but it might be that a much later version (4.x?) is needed. Not sure!

Add seekable method

Some Python libraries (like zipfile) require to know if a file is seekable by looking at its seekable method.

Deprecation Warning

Newer Python 3 versions show the following deprecation warnings upon calling getdents():

DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats

OverflowError when reading 4GB+ files

Using a normal open() I experienced an OverflowError: size does not fit in an int.

Using Python 3.6.5. on Linux.

Please let me know if you need more information.

ctx = smbc.Context(auth_fn=my_auth_callback_fn)

Hello, do you think is possible to have more info about how to use the my_auth_callback_fn?

Am I right that the function should return the values as below?

def auth_fn(server, share, workgroup, username, password):
    return (workgroup, settings.USERNAME, settings.PASSWORD)

Cannot open directory "." with opendir()

Hi,
I am implementing samba support in a python 3.5.10 software.
I'm using version 1.0.15.6 (the one available on debian stretch, see https://packages.debian.org/stretch/python3-smbc). I also tried directly with 1.0.23.
I have an issue when trying to list "." (current directory).

>>> context.opendir("smb://user:password@host:139/share/.")
smbc errno NT_STATUS_OBJECT_NAME_INVALID -> 22
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: (22, 'Invalid argument')

However, when I just remove the ".", I can use opendir(url).getdents() and I do get the two specific resources "." and ".." (as well as all other resources).

Is this normal?

Thanks

Information about control bit is missing in getxattr response

When I use smbcacls, I see detailed about control-bits

smbcacls //server/folder sub-folder -U administrator%password

REVISION:1
CONTROL:SR|DI|DP
OWNER:Administrators
GROUP:WIN-USERS\None
ACL:user:ALLOWED/OI|CI|I/CHANGE

However, when I use the getxattr method of the pysmbc lib, I don't see the control field in the response. Is there any other method in Pysmbc that returns control bit information?

no new release

Hello,
I can download the latest release from PyPi but i cannot from Github. Can you plaese provide the latest release?
Thank you =)

TimedOutError handling

Hi,

Just faced TimedOutError. Tried to pass timeout into Context.__init__, but it won't accept it. Tried to supply .timeout attribute to context object, but it seemed to have no effect.

Is there any way I can increase the default timeout?

tell method for file objects

Thanks for the very useful code! I am hoping to use this library in conjunction with numpy and/or h5py to write array data to a remote samba filestore. numpy and h5py (as of version 2.9) can both write to file objects, as long as those objects have certain methods. However, the code I am trying to run is currently failing because the smbc.File objects returned by smbc.Context.open() do not have a tell method (h5py) nor a flush method (numpy). I've tried to look through the code to figure out whether (a) libsmbclient even supports something like tell or flush and (b) whether I could figure out how to do it, but I'm stuck - C++ is not my strength.

So: Would it be possible to incorporate tell and/or flush methods into the smbc.File objects? Please and thanks for your time. If I can get this to work, a long-term goal would be to incorporate support for samba filestores into the cottoncandy library (a useful library created by a colleague of mine to store array data in s3fs and google drive)

More generally, I'm also not sure that the absence of tell and flush will be sufficient to make my code work (there may be other missing methods too that would only generate errors later). Here are two snippets of example code that I'm hoping to use. I would be most obliged if you could test them, if you do manage to implement tell and/or flush methods, to see if anything else breaks.

For h5py:

import smbc
import h5py # must be version 2.9
import os
import numpy as np

# Setup
basedir = 'smb://my.samba.store' 
username = 'myusername'
password = 'mypassword'
workgroup = 'myworkgroup'
samba_share = 'myshare'
fdir = 'my_folder'
fname = 'hdf_test.hdf'
ctx = smbc.Context()
cb = lambda se, sh, w, u, p: (w, username, password)
ctx.functionAuthData = cb
# As a side note, specifying workgroup has been necessary
# to get this to work properly for me
ctx.workgroup = workgroup
mode = os.O_CREAT | os.O_TRUNC | os.O_WRONLY
fid = ctx.open(os.path.join(basedir, samba_share, fdir, fname), mode)

# The following lines work with a file object created by:
# fid = open(fname, mode='wb')
hf = h5py.File(fid, mode='w')
rr = np.random.randn(1000,100)
hf.create_dataset('data', shape=rr.shape, dtype=rr.dtype, data=rr)
hf.close()

fid.close()

for numpy savez:

import smbc
import h5py # must be version 2.9
import os
import numpy as np

# Setup
basedir = 'smb://my.samba.store' 
username = 'myusername'
password = 'mypassword'
workgroup = 'myworkgroup'
samba_share = 'myshare'
fdir = 'my_folder'
fname = 'numpy_test.npz'
ctx = smbc.Context()
cb = lambda se, sh, w, u, p: (w, username, password)
ctx.functionAuthData = cb
# As a side note, specifying workgroup has been necessary
# to get this to work properly for me
ctx.workgroup = workgroup
mode = os.O_CREAT | os.O_TRUNC | os.O_WRONLY
fid = ctx.open(os.path.join(basedir, samba_share, fdir, fname), mode)

# The following lines work with a file object created by:
# fid = open(fname, mode='wb')
rr = np.random.randn(1000,100)
np.savez(fid, data=rr)
fid.close()

よろしくお願い申し上げます

Fix Some Holes In Error Checking And Potential Memory Leaks

The following patch ldo-structured-error-checks.patch.txt reworks some routines to fix holes in error checking and potential memory leaks from error recovery.

The basic principle is, all temporary object pointers are initialized to NULL at the start, and unconditionally passed to Py_XDECREF at end. Ownership of objects being constructed is only passed from temporary to result pointers after completion of all operations without errors. Note in particular how the loop-within-a-loop is handled in the Dir.getdents() routine.

Issuing commands / printing

Hi.
I am trying to figure out how to replicate this functionality of smbclient:
smbclient -U username \\\\server\\printer_share -c "print file.txt"

I've looked through files but I can't figure out how to do it with this library and I would like to avoid using subprocess for compatibility reasons.

Accessing DFS Shares with PySMBC

When I have opened a context to a share and changed to a folder that is provided via DFS the code appears to hang. Is there anything special I need to do with the SMB context to open a DFS Junction ?. A wireshark trace shows "Path not covered". I appreciate this is not a problem with the library just my own lack of knowledge but any clues would be appreciated

unable to install pysmbc on windows

I am working on a project which requires pysmbc, I need to install this project on windows 10. while installing pysmbc I get the following error; any help, please;

Collecting pysmbc
Using cached pysmbc-1.0.23.tar.gz (26 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [12 lines of output]
Traceback (most recent call last):
File "", line 2, in
File "", line 34, in
File "C:\Users\LENOVO\AppData\Local\Temp\pip-install-p2tj60wg\pysmbc_e51419d09aff403eb9eca13e53bf1217\setup.py", line 118, in
library_dirs=pkgconfig_L("smbclient"),
File "C:\Users\LENOVO\AppData\Local\Temp\pip-install-p2tj60wg\pysmbc_e51419d09aff403eb9eca13e53bf1217\setup.py", line 68, in pkgconfig_L
c = subprocess.Popen(["pkg-config", "--libs", pkg], stdout=subprocess.PIPE)
File "C:\Dev\platforms\python\python39\lib\subprocess.py", line 951, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Dev\platforms\python\python39\lib\subprocess.py", line 1420, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] Sistem belirtilen dosyayı bulamıyor
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Windows SACL File Audit Policy lists

Hi there,

with
Context = smbc.Context()
ACL = Context.getxattr("smb://UserName:Password@SharePath", smbc.XATTR_ALL)
I am able to obtain the revision owner group and Discrete ACL

Is there any support for the System Access Control List

Cheers
Pearce

Support with/as

Valid code:

f = ctx.open(path, mask)
f.write(content)
f.close()

Proposal:

with ctx.open(path, mask) as f:
    f.write(content)

getxattr() fails to retrieve the ACLs for SMB Azure File Share

Hi Team,

We are trying to use pysmbc for getting meta-data of SMB Azure File Share and it's able to hit the opendir() call to retrieve the children but failed with RuntimeError: (61, 'No data available') when tried hitting getxattr() requesting the file/folder ACLs

>>> import smbc
>>> context = smbc.Context()
>>> cb = lambda se, sh, w, u, p: (domain_name, azure_file_share_name, azure_file_share_access_key)
>>> context.opendir("smb://AZURE_FILE_SHARE_PATH").getdents()
[<smbc.Dirent object "." (Dir) at 0x7fe36920eb50>, <smbc.Dirent object ".." (Dir) at 0x7fe36920ee20>, <smbc.Dirent object "Tmp" (Dir) at 0x7fe3645ebe40>]
>>> context.getxattr("smb://AZURE_FILE_SHARE_PATH", smbc.XATTR_ALL)
cli_nt_session_open fail!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: (61, 'No data available')

I increased the debug-level to 5, and compare it with smbcacls debug logs, but the ultimate result was the same. cli_nt_session_open fail in pysmbc

We are able to retrieve the ACLs for the SMB Azure File Share using smbcacls so ideally we should be able to achieve the same using pysmbc hence To DEBUG further, we have captured the TCPdump and noticed that we couldn't notice any SEC_INFO (to fetch ACL info) calls in pysmbc tcpdumps. We only see the FS_INFO call, which retrieves file/folder details.

cc: @debjit-bhattacharjee @anagda3

read() without a parameter makes seek fail

(Pdb) obj.read()
read ()
b'PK\x05\x06\x00\x00\x00\x00*\x00*\x00\xae\x0f\x00\x00\x067\xa5\x00\x00\x00'
(Pdb) obj.seek(0, 2)
seek (0, 2)
*** ValueError: (22, 'Invalid argument')

To avoid that, I always pass a number of bytes, avoiding reading more than needed.

Adding wheels (binary) release to pysmbc

My last patch added support for setuptools, which enables the possibility to generate wheels (binary) of pysmbc.

The release is hosted here: https://github.com/zehome/pysmbc-wheels

Wheels are generated against manylinux1, so it should work on most post centos-5 linux systems.

Do you want to take over the wheels package and upload it yourself to pypi or should I handle it?

pip install fails to install v1.0.22

Hello, I am trying to package the newest version 1.0.22 via nsls-ii-forge/pysmbc-feedstock#3, but am observing a strange error:

Processing $SRC_DIR
  Created temporary directory: /tmp/pip-req-build-s006bzfn
  Added file://$SRC_DIR to build tracker '/tmp/pip-req-tracker-i5g6rske'
    Running command python setup.py egg_info
    Running setup.py (path:/tmp/pip-req-build-s006bzfn/setup.py) egg_info for package from file://$SRC_DIR
    Created temporary directory: /tmp/pip-pip-egg-info-k6_ulgzy
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-req-build-s006bzfn/setup.py", line 117, in <module>
        define_macros=pkgconfig_Dversion("smbclient"),
      File "/tmp/pip-req-build-s006bzfn/setup.py", line 82, in pkgconfig_Dversion
        ver = str(int(vers[0]) * 10000 + int(vers[1]) * 100 + int(vers[2]))
    IndexError: list index out of rang

Have you observed it? Is there any known workaround? I am using python -m pip install . --no-deps -vv command during conda build. Thanks!

more of a question than an issue

I am wanting to use the debug information from smbc.Context in my code as part of research.

currently, i'm doing smbc.Context(debug=3) as it has the ability to provide some additional information regarding the SMB OID. any ideas how i might do this?

Thanks in advance.

setxattr() input and getxattr() output doesn't match

Hello Team,

We are trying to update the permissions of a folder using pysmbc module where we first try to set the permissions using setxattr() and then retrieve using the getxattr() to verify that the permissions have been updated correctly but we get all permissions revoked after applying setxattr().

Trying to set the following data and received success (0) response:

REVISION:1,OWNER:S-1-5-21-1307774611-3696762510-3468689618-1000,GROUP:S-1-5-21-1307774611-3696762510-3468689618-513,ACL:S-1-1-0:0/0/0x001f01ff,ACL:S-1-5-21-1307774611-3696762510-3468689618-1000:0/16/0x001f01ff,ACL:S-1-5-32-544:0/16/0x001f01ff,ACL:S-1-5-18:0/16/0x001f01ff,ACL:S-1-1-0:0/16/0x001f01ff

While fetching we get the following data:

REVISION:1,OWNER:S-1-5-21-1307774611-3696762510-3468689618-1000,GROUP:S-1-5-21-1307774611-3696762510-3468689618-513,ACL:S-1-1-0:0/0/0x00000000,ACL:S-1-1-0:0/16/0x00000000,ACL:S-1-5-18:0/16/0x00000000,ACL:S-1-5-32-544:0/16/0x00000000,ACL:S-1-5-21-1307774611-3696762510-3468689618-1000:0/16/0x00000000

Correspondingly the actual access is getting revoked in the WFS!

PS: Just to confirm that we are using pysmbc-1.0.23 version and wondering if this has been already fixed in some other versions. Kindly update ASAP.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.