web-dev-qa-db-ja.com

smbプロトコルpython3を使用してサーバー上のリモートファイルにアクセスする

いくつかのファイルを含むリモートサーバーがあります。

_smb://ftpsrv/public/
_

そこで匿名ユーザーとして認証を受けることができます。 Javaでこのようなコードを簡単に書くことができます

SmbFile root = new SmbFile(SMB_ROOT);

内部のファイルを操作する機能を取得します(必要なのは1行だけです)が、python3でこのタスクを管理する方法を見つけることができません。多くのリソースがありますが、それらは関連がないと思います私にとっては、彼らは頻繁にpython2や古いアプローチに合わせて調整されているからです。 Javaコードのような簡単な方法はありますか?または、たとえば、_fgg.txt_フォルダー内のファイル_smb://ftpsrv/public/_にアクセスしたい場合、実際の解決策を誰かが提供できます。この問題に取り組むのに本当に便利なlibはありますか?

たとえば、現場で

_import tempfile
from smb.SMBConnection import SMBConnection

# There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip
# client_machine_name can be an arbitary ASCII string
# server_name should match the remote machine name, or else the connection will be rejected
conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
assert conn.connect(server_ip, 139)

file_obj = tempfile.NamedTemporaryFile()
file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', file_obj)

# Retrieved file contents are inside file_obj
# Do what you need with the file_obj and then close it
# Note that the file obj is positioned at the end-of-file,
# so you might need to perform a file_obj.seek() if you need
# to read from the beginning
file_obj.close()
_

これらすべての詳細を真剣に提供する必要があるのでしょうかconn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)

5
Alex

Python 3でurllibとpysmbを使用してファイルを開く簡単な例

import urllib
from smb.SMBHandler import SMBHandler
opener = urllib.request.build_opener(SMBHandler)
fh = opener.open('smb://Host/share/file.txt')
data = fh.read()
fh.close()

匿名のSMBの共有をテストする準備ができていませんが、このコードは機能するはずです。
urllib2は、python 2パッケージ、python 3では、urllibに名前が変更され、いくつかのものが移動しました。

1
Rick Rongen