2025年1月31日 星期五

兩台電腦如何存取同一個檔案

今天遇到的問題 : 兩台電腦如何存取同一個檔案

大概有想到幾個方法

1. ubuntu 開 share folder 給 windows

2. windows 開 share folder 給 unbuntu

3. 用 mongoDB 做 KV store

4. 用 amazonS3

最後採用 1 的作法,順便記錄一下

一開始先是上網 google 了一下

很快就找到一堆人講,試了 2 個都不 work,也不知道是缺啥

打開 chatgpt 問一下詳細多了

step1. 安裝 Samba(SMB)

sudo apt update
sudo apt install samba

step2. 編輯設定檔

sudo nano /etc/samba/smb.conf

打開後 scroll 到最下面,然後加入下面這段

[SharedFolder]
path = /path/to/share
available = yes
valid users = your_username
read only = no
browsable = yes
public = yes
writable = yes

step3. 設定 Samba 密碼

sudo smbpasswd -a your_username

step4. 重啟 Samba 服務

sudo systemctl restart smbd

step5. 防火牆允許 Samba 服務

sudo ufw allow samba

step6. 完成,現在可以在File Explorer輸入下列位置就可以訪問了

\\ubuntu_ip_address\SharedFolder

他會要你輸入 username & password 就是你在 step3 設置的

----------------------------------------------------------------------------------------------

如果我在 Ubuntu 有兩個資料夾要分享該怎麼做?

chatgpt 的回答如下,供參考

step1. 編輯設定檔

sudo nano /etc/samba/smb.conf

打開後 scroll 到最下面,然後加入下面這段

[Folder1]
path = /home/username/folder1
available = yes
valid users = your_username
read only = no
browsable = yes
public = yes
writable = yes

[Folder2]
path = /home/username/folder2
available = yes
valid users = your_username
read only = no
browsable = yes
public = yes
writable = yes

----------------------------------------------------------------------------------------------

如果要用 python 存取 shared folder 該怎麼做?

1. 使用 smbprotocol

pip install smbprotocol

然後使用下面這段程式

import smbprotocol
from smbprotocol import smb2
from smbprotocol import client

# Initialize the SMB protocol (need to run this before anything else)
smbprotocol.ClientConfig(username="your_username", password="your_password", domain="WORKGROUP")

# Set the server address and share name
server = "192.168.1.100"  # IP address of the Ubuntu machine with the shared folder
share = "Folder1"  # The name of the share in smb.conf
file_path = "testfile.txt"  # File inside the shared folder you want to access

# Connect to the share
client = smb2.SMB2(server, 445)

# Open the shared folder and access the file
with client.open(share, file_path, "rb") as file:
    data = file.read()  # Read the file content
    print(data.decode())  # Print the content of the file

# You can also use client.list() to list files and directories
for item in client.list(share):
    print(item)

But

我想使用 json 來做存取,譬如下面這樣

with open(json_path, mode="w", encoding="utf-8") as f: 
    json.dump(json_data, f, indent=4, ensure_ascii=False)

這時候 chatgpt 就建議使用 mount 的方式了

如果是用 windows 的話,打開 File Explorer 的首頁

按右鍵就會出現 Add a network location



在 windows 我可以用以下 path 存取

path = r"\\192.168.50.75\sharedfolder\bb.json"

但這段字丟到 linux 上會有問題,用下面這樣打開 json 會報錯

with open(json_path, mode="r", encoding="utf-8") as f: 
    json_data = json.loads(f.read())

因為 linux 上使用的是 "/" 而不是 "\"

所以要做

path = path.replace("\\", "/")

大概是這樣