用 python 去測試 samba 服務分享出來的資料匣
以下是一個簡單的 python example 去進行網路芳鄰權限的測試, 請就需要修改的資料進行調整!!
這組程式碼中有一個測試用的檔案 “sample_file.doc”, 請自行產出或是找地方下載
首先我們先看一下這組程式碼在做什麼
1. 首先我們先設定好 samba service 所在 server 的 ip
2. 再來因為我們做資料匣分享都會設定帳號密碼與分享資料匣的名稱, 因次這邊也要一一輸入
3. 最後當我們正確連上去這個分享匣之後, 會試著進入一個子資料匣找一個指定的檔案 sample.file.doc(自行生產一個), 確定之後就會試著上傳一個檔案上去, 如果一切成功就代表你的設定沒有問題.
from smb.SMBConnection import SMBConnection
# samba server ip
ip = '192.168.1.1'
userID = 'smbuser'
userPWD = 'smbuser'
# just a name, nothing important
remote_name = 'student_VM'
# samba share folder name
targetShareFolder = 'share'
# the sub folder inside the named "share" folder
targetSubFolder = 'examineFolder'
# the file existence to be verified
targetFileName = 'sample_file.doc'
# the file to be uploaded, this file should be in the same folder with python
uploadFile = 'doExisted.csv'
conn = SMBConnection(userID, userPWD, 'windows_examiner', remote_name)
assert conn.connect(ip, timeout=3)
print("")
print('----------------- process started -------------------')
for s in conn.listShares():
if s.name == targetShareFolder:
try:
for f in conn.listPath(s.name, '/'):
# print(f.filename)
if f.filename == targetSubFolder:
for f2 in conn.listPath(s.name, '/' + targetSubFolder):
# print(f2.filename)
if f2.filename == targetFileName:
print("Task 1, Found the required files")
loadFile = open(uploadFile, 'rb')
conn.storeFile(targetShareFolder, targetSubFolder + '/' + uploadFile, loadFile)
loadFile.close()
print("Task 2, Upload file successfully")
except:
print('### can not access the resource')
print('----------------- process finished -------------------')
print('')
conn.close()