「これからのための気持ちの整理。 」

これからのことを考えています。本当に、本当にめんどうくさい、めんどくさい人間です。これからのために、気持ちの整理をします。

pythonでsambaのファイルサーバーにファイルを保存する際に参考にしたリンク

qiita.com

kapibara-sos.net

samba.py

import platform
import os
from pathlib import Path
import sys
from smb.SMBConnection import SMBConnection

class Smb():
    def __init__(self, username, password, remote_name, ip):
        self.conn = SMBConnection(
                username, password, platform.node(), remote_name)
        self.ip = ip

    def __enter__(self):
        self.conn.connect(self.ip, 139)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.conn.close()

    def echo(self, data):
        return self.conn.echo(data)

    def send_file(self, local_file, svc_name, remote_dir):
        if not os.path.isfile(local_file):
            print("invalid path: {}".format(local_file))
            return False

        try:
            if not self.conn.getAttributes(svc_name, remote_dir).isDirectory:
                print("invalid remote path: {} - {}".format(svc_name, remote_dir))
                return False

            print("sending file...")
            with open(local_file, 'rb') as f:
                # store file to remote path
                path_ = os.path.join(
                        remote_dir, os.path.basename(local_file))
                self.conn.storeFile(svc_name, path_, f)

        except:
            print_exc()
            return False

    def exists(self, service_name, path):
        parent = Path(path).parent.as_posix().replace('.', '/')
        if parent == '/' or self.exists(service_name, parent):
            return bool([f for f in self.conn.listPath(service_name, parent) if f.filename == Path(path).name])


    def makedirs(self, service_name, path):
        parent = Path(path).parent.as_posix().replace('.', '/')
        if not parent == '/' and not self.exists(service_name, parent):
            makedirs(service_name, parent)
        if not self.exists(service_name, path):
            self.conn.createDirectory(service_name, path)

sendModule.py

from samba import Smb

def sendFileToFileServer(dir_name, file_name):
    params = {
        'username': '',
        'password': '',
        'remote_name': 'shared',
        'ip': 'target-host-ipaddress-or-name'
    }
    with Smb(**params) as smb:
        # print(smb.echo("echo !!"))
        smb.makedirs("shared", dir_name)
        smb.send_file(file_name, "shared", dir_name)