使用pysmbc通过samb读取文件

2024-06-01 07:54:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Ubuntu上的python smbc库访问samba共享。我可以很好的访问目录结构,但是我不知道如何访问实际的文件和它们的内容。网页(https://fedorahosted.org/pysmbc/)没有提到任何东西,代码是C/C++,文档很少,所以我不太确定如何使用它。

我知道Context.open(用于文件)接受uri、标志和模式,但我不知道什么是标志和模式。

有没有人使用过这个库,或者有过如何使用它读取文件的例子?

理想的情况当然是使用smbfs挂载,但是当我使用smbmount挂载同一共享时,所有文件夹都是空的。尽管我可以用smbclient浏览它,但是可以使用相同的凭据。


Tags: 文件代码httpsorg目录网页内容ubuntu
2条回答

如果您有一个开放的上下文(请参阅此处的单元测试)
*https://github.com/ioggstream/pysmbc/tree/master/tests

suri =  'smb://' + settings.SERVER + '/' + settings.SHARE + '/test.dat'  
dpath = '/tmp/destination.out'

# open smbc uri
sfile = ctx.open(suri, os.O_RDONLY)

# open local target where to copy file
dfile = open(dpath, 'wb')

#copy file and flush
dfile.write(sfile.read())
dfile.flush()

#close both files
sfile.close()    
dfile.close()

要打开上下文,只需定义一个身份验证函数

ctx = smbc.Context()

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

ctx.optionNoAutoAnonymousLogin = True
ctx.functionAuthData = auth_fn

如果不知道这是不是说得更清楚,但这里是我从这一页收集到的,并从一点额外的谷歌整理出来的:

def do_auth (server, share, workgroup, username, password):
  return ('MYDOMAIN', 'myacct', 'mypassword')


# Create the context
ctx = smbc.Context (auth_fn=do_auth)
destfile = "myfile.txt"
source = open('/home/myuser/textfile.txt', 'r')
# open a SMB/CIFS file and write to it
file = ctx.open ('smb://server/share/folder/'+destfile, os.O_CREAT | os.O_WRONLY)
for line in source:
        file.write (line)
file.close()
source.close()

# open a SMB/CIFS file and read it to a local file
source = ctx.open ('smb://server/share/folder/'+destfile, os.O_RDONLY)
destfile = "/home/myuser/textfile.txt"
fle = open(destfile, 'w')
for line in source:
        file.write (line)
file.close()
source.close()

相关问题 更多 >