[Python] smb共有サーバー(共有ディスク)ファイルのアップロードとダウンロード



Smb Shared Server File Upload



ローカルエリアネットワークでは、次のようにsmbサーバーとpythonの実装を共有するためにファイルをアップロードする必要があります。

まず、インストールパッケージpysmb

pysmb pipコマンドを使用してパッケージをインストールします。パッケージは、pysmb smbプロトコルドキュメント管理モジュールをサポートします。デフォルトでは、このパッケージを独自にインストールする必要はありません。
コマンドマウントpysmb:



pip install pysmbまたはpip3 install pysmb

1つはpython2、python3の1つです。



pipはPythonパッケージ管理ツールであり、コマンドpipがない場合は、pipをインストールする必要があり、通常はデフォルトでインストールされます。

次に、サーバーsmbにログオンします

最初のインポートsmbパッケージ:

from smb.SMBConnection import SMBConnection



ログインsmbサーバーのコード例:

#!/usr/local/bin/python3 from smb.SMBConnection import SMBConnection host='xxx.xxx.xxx.xxx' #ip or domain name username='xxxxxx' password='xxxxxx' conn=SMBConnection(username,password,'','',use_ntlm_v2 = True) result = conn.connect(host, 445) print('login successful')

第三に、サーバーsmbにファイルをアップロードします

localFile=open('file path','rb') # Open local files, note that if a binary file, such as zip package, need to add the parameter b, that is binary mode, the default mode is t, that is, text text mode. conn.storeFile('Shared folder name','Storage path',localFile) # Smb upload files to the server, the default 30-second timeout, you can modify: timeout = xx. Storage path is a relative path of the shared folder. localFile.close() #shut down

記載されているアップロードバイナリファイルは、ローカルファイルを開いてもパラメータbが追加されない場合、例外がスローされます。
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbc in position 2: invalid start byte
これは、テキストファイルとしてのファイルが通常の文字にトランスコードできないためです。読み取ったバイナリファイルを変更する必要があります。

第四に、サーバーからローカルsmbにファイルをダウンロードします

ファイルをダウンロードし、()関数を開いて、2番目のパラメーター変更モードを記述します。

localFile=open('file path','wb') # Write binary files

完全なコードは次のとおりです。

localFile=open('After downloading the file path.','wb') # Create a local file, note the download binary files, such as zip package, need to add the parameter b, that is binary mode, the default mode is t, that is, text text mode. conn.storeFile('Shared folder name','All Files Path',localFile) # Smb upload files to the server, the default 30-second timeout, you can modify: timeout = xx. All file path is relative to a shared folder. localFile.close() #shut down