Exemple #1
0
def test_connection(address=None, username=None, password=None,
                    server_name=None, service_name=None):
    ''' test whether an SMB share is writable '''

    address = address or SETTINGS.get('picserv_ip')
    username = username or SETTINGS.get('picserv_username')
    password = password or SETTINGS.get('picserv_password')
    server_name = server_name or SETTINGS.get('picserv_name')
    service_name = service_name or SETTINGS.get('picserv_share')

    # test whether server is reachable and has a samba service
    if not test_socket(address, SAMBA_PORT):
        return False

    try:
        conn = smb_connect(address=address,
                           username=username, password=password,
                           server_name=server_name)
    except:
        return False

    # generate random UUID as folder name
    fname = uuid.uuid4().urn[9:]
    try:
        create_folder(path=fname, service_name=service_name, conn=conn)
        delete_folder(path=fname, service_name=service_name, conn=conn)
        return True
    except:
        return False
Exemple #2
0
def ora_connect(address=None, username=None, password=None, service=None):
    ''' prepare and return a working Oracle connection based on params '''

    return cx_Oracle.connect(
        '{username}/{password}@{address}/{service}'.format(
            username=username or SETTINGS.get('db_username'),
            password=password or SETTINGS.get('db_password'),
            address=address or SETTINGS.get('db_serverip'),
            service=service or SETTINGS.get('db_sid')))
Exemple #3
0
 def save_settings(self):
     logger.info("Updating SETTINGS")
     for key, value in SETTINGS.items():
         if hasattr(self, key):
             ledit = getattr(self, key)
             if ledit.text():
                 SETTINGS.update({key: ledit.text()})
     save_settings(SETTINGS_FILE, SETTINGS)
     self.close()
Exemple #4
0
def smb_connect(address=None, username=None, password=None, server_name=None):
    ''' prepare and return a valid SMB Connection object

        Uses global settings for unspecified parameters '''

    conn = SMBConnection(username=username or SETTINGS.get('picserv_username'),
                         password=password or SETTINGS.get('picserv_password'),
                         my_name="ANAM-DESKTOP",
                         remote_name=server_name or
                         SETTINGS.get('picserv_name'))
    assert conn.connect(address or SETTINGS.get('picserv_ip'), 139)
    return conn
Exemple #5
0
def delete_file(path, service_name=None, conn=None):
    ''' delete a file at `path` on the SMB share `service_name` '''

    conn = conn or smb_connect()
    conn.deleteFiles(
        service_name=service_name or SETTINGS.get('picserv_share'),
        path_file_pattern=path)
Exemple #6
0
def test_url_socket(url=None):
    ''' shortcut to test if socket is opened from a URL '''
    try:
        u = urllib.parse.urlparse(url or SETTINGS.get('store_url'))
    except Exception as exp:
        logger.error("Unable to parse URL `{}`".format(url))
        logger.exception(exp)
        return False

    # check if address and port are reachable
    return test_socket(u.hostname, u.port or 80)
Exemple #7
0
def do_request(path, method, kwargs={}, or_none=False,
               server_url=None, server_token=None):
    ''' performs a GET or POST on `path`

        URL is computed from `server_url`, /api and `path`
        Authorization header sent with `server_token`

        Excepts `anam-receiver` formatted JSON response.
        Raises on non-success status response.

        returns response as JSON '''

    server_url = server_url or SETTINGS.get('store_url', '')
    server_token = server_token or SETTINGS.get('store_token')

    url = ''.join((server_url, '/api', path))

    if not test_url_socket(url):
        logger.info("{} requests to {} failed. No socket.".format(method, url))
        if or_none:
            return None
        else:
            raise IOError("Unable to connect to {}. Network Error".format(url))

    req = None
    try:
        req = getattr(requests, method.lower())(
            url, headers=get_auth_headers(server_token), timeout=30, **kwargs)
        assert req.status_code in (200, 201)
        resp = req.json()
        assert resp['status'] == 'success'
        return resp
    except Exception as exp:
        if req:
            logger.error(req.status_code, req.text)
        logger.exception(exp)

        # silented error
        if or_none:
            return None
        raise
Exemple #8
0
def ora_test(address=None, username=None, password=None, service=None):
    ''' tests oracle credentials by connecting to it '''
    def test_conn():
        conn = ora_connect(address=address,
                           username=username,
                           password=password,
                           service=service)
        conn.close()
        return True

    # check that server is reachable and open
    if not test_socket(address or SETTINGS.get('db_serverip'), ORACLE_PORT):
        return False

    # check that we can actually connect to it
    try:
        return test_conn()
    except:
        return False
Exemple #9
0
def copy_files(files, service_name=None, conn=None):
    ''' copy a list of files to `service_name`

        files is a list of (source_path, destitionation_path) tuples

        returns (success, [list, of, failures]) '''

    conn = conn or smb_connect()
    service_name = service_name or SETTINGS.get('picserv_share')

    def _create_folder(service_name, path):
        try:
            sharedFile = conn.getAttributes(service_name=service_name,
                                            path=path)
            assert sharedFile.isDirectory
        except OperationFailure:
            # does not exist, create folder
            create_folder(path, service_name, conn)
        except AssertionError:
            # is not a directory. remove and recreate
            delete_file(path, service_name, conn)
            create_folder(path, service_name, conn)
        else:
            # path already exist and is directory. moving on.
            return

    def _create_folder_tree(service_name, dest_filename):
        # create recursing folders on destination
        walked_folders = []
        for folder in p(dest_filename).splitall()[:-1]:
            if not folder:
                continue

            walked_folders.append(folder)
            path = os.path.join(*walked_folders)

            _create_folder(service_name, path)

    failures = []

    for local_filename, dest_filename in files:
        logger.debug("Copying `{}` to `{}`"
                     .format(local_filename, dest_filename))

        # create all folders up to dest_filename on samba share
        try:
            _create_folder_tree(service_name, dest_filename)
        except Exception as exp:
            logger.debug("Unable to create folder tree for `{}`"
                         .format(dest_filename))
            logger.exception(exp)
            failures.append((local_filename, dest_filename))
            continue

        try:
            # write file on destination (overwrites if exists)
            with open(local_filename, 'rb') as local_file:
                assert conn.storeFile(
                    service_name, dest_filename, local_file) > 0
        except Exception as exp:
            logger.error("Unable to write {s} onto {d} on SMB {sh}"
                         .format(s=local_filename, d=dest_filename,
                                 sh=service_name))
            logger.exception(exp)
            failures.append((local_filename, dest_filename))

    return not failures, failures
Exemple #10
0
def delete_folder(path, service_name=None, conn=None):
    ''' delete a folder at `path` on the SMB share `service_name` '''

    conn = conn or smb_connect()
    conn.deleteDirectory(
        service_name=service_name or SETTINGS.get('picserv_share'), path=path)
Exemple #11
0
 def __init__(self, settings_key, *args, **kwargs):
     super().__init__(*args, **kwargs)
     value = SETTINGS.get(settings_key)
     if value:
         self.setText(value)
Exemple #12
0
def get_auth_headers(token=None):
    ''' `authorization header (dict) for `requests` using `token` '''
    return {'Authorization': "Token {}".format(
        token or SETTINGS.get('store_token'))}