Giter Club home page Giter Club logo

miketeo / pysmb Goto Github PK

View Code? Open in Web Editor NEW
335.0 12.0 97.0 6.96 MB

pysmb is an experimental SMB/CIFS library written in Python. It implements the client-side SMB/CIFS protocol (SMB1 and SMB2) which allows your Python application to access and transfer files to/from SMB/CIFS shared folders like your Windows file sharing and Samba folders.

License: Other

Python 99.08% Makefile 0.48% Batchfile 0.44%
smb cifs-protocol cifs-library python samba smb2

pysmb's Introduction

pysmb's People

Contributors

acpiper avatar agentsnoop avatar armann7 avatar azaubaevviktor avatar benmoran56 avatar carlosefr avatar divad avatar element-s avatar foxxyz avatar frafra avatar i4hjrl0 avatar jariinc avatar joshlin5900 avatar kbonne avatar koniiiik avatar lff5 avatar macjohnny avatar mcheciches avatar miketeo avatar petercable avatar s-t-e-v-e-n-k avatar scfarley avatar scottbrewer avatar sdvillal avatar theoharr avatar ttjoseph avatar viatoriche avatar viralmutant avatar yashikno avatar yepoleb 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

pysmb's Issues

NT 4 crypto

With the New samba update i cannot use list_shares any more. Samba CN Show a New Parameter "allow nt4 crypto = yes" does not solve the problem.

pysmb-1.1.18 (from pip): Unknown status value (0xC0000001) in SMB_COM_SESSION_SETUP_ANDX

smb.smb_structs.ProtocolError: Unknown status value (0xC0000001) in SMB_COM_SESSION_SETUP_ANDX (with extended security)
==================== SMB Message ====================
Command: 0x01 (SMB2_COM_SESSION_SETUP)
Status: 0xC0000001
Flags: 0x01
PID: 25621
MID: 2
TID: 0
Data: 9 bytes
090000000000000000
==================== SMB Data Packet (hex) ====================
fe534d4240000000010000c001000100010000000000000002000000000000001564000000000000c316f8ea0000000000000000000000000000000000000000090000000000000000

The most fun thing about this error, that if I start program second time - it will work. But with time this error arises again.

smb-error-0xC0000001.pcapng.zip

Ability to change last_access_time, last_write_time, create_time, etc.

I'm working on a project in which I need to update the access time of a bunch of files on a share.
Basically I need to re-upload some files that have been corrupted, but keep the access/write/change time the same as the original files (setting it to a time in the past). Being able to do this using pysmb would be extremely beneficial as I am using it to do all the other work on the share.

Permission denied writing files

Hi Mike,

It appears that when writing files, you use WRITE_DAC - is there any reason to do so? In our environment, most users don't have permission to write to the ACLs, thus writes tend to existing files that the user didn't create fail.

I am still looking into the details of this - and I'm not 100% convinced it's "just" this that's responsible, but will keep investigating.

Chris

Support specifing Domain variable values and OS values

Currently pysmb ignores the domain value assigned to the domain variable when setting up the SMBConnection string. It does not support OS variable settings at all and has a permanent value set of 'pysmb'. Example capture below (note DOMAIN is blank even though specified in the connection string and that OS value is pysmb)

NTLMv1 Response Captured from 192.168.1.102:64328 - 192.168.1.102
USER:William.Admin DOMAIN: OS:pysmb LM:
LMHASH:Disabled
NTHASH:6b75193e7a6f6d9afe35613530bd9f61e*********

storeFile writing 0 byte files

I'm using pysmb 1.1.13 with Python 2. I'm using the storeFIle function to copy files to a share. It is writing 0 byte files. The same piece of code works just fine on a different share on a different server.

Here's the code.

from smb.SMBConnection import SMBConnection
from smb import smb_structs
smb_structs.SUPPORT_SMB2 = False

client_machine_name = 'TESTPC'
server_name = 'testsvr'
server_ip = 'testsvr'
username = 'bob'
password = 'password'
inputfile = 'text.txt'

conn = SMBConnection(username, password, client_machine_name, server_name, use_ntlm_v2 = True)

conn.connect(server_ip, 139)

with open(inputfile, 'r') as file_obj:
numBytes = conn.storeFile('workgroup', 'testpath', file_obj, timeout=600)

conn.close()

Not sure what is different about each share that one would result in 0 byte files. Any ideas on how to troubleshoot this?

base.py uses "unicode"

unicode() is deprecated in 3. I will try to post a pull request, but simply replacing "unicode(" with "str(" should fix this, I believe.

A side note: in testing, I noticed that v1.1.12 targeted for python 3.2 still contains regular strings for bytes. In 3.3 and 3.4 this isn't a problem. Not sure if there is a reason for the difference.

Unable to delete files matching a pattern

Deleting a file without using wildcards works fine. However, I receive an error when attempting to delete files using a pattern. The docstring for deleteFiles mentions it is possible, but I didn't notice any of the tests attempting it.

>>> conn.deleteFiles('test', 'test-dir2/*')
OperationFailure: Failed to delete test-dir2\* on test: Unable to open file
==================== SMB Message 0 ====================
SMB Header:
-----------
Command: 0x05 (SMB2_COM_CREATE)
Status: 0x00000000
Flags: 0x00
PID: 17752
MID: 70
TID: 3294742596
Data: 168 bytes
390000000200000000000000000000000000000000000000800001000000000007000000010000004000000078001600900000005800000074006500730074002d0064006900720032005c002a0000002800000010000400000018001000000044486e510000000000000000000000000000000000000000180000001000040000001800000000004d78416300000000000000001000040000001800000000005146696400000000
SMB Data Packet (hex):
----------------------
fe534d42400000000000000005000000000000000000000046000000000000005845000044c861c43e2f79980000000000000000000000000000000000000000390000000200000000000000000000000000000000000000800001000000000007000000010000004000000078001600900000005800000074006500730074002d0064006900720032005c002a0000002800000010000400000018001000000044486e510000000000000000000000000000000000000000180000001000040000001800000000004d78416300000000000000001000040000001800000000005146696400000000
==================== SMB Message 1 ====================
SMB Header:
-----------
Command: 0x05 (SMB2_COM_CREATE)
Status: 0xC0000033
Flags: 0x01
PID: 17752
MID: 70
TID: 3294742596
Data: 9 bytes
090000000000000000
SMB Data Packet (hex):
----------------------
fe534d4240000000330000c005000100010000000000000046000000000000005845000044c861c43e2f79980000000000000000000000000000000000000000090000000000000000

I can't authorize on host, because machine name is 'LOCALHOST'

pysmb 1.1.17

ntlm.py:84

def generateAuthenticateMessage(challenge_flags, nt_response, lm_response, session_key, user, domain = 'WORKGROUP', workstation = 'LOCALHOST'):

call it in base.py:312 and base.py:1650

ntlm_data = ntlm.generateAuthenticateMessage(server_flags,
                                                     nt_challenge_response,
                                                     lm_challenge_response,
                                                     session_key,
                                                     self.username,
                                                     self.domain)

I have service login with fixed computer name in AD and I can't authorize on another network resource.
Code fixed this problem.

ntlm_data = ntlm.generateAuthenticateMessage(server_flags,
                                                     nt_challenge_response,
                                                     lm_challenge_response,
                                                     session_key,
                                                     self.username,
                                                     self.domain,
                                                     self.my_name)

Python3 SMBConnection.StoreFile() the opening mode of file is not checked.

If you do not open a file in binary mode 'rb' instead of 'r' before giving it to StoreFile() you'll get an error like this "TypeError: can't concat bytes to str".
Indeed in the "smb2_structs.py", line 466, the prepare method concats the result of struct.pack(...) and self.data. If the file is opened in normal mode then self.data is of type "str".
Maybe it could be good to check the format of self.data before sending it ?

query IP for domain

Send a query to the machine with ip and hopes that the machine will reply back with its domain. how to do?

calculate md5 after file upload

This is not really an issue as such, but I am uploading a file to a smb share and wanted to check the md5 before and after to make sure it has uploaded successfully. 1) is this possible using pysmb and, 2) do I need to, or does pysmb already do this kind of check for me?

Many thanks,
Mike

"smb" and "nmb" namespaces require creative package/module file names

Having "smb" and "nmb" as top-level namespaces forces client libraries to use something other than these two names. I recommend "pysmb.smb" and "pysmb.nmb".

When coming up with a naming scheme for my project, the natural choice for a submodule in the package is "smb":
mypackage/network/smb.py

However, if I do this and then "from smb.SMBConnection import SMBConnection", python thinks "smb" is the current file. Thus I have to rename smb.py something silly like "mysmb.py" or "smb1.py".

There is probably a workaround somewhere.

Python3 listPath: Can't convert bytes object to str implicitly

I have an issue with Python 3.4 (works fine in Python 2.7). Whenever I call listPath, I get the following error:

Traceback (most recent call last):
  File "smb_test.py", line 56, in collect
    files = conn.listPath('logs', path='', pattern='*.log')
  File "C:\Python34\lib\site-packages\pysmb-1.1.13-py3.4.egg\smb\SMBConnection.py", line 184, in listPath
  File "C:\Python34\lib\site-packages\pysmb-1.1.13-py3.4.egg\smb\SMBConnection.py", line 538, in _pollForNetBIOSPacket
  File "C:\Python34\lib\site-packages\pysmb-1.1.13-py3.4.egg\nmb\base.py", line 54, in feedData
  File "C:\Python34\lib\site-packages\pysmb-1.1.13-py3.4.egg\nmb\base.py", line 75, in _processNMBSessionPacket
  File "C:\Python34\lib\site-packages\pysmb-1.1.13-py3.4.egg\smb\base.py", line 137, in onNMBSessionMessage
  File "C:\Python34\lib\site-packages\pysmb-1.1.13-py3.4.egg\smb\base.py", line 274, in _updateState_SMB2
  File "C:\Python34\lib\site-packages\pysmb-1.1.13-py3.4.egg\smb\base.py", line 588, in queryCB
TypeError: Can't convert 'bytes' object to str implicitly

I have tried using is_direct_tcp=True and port 445, which produces the same error. Looking at the code:

        def queryCB(query_message, **kwargs):
            messages_history.append(query_message)
            if query_message.status == 0:
                data_buf = decodeQueryStruct(kwargs['data_buf'] + query_message.payload.data)

It appears that kwargs['data_buf'] could possibly be a string, while query_message.payload.data is a bytes object. Not sure on that though.

Doesn't work on a machine with FIPS enabled

If FIPS is enabled on a machine, this library throws an exception for any SMB operation (possibly due to MD5). Is there a workaround or a fix?

2016-02-23 11:56:54 ERROR pysmb_services.py:28 Failed to connect using pysmb [error:060800A3:digital envelope routines:EVP_DigestInit_ex:disabled for fips]

Read file .evtx

Hi,

When i would like to get a file as Security.evtx (windows logs events .evtx) with the following code:
file = open('Security.evtx', 'wb')
conn.retrieveFileFromOffset('Logs', 'Security.evtx', file)

i obtain the following issue via wireshark (STATUS_SHARING_VIOLATION):
smbviolation

When i modify the Oplock flag, i obtain the same result.

The share access attribute is the following:
share_access

When a file is not use by a system process, it's work fine...

If i access to this file with a samba share (smbmount) on linux, it's work fine and i obtain the following smbheader with the following share access attribut:
smbmount_access

Idea ?

Thx for your help,

smb.smb_structs.OperationFailure: Failed to list shares: Unable to connect to IPC$

When trying to access a Samba 3.0.33-3.40el5_10 server (which seems to be the main version on a CentOS 5 system) I'm getting the following traceback:

Traceback (most recent call last):
File "ap_67_app/scripts/smbtest.py", line 116, in
main()
File "ap_67_app/scripts/smbtest.py", line 86, in main
shares = conn.listShares(timeout=120)
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/smb/SMBConnection.py", line 148, in listShares
self._pollForNetBIOSPacket(timeout)
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/smb/SMBConnection.py", line 535, in _pollForNetBIOSPacket
self.feedData(data)
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/nmb/base.py", line 54, in feedData
self._processNMBSessionPacket(self.data_nmb)
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/nmb/base.py", line 75, in _processNMBSessionPacket
self.onNMBSessionMessage(packet.flags, packet.data)
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/smb/base.py", line 137, in onNMBSessionMessage
if self._updateState(self.smb_message):
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/smb/base.py", line 1497, in _updateState_SMB1
req.callback(message, **req.kwargs)
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/smb/base.py", line 1757, in connectCB
errback(OperationFailure('Failed to list shares: Unable to connect to IPC$', messages_history))
File "/home/jsivak/projects/ap_67_ve/lib/python2.7/site-packages/smb/SMBConnection.py", line 142, in eb
raise failure
smb.smb_structs.OperationFailure: Failed to list shares: Unable to connect to IPC$
==================== SMB Message 0 ====================

SMB Header:

Command: 0x75 (SMB_COM_TREE_CONNECT_ANDX)
Status: NTSTATUS=0x00000000
Flags: 0x08
Flags2: 0xC841
PID: 9173
UID: 100
MID: 4
TID: 0
Security: 0x0000000000000000
Parameters: 8 bytes
ff00000008000100
Data: 49 bytes
005c005c004600410052004d002d004d004f00520031002d005300520056005c00490050004300240000003f3f3f3f3f00

SMB Data Packet (hex):

ff534d4275000000000841c80000000000000000000000000000d5236400040004ff000000080001003100005c005c004600410052004d002d004d004f00520031002d005300520056005c00490050004300240000003f3f3f3f3f00
==================== SMB Message 1 ====================

SMB Header:

Command: 0x75 (SMB_COM_TREE_CONNECT_ANDX)
Status: NTSTATUS=0xC0000022
Flags: 0x88
Flags2: 0xC801
PID: 9173
UID: 100
MID: 4
TID: 0
Security: 0x0000000000000000
Parameters: 0 bytes

Data: 0 bytes

SMB Data Packet (hex):

ff534d4275220000c08801c80000000000000000000000000000d52364000400000000

Paginating directory contents

Is it possible to list a directory from a certain offset (similar to SQL's limit/offset)? This would be valuable for large directories.

I'm experimenting with changes to make this possible for SMB2. Would it be as easy as allowing the offset at https://github.com/miketeo/pysmb/blob/master/python2/smb/smb2_structs.py#L684 to be set via the request? [https://msdn.microsoft.com/en-us/library/cc246551.aspx](MSDN docs) indicate that SMB2_INDEX_SPECIFIED must be set in the flag as well.

Here's what I have so far: vinodc@b75db1a#diff-cc00e826250fdce36132bf168b068855R584

For some reason, it still seems to be enumerating the entire directory. Any pointers you had would be helpful. I've confirmed the connection is using SMB2.

pysmb does not work on azure due to broadcast flag in netbios.queryIPForName

On Azure broadcast messages are blocked.

This prevents the netbios.queryIPForName call from going through.

We've managed pysmb to work for us on Azure by changing 0x0010 to 0x0000 in nmb/base.py (in the prepareNetNameQuery method at the bottom of the file.) Basically just turning off the broadcast flag.

We don't know much (or really, anything) about the smb protocol, so we don't know if this is the right way to fix this.

In any case, what we would like to know, is whether a fix for this problem could make it into the next release?

Unknown status value (0x00010002) in SMB_COM_SESSION_SETUP_ANDX

Hi,

I'm trying to access a server which is running Zebi OS (which is on top of Solaris). When using smbclient it shows:

internal_resolve_name: returning 1 addresses: [redac]:0
Connecting to [redac] at port 445
Socket options:
        SO_KEEPALIVE = 0
        SO_REUSEADDR = 0
        SO_BROADCAST = 0
        TCP_NODELAY = 1
        TCP_KEEPCNT = 9
        TCP_KEEPIDLE = 7200
        TCP_KEEPINTVL = 75
        IPTOS_LOWDELAY = 0
        IPTOS_THROUGHPUT = 0
        SO_REUSEPORT = 0
        SO_SNDBUF = 87040
        SO_RCVBUF = 374400
        SO_SNDLOWAT = 1
        SO_RCVLOWAT = 1
        SO_SNDTIMEO = 0
        SO_RCVTIMEO = 0
        TCP_QUICKACK = 1
        TCP_DEFER_ACCEPT = 0
 session request ok
info
cli_init_creds: user [domain]\[user] domain WORKGROUP
Domain=[domain] OS=[Windows 2000] Server=[Windows 2000 LAN Manager]
 session setup ok
num_setup=1, max_setup=0, param_total=24, this_param=24, max_param=2, data_total=0, this_data=0, max_data=65535, param_offset=68, param_pad=0, param_disp=0, data_offset=92, data_pad=0, data_disp=0
 tconx ok
smb: \>

Trying to connect via pysmb I get:

>>> from smb.SMBConnection import SMBConnection
>>> c = SMBConnection(user, passwd, 'vagrant', 'work')
>>> c.connect('[redac]')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [snip]
  File "/home/vagrant/venv/local/lib/python2.7/site-packages/smb/base.py", line 1492, in _updateState_SMB1
    message.raw_data, message)
smb.smb_structs.ProtocolError: Unknown status value (0x00010002) in SMB_COM_SESSION_SETUP_ANDX (with extended security)
==================== SMB Message ====================
Command: 0x73 (SMB_COM_SESSION_SETUP_ANDX)
Status: ErrorClass=0x00 ErrorCode=0x0002
Flags: 0x90
Flags2: 0x8807
PID: 681
UID: 0
MID: 2
TID: 0
Security: 0x0000000000000000
Parameters: 0 bytes

Data: 0 bytes

==================== SMB Data Packet (hex) ====================
ff534d4273020001009007880000000000000000000000000000a90200000200000000

>>>

Any idea what I'm missing? pysmb works great when connecting to an Ubuntu server running samba 3.6.3. Is there more info I can provide?

Thanks!

parameter remote_name in SMBConnection.__init__

Could you give a comment that why the NetBIOS name is so important that we couldn't omit it? It seems that no other client needs that information.
Though it's easy to get NetBIOS name with NetBIOS().queryIPForName, I'm in trouble that this call returns None.

listPath fails sometimes

hello Mike,
I’m trying to list all files in a remote shared dir with pysmb 1.1.15 & pysmb 1.1.17(use conn.listPath method). And it will raise smb.smb_structs.OperationFailure: Failed to list xxx on xx: Unable to retrieve file list for some of my directories (most directories works ok, but a few of them fails), what’s the problem??

KeyError: 'support_dfs' found in line 1874

I'm getting a KeyError: 'support_dfs' in line 1874 when running listPath. This seems to happening when I have over 91 files in a directory. See traceback below:

files = conn.listPath(service_name, path)
  File "/.../lib/python3.4/site-packages/smb/SMBConnection.py", line 184, in listPath
    self._pollForNetBIOSPacket(timeout)
  File "/.../lib/python3.4/site-packages/smb/SMBConnection.py", line 550, in _pollForNetBIOSPacket
    self.feedData(data)
  File "/.../lib/python3.4/site-packages/nmb/base.py", line 54, in feedData
    self._processNMBSessionPacket(self.data_nmb)
  File "/.../lib/python3.4/site-packages/nmb/base.py", line 75, in _processNMBSessionPacket
    self.onNMBSessionMessage(packet.flags, packet.data)
  File "/.../lib/python3.4/site-packages/smb/base.py", line 137, in onNMBSessionMessage
    if self._updateState(self.smb_message):
  File "/.../lib/python3.4/site-packages/smb/base.py", line 1509, in _updateState_SMB1
    req.callback(message, **req.kwargs)
  File "/.../lib/python3.4/site-packages/smb/base.py", line 1874, in findFirstCB
    sendFindNext(find_message.tid, sid, last_name_offset, kwargs['support_dfs'])
KeyError: 'support_dfs'

Get file/directory attributes

SMBConnection is cool but I don't see a way to get the metadata for a file, specifically I'd like to be able to get 'offline' attribute for a file. How can I get that attribute for a file using this library?

urllib.request getters removed in Python 3.4

When trying examples in https://pythonhosted.org/pysmb/api/smb_SMBHandler.html using Python 3.4, got error:

  File "/usr/local/lib/python3.4/urllib/request.py", line 455, in open
    response = self._open(req, data)
  File "/usr/local/lib/python3.4/urllib/request.py", line 473, in _open
    '_open', req)
  File "/usr/local/lib/python3.4/urllib/request.py", line 433, in _call_chain
    result = func(*args)
  File "/share/private/jari/fb-local/ENV/lib/python3.4/site-packages/smb/SMBHandler.py", line 20, in smb_open
    host = req.get_host()
AttributeError: 'Request' object has no attribute 'get_host'

urllib.request.get_host() was deprecated in 3.3 and removed in 3.4, see: https://docs.python.org/3.3/library/urllib.request.html#urllib.request.Request.get_host

Read-only connections for "locked" files

I am trying to open a file on a share that is locked for writing by someone else; however, it would be rather useful to at least read old data out of that file... the file in question is: MySpreadsheet.xlsx, and the directory has a Windows lock file in the same directory called ~MySpreadsheet.xlsx...

I'm using this script...

from getpass import getpass
from StringIO import StringIO

from smb.SMBHandler import SMBHandler, SMBConnection

password = getpass('Windows password for mpenning: ')

conn = SMBConnection('mpenning', password, 'local-server-name', 'file-share-server-name', 
    'active-directory-name.local', use_ntlm_v2=True, 
    sign_options=SMBConnection.SIGN_WHEN_SUPPORTED, is_direct_tcp=True)
connected = conn.connect('file-share-server-name', 445)

if connected:
    print "CONNECTED", conn
    temp_fh = StringIO()

    print conn.retrieveFile('SHARE_NAME', '/Directory1/Directory2/Directory3/MySpreadsheet.xlsx', temp_fh)
    temp_fh.close()

I get the following error when I try to open that read-only file...

  File "smb_test.py", line 15, in <module>
    print conn.retrieveFile('SHARE_NAME', '/Directory1/Directory2/Directory3/MySpreadsheet.xlsx', temp_fh)
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/smb/SMBConnection.py", line 267, in retrieveFile
    return self.retrieveFileFromOffset(service_name, path, file_obj, 0L, -1L, timeout)
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/smb/SMBConnection.py", line 299, in retrieveFileFromOffset
    self._pollForNetBIOSPacket(timeout)
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/smb/SMBConnection.py", line 581, in _pollForNetBIOSPacket
    self.feedData(data)
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/nmb/base.py", line 54, in feedData
    self._processNMBSessionPacket(self.data_nmb)
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/nmb/base.py", line 75, in _processNMBSessionPacket
    self.onNMBSessionMessage(packet.flags, packet.data)
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/smb/base.py", line 143, in onNMBSessionMessage
    if self._updateState(self.smb_message):
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/smb/base.py", line 282, in _updateState_SMB2
    req.callback(message, **req.kwargs)
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/smb/base.py", line 796, in createCB
    errback(OperationFailure('Failed to list %s on %s: Unable to open file' % ( path, service_name ), messages_history))
  File "/opt/virtual_env/py27_default/lib/python2.7/site-packages/smb/SMBConnection.py", line 293, in eb
    raise failure
smb.smb_structs.OperationFailure: Failed to list \Directory1\Directory2\Directory3\MySpreadsheet.xlsx on IT_Group: Unable to open file

nmb.NetBIOS.NetBIOS.queryName should call self.prepareNameQuery with the is_broadcast keyword argument

When a nmb.NetBIOS.NetBIOS object is created with the broadcast keyword parameter set to False and nmb.NetBIOS.NetBIOS.queryName is called with the ip keyword argument no reply will be received because a query packet with the broadcast flag set is still being sent. I propose the following change to correct this:

In nmb.NetBIOS.NetBIOS.queryName this line:
data = self.prepareNameQuery(trn_id, name)

Should become this line:
data = self.prepareNameQuery(trn_id, name, is_broadcast = self.broadcast)

pysmb: python3: SyntaxError

Dear Author,

Here some concerns from python-interpreter about syntax errors in python3/nmb/NetBIOSProtocol.py

File "nmb/NetBIOSProtocol.py", line 119
expired = filter(lambda (trn_id, (expiry_time, name, d)): expiry_time < now, self.pending_trns.iteritems())
^
SyntaxError: invalid syntax

Trying to connect when already connected causes "UnboundLocalError" after 3.3

Using Python 3.3.4, pysmb 1.1.12:

from smb.SMBConnection import SMBConnection

connection = SMBConnection(USERNAME, PASSWORD, CLIENTNAME, SERVERNAME, DOMAIN)
connection.connect(IP_ADDRESS)
connection.connect(IP_ADDRESS)

causes an UnboundLocalError:

SMBConnection.py", line 505, in _pollForNetBIOSPacket
if type(ex) is tuple:
UnboundLocalError: local variable 'type' referenced before assignment

In 3.2 the socket.error passes through.
I believe this is because of changes to exceptions in socket.error in python 3.3 and newer. It looks to me that this breaks backwards compatibility, so it might be something to report to the python developers.
https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy

I think I can work around this for now, but I thought you should know. I will try to take a look at it if I get the time.

Use of type() raises an UnboundLocalError

During the handling of a ConnectionResetError raised while trying to connect to a server, an UnboundLocalError is raised because type() is used to detect whether a variable is a tuple.
Indeed, type is also the name of a variable affected a few lines later.

This issue affects both Python2 and Python3.

Two solutions:
a) change the name of the variable not to shadow a built-in name, or
b) use isinstance() instead of type() in the condition (which is the recommended way for testing types).

I'm sending a pull request that will implement b) soon.

smb.base.NotReadyError: SMB connection not authenticated

I think I'm using this library incorrectly, but I'm not sure how to use it correctly.

On Ubuntu, I can access my samba share using the command line:

smbclient smb://192.168.0.10/share_name -U domain/user_name

NetBIOS over TCP is disabled.

My python code is:

conn = SMBConnection(username='domain/user_name',
                     password=password,
                     my_name='whatever',
                     remote_name='whatever',
                     use_ntlm_v2=True, is_direct_tcp=True)
_conn = conn.connect('192.168.0.10', 445)
print(_conn)

my_name and remote_name seem irrelevant since I don't have to put them in the command line, however they are required for initialization.

However, this code results in _conn always being false. Is there something conceptually wrong? Can pysmb handle connections without netbios names?

getAttributes returns incorrect values

If I create a file on the test server, the values returned by getAttributes() are incorrect while the values returned for the same file by listPath are correct.

listPath is correct on everything but possibly not the short_name attribute. alloc_size seems big even for listPath. The file in question is 13 bytes and takes 2048 bytes (4 512-byte blocks) on disk. However, I do not know what Samba v3.6.24 is reporting. getAttributes does not return Unicode for the filename attribute.

Information retrieved by listPath:
{'alloc_size': 1048576,
'create_time': 1405439522.0,
'file_attributes': 32,
'file_size': 13,
'filename': u'info.txt',
'last_access_time': 1405439522.0,
'last_attr_change_time': 1405439522.0,
'last_write_time': 1405439522.0,
'short_name': u'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'}

getAttributes:
{'alloc_size': 4503599627370496,
'create_time': 130499131220000000,
'file_attributes': 32,
'file_size': 55834574848,
'filename': 'info.txt',
'last_access_time': 130499131220000000,
'last_attr_change_time': 130499131220000000,
'last_write_time': 130499131220000000,
'short_name': 'info.txt'}

isReadOnly missing from python3 version

Sorry to dump these on you! Thanks for all the work you've put into it!

isReadOnly is missing from the python3 version in all releases. Just copying the isReadOnly code from python2/base.py to python3/base.py worked for me.

Weird "Unable to open file" using pysmb.

Hi,

I'm trying to create a file on share via pysmb but without a luck.
Could you give any clue on what might be wrong, since creating a file from Nautilus (Ubuntu) works like a charm?

smb.smb_structs.OperationFailure: Failed to store Balalayka_salary.Res\pytest.txt on Projects: Unable to open file
==================== SMB Message 0 ====================
SMB Header:
-----------
Command: 0x03 (SMB2_COM_TREE_CONNECT) 
Status: 0x00000000 
Flags: 0x00 
PID: 6276 
MID: 9 
TID: 0 
Data: 42 bytes 
09000000480022005c005c00520045004d004f00540045005c00500072006f006a006500630074007300 
SMB Data Packet (hex):
----------------------
fe534d424000000000000000030000000000000000000000090000000000000084180000000000008d0800a4f29c00000000000000000000000000000000000009000000480022005c005c00520045004d004f00540045005c00500072006f006a006500630074007300
==================== SMB Message 1 ====================
SMB Header:
-----------
Command: 0x03 (SMB2_COM_TREE_CONNECT) 
Status: 0x00000000 
Flags: 0x01 
PID: 6276 
MID: 9 
TID: 5 
Data: 16 bytes 
100001000308000008000000ff011f00 
SMB Data Packet (hex):
----------------------
fe534d424000000000000000030001000100000000000000090000000000000084180000050000008d0800a4f29c000000000000000000000000000000000000100001000308000008000000ff011f00
==================== SMB Message 2 ====================
SMB Header:
-----------
Command: 0x05 (SMB2_COM_CREATE) 
Status: 0x00000000 
Flags: 0x00 
PID: 6276 
MID: 10 
TID: 5 
Data: 240 bytes 
3900000002000000000000000000000000000000000000009f0112002000000000000000050000004400000078003e00b800000078000000420061006c0061006c00610079006b0061005f00730061006c006100720079002e005200650073005c007000790074006500730074002e0074007800740000002800000010000400000018001000000044486e51000000000000000000000000000000000000000020000000100004000000180008000000416c5369000000008562000000000000180000001000040000001800000000004d78416300000000000000001000040000001800000000005146696400000000 
SMB Data Packet (hex):
----------------------
fe534d4240000000000000000500000000000000000000000a0000000000000084180000050000008d0800a4f29c0000000000000000000000000000000000003900000002000000000000000000000000000000000000009f0112002000000000000000050000004400000078003e00b800000078000000420061006c0061006c00610079006b0061005f00730061006c006100720079002e005200650073005c007000790074006500730074002e0074007800740000002800000010000400000018001000000044486e51000000000000000000000000000000000000000020000000100004000000180008000000416c5369000000008562000000000000180000001000040000001800000000004d78416300000000000000001000040000001800000000005146696400000000
==================== SMB Message 3 ====================
SMB Header:
-----------
Command: 0x05 (SMB2_COM_CREATE) 
Status: 0xC0000257 
Flags: 0x01 
PID: 6276 
MID: 10 
TID: 5 
Data: 9 bytes 
090000000000000000 
SMB Data Packet (hex):
----------------------
fe534d4240000000570200c00500010001000000000000000a0000000000000084180000050000008d0800a4f29c000000000000000000000000000000000000090000000000000000

I'm using Python 2.7 and smbclient says it's Windows Server 2012 R2 Standard 6.3 that serves shares. is_direct_tcp=True, port=445.

Issue with listPath()

Hi, I use your great module to get access to my mini wifi router (hootoo) usbstick (fat32). Everything seems to work except listPath() from the SMBConnection Class. Most of the time I got a error (98 out of 100 tries), but I can't find the bug.
my example
In the SMB Message 1 I can find "A: NTFS SMBu". Should it be 'FAT32' or is this correct?

Unable to connect via python3

I use pysmb 1.1.8 and python 2.7.9, 3.4.3
In python 2.7.9, it can connect to the smb server.
but in python3.4.3, can't access smb server.

code andtrace back as follows:

    def _smb_connect(self):
        self.conn = SMBConnection(self.userID, self.password, self.client_machine_name, self.server_name, self.domain, use_ntlm_v2=True)
        assert self.conn.connect(self.server_ip, 139)
        remote_filelist = self.conn.listPath(service_name=self.rootdir, path=self.logpath, pattern=u"*")  ```

```python:traceback
Traceback
  File "/usr/local/pyenv/versions/devel-3.4.3/lib/python3.4/site-packages/smb/base.py", line 651, in connectCB
    errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history))
  File "/usr/local/pyenv/versions/devel-3.4.3/lib/python3.4/site-packages/smb/SMBConnection.py", line 178, in eb
    raise failure
smb.smb_structs.OperationFailure: Failed to list サブディレクトリ on mydir: Unable to connect to shared device
==================== SMB Message 0 ====================
SMB Header:
-----------
Command: 0x03 (SMB2_COM_TREE_CONNECT)
Status: 0x00000000
Flags: 0x08
PID: 31223
MID: 3
TID: 0
Data: 46 bytes
b'0900000---6800'
SMB Data Packet (hex):
----------------------
b'fe534d4240000000---63006800'
==================== SMB Message 1 ====================
SMB Header:
-----------
Command: 0x03 (SMB2_COM_TREE_CONNECT)
Status: 0xC0000022
Flags: 0x09
PID: 31223
MID: 3
TID: 0
Data: 9 bytes
b'09000000000000005c'
SMB Data Packet (hex):
----------------------
b'fe534d4240000000----000000000000005c'

I feel like a problem due to the conversion of the character code.

listShares() shows struct.error

Hi
When running listShares(), it shows "struct.error unpack requires ..."
Then I traced the code, I found that the "data_bytes" passed to "decodeResults" was wrong.
Because some bytes were lost, offset would be wrong.
But I do not think it's caused by the unstable Internet, because I save "data_bytes" to bin file every times, and the file is always the same.
I used the tool "SoftPerfect Network Scanner", and it worked fine, so I think the server is OK.
But there are about 819 shares in the server.
However I don't know how to debug more, I hope above information could provide help.

Identifying symbolic links

When getting attributes on a symbolic link to a directory, is it possible to differentiate it from a real directory?

The File Attributes documentation appears to state that FILE_ATTRIBUTE_REPARSE_POINT is set when it is a symbolic link. However the file_attributes for the SharedFile show up as 0x10 instead. Did you have any thoughts on this?

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.