pysmb#
- pysmb を用いて リモートファイルサーバーから対象ディレクトリ配下のファイル名(パス)を再帰的に取得するプログラム。
Warning
手元の環境では (以下のread_file関数部分)ファイルの内容の読み取りに失敗
import datetime
import os
import io
import sys
ffrom smb.SMBConnection import SMBConnection
import time
参考: https://end0tknr.hateblo.jp/entry/20200524/1590283421
PARAMS = {
'userID':'test',
'password':'p@ssw0rd',
'server_name':'TEST'
'server_ip':'192.168.32.250',
'remote_port':445,
'is_direct_tcp':True,
'remote_path':'share',
'sleep':0.2
}
def manin():
smb_connection = SMBConnection(
PARAMS['userID'],
PARAMS['password'],
platform.uname().node,
PARAMS['server_name'],
is_direct_tcp=PARAMS['is_direct_tcp'],
use_ntlm_v2=True
)
try:
smb_connection.connect(PARAMS['server_ip'],PARAMS['remote_ip'])
except Exception as e:
print(f'Connection failed Reason: {e}')
target_dir = '/tmp'
file_list = []
result = get_filePath(smb_connection, target_dir, file_list)
read_file(smb_connection, file_list)
smb_connection.close()
# smb.smbstructs.oeprationfailure unable to open file
def read_file(cmb_connection, file_list):
for fileName in file_list:
print(filename)
with io.BytesIO() as file:
smb_connection.retrieveFile(PARAMS['remote_path'], fileName, file)
file.seek(0)
print(file.read().decode())
def get_filePath(cmb_connection,target_dir, file_list):
time.sleep(PARAMS['sleep'])
dir_list = smb.connection.listPath(PARAMS['remote_path'], target_dir)
for dir_or_file in dir_list:
if dir_or_file.filename == '.' or dir_or_file.filename == '..':
continue
if dir_or_file.isDirectory:
next_dir = target_dir + '/' dir_or_file.filename
# 再帰関数で処理
get_filePath(smb_connection, next_dir, file_list)
else:
if '.log' in dir_or_file.filename:
filePath = target_dir + dir_or_file.filename
file_list.append(filePath)
return file_list
if __name__ == '__main__':
main()