Files
MiPi_TEST/ai_mgmt.py

99 lines
2.6 KiB
Python
Raw Normal View History

2026-04-07 15:17:32 +01:00
import socket
2026-04-07 15:58:01 +01:00
from pathlib import Path
2026-04-07 15:17:32 +01:00
from smb.SMBConnection import SMBConnection
SERVER = "192.168.45.4"
SHARE = "AGILENT"
2026-04-07 15:58:01 +01:00
USERNAME = ""
2026-04-07 15:17:32 +01:00
PASSWORD = ""
CLIENT_NAME = socket.gethostname()
2026-04-07 15:58:01 +01:00
SERVER_NAME = SERVER
2026-04-07 15:17:32 +01:00
2026-04-07 15:58:01 +01:00
DATA_DIR = Path(__file__).parent / "data"
2026-04-07 15:17:32 +01:00
2026-04-07 15:58:01 +01:00
def _connect():
2026-04-07 15:17:32 +01:00
conn = SMBConnection(
2026-04-07 15:58:01 +01:00
USERNAME, PASSWORD,
2026-04-07 15:17:32 +01:00
CLIENT_NAME, SERVER_NAME,
use_ntlm_v2=True,
2026-04-07 15:58:01 +01:00
is_direct_tcp=True
2026-04-07 15:17:32 +01:00
)
2026-04-07 15:58:01 +01:00
if not conn.connect(SERVER, 445):
raise ConnectionError("Failed to connect to SMB share.")
return conn
2026-04-07 15:17:32 +01:00
2026-04-07 15:58:01 +01:00
def list_csv_files(server=SERVER, share=SHARE, username=USERNAME, password=PASSWORD):
"""Return a list of all .csv paths found on the share (recursive)."""
conn = _connect()
2026-04-07 15:17:32 +01:00
csv_files = []
def walk(path):
2026-04-07 15:58:01 +01:00
for entry in conn.listPath(share, path):
2026-04-07 15:17:32 +01:00
if entry.filename in (".", ".."):
continue
full_path = f"{path}/{entry.filename}"
if entry.isDirectory:
walk(full_path)
elif entry.filename.lower().endswith(".csv"):
csv_files.append(full_path)
try:
walk("/")
finally:
conn.close()
return csv_files
2026-04-07 15:58:01 +01:00
def transfer_csv_files():
"""
Copy all .csv files from the scope share to DATA_DIR,
then delete them from the scope.
Returns (copied, failed) counts.
"""
DATA_DIR.mkdir(exist_ok=True)
conn = _connect()
copied = 0
failed = 0
try:
csv_files = []
def walk(path):
for entry in conn.listPath(SHARE, path):
if entry.filename in (".", ".."):
continue
full_path = f"{path}/{entry.filename}"
if entry.isDirectory:
walk(full_path)
elif entry.filename.lower().endswith(".csv"):
csv_files.append(full_path)
walk("/")
for remote_path in csv_files:
filename = Path(remote_path).name
local_path = DATA_DIR / filename
try:
with open(local_path, "wb") as f:
conn.retrieveFile(SHARE, remote_path, f)
conn.deleteFiles(SHARE, remote_path)
print(f" TRANSFERRED: {filename}")
copied += 1
except Exception as e:
print(f" FAILED: {filename}{e}")
failed += 1
finally:
conn.close()
return copied, failed
2026-04-07 15:17:32 +01:00
if __name__ == "__main__":
2026-04-07 15:58:01 +01:00
print(f"Transferring CSV files from \\\\{SERVER}\\{SHARE} to {DATA_DIR}...\n")
copied, failed = transfer_csv_files()
print(f"\nDone. {copied} transferred, {failed} failed.")