示例#1
0
def get_rdns_base(ip: Union[str, IPv4Address, IPv6Address, Any],
                  fallback: T = None,
                  fail=False) -> Union[str, T]:
    ip = str(stringify(ip))
    try:
        return str(socket.gethostbyaddr(ip)[0])
    except Exception as e:
        log.info('Could not resolve IP %s due to exception %s %s', ip, type(e),
                 str(e))
        if fail: raise e
        return fallback
 def test_call_sys_read(self):
     """Test reading output from call_sys by calling 'ls -l' on a temporary folder with spaces in it"""
     with TemporaryDirectory() as td:
         _temp_dir = 'path with/spaces in it'
         temp_dir = path.join(td, 'path with', 'spaces in it')
         makedirs(temp_dir)
         with NamedTemporaryFile(dir=temp_dir) as tfile:
             tfile.write(b'hello world')
             out, err = helpers.call_sys('ls', '-l', _temp_dir, cwd=td)
             out = helpers.stringify(out)
             self.assertIn(path.basename(tfile.name), out)
示例#3
0
class CryptoBaseCase(PrivexBaseCase):
    fake_b64_key = stringify(base64.urlsafe_b64encode(b'not a key'))

    @staticmethod
    def _sign_verify(priv, pub):
        """Helper method to avoid duplicating sign+verify code for every algorithm"""
        km = KeyManager(priv)  # KeyManager with private key (public key interpolated from private key)
        km_pub = KeyManager(pub)  # KeyManager with only public key
        sig = km.sign('hello world')  # Sign 'hello world' with the private key
        # Verify the signature, these methods will raise InvalidSignature if it doesn't verify.
        km_pub.verify(signature=sig, message='hello world')  # Verify with pubkey-only instance
        km.verify(signature=sig, message='hello world')  # Verify with privkey-only instance
示例#4
0
def save_rules(ipver='v4') -> List[str]:
    cmd = [] if is_root() else ['sudo', '-n']
    cmd += ['iptables-save'] if ipver in ['v4', '4', 'ipv4', 4
                                          ] else ['ip6tables-save']

    res = run_prog(*cmd)

    if res.code != 0:
        log.error(
            f"ERROR! Non-zero return code ({res.code}) from command: {cmd}")
        log.error("Command stdout: %s", res.stdout)
        log.error("Command stderr: %s", res.stderr)
        raise IPTablesError(
            f"Non-zero return code ({res.code}) from command: {cmd}")

    return stringify(res.stdout).split("\n")
示例#5
0
def set_cache_adapter(adapter: Union[str, CacheAdapter] = None,
                      reset=False) -> CacheAdapter:
    if not reset and settings.CACHE_ADAPTER_SET:
        log.debug(
            " [core.set_cache_adapter] CACHE_ADAPTER_SET is True + reset is False. Returning "
            "pre-configured adapter via adapter_get...")
        adp = adapter_get()
        log.debug(" [core.set_cache_adapter] Adapter is: %s", repr(adp))
        return adp

    adapter = empty_if(adapter, settings.CACHE_ADAPTER, zero=True)
    if empty(adapter, zero=True):
        try:
            # import redis
            log.debug(
                " [core.set_cache_adapter] Attempting to import RedisCache")
            from privex.helpers.cache.RedisCache import RedisCache
            log.debug(
                " [core.set_cache_adapter] Successfully imported RedisCache - calling adapter_set(RedisCache())"
            )
            res = adapter_set(RedisCache(use_pickle=True))
            res.set("myip:testing_cache", "test123", 120)
            crz = res.get("myip:testing_cache", fail=True)
            assert stringify(crz) == "test123"
            log.info(
                " [core.set_cache_adapter] REDIS WORKS :) - Successfully tested Redis by setting + getting a key, "
                "and validating the result. Will use Redis for caching!")
        except Exception as sce:
            log.warning(
                f"Failed to import 'privex.helpers.cache.RedisCache' for cache adapter. Reason: {type(sce)} - {sce!s}"
            )
            log.warning(
                "Please make sure the package 'redis' is installed to use the Redis adapter, and that "
                "the Redis server is actually running. Attempting to fallback to Memcached"
            )
            try:
                log.debug(
                    " [core.set_cache_adapter] Attempting to import MemcachedCache"
                )
                from privex.helpers.cache.MemcachedCache import MemcachedCache
                log.debug(
                    " [core.set_cache_adapter] Successfully imported MemcachedCache - calling adapter_set(MemcachedCache())"
                )

                res = adapter_set(MemcachedCache(use_pickle=True))
                res.set("myip:testing_cache", "test123", 120)
                crz = res.get("myip:testing_cache", fail=True)
                assert stringify(crz) == "test123"
                log.info(
                    " [core.set_cache_adapter] MEMCACHED WORKS :) - Successfully tested Memcached by setting + getting a key, "
                    "and validating the result. Will use Memcached for caching!"
                )
            except Exception as scx:
                log.warning(
                    f"Failed to import 'privex.helpers.cache.MemcachedCache' for cache adapter. Reason: {type(scx)} - {scx!s}"
                )
                log.warning(
                    "Please make sure the package 'pylibmc' is installed to use the Memcached adapter, and that "
                    "the Memcached server is actually running. Attempting to fallback to Memory Cache"
                )
                log.debug(
                    " [core.set_cache_adapter] Failed to set both redis + memcached. Falling back to "
                    "MemoryCache - adapter_set(MemoryCache())")

                res = adapter_set(MemoryCache())
                log.info(
                    " [core.set_cache_adapter] Going to use Memory Cache for caching."
                )
    else:
        log.debug(
            " [core.set_cache_adapter] Setting Cache Adapter using user specified string: %s",
            adapter)

        res = adapter_set(adapter)
        log.debug(
            " [core.set_cache_adapter] Got cache adapter from adapter_set(%s): %s",
            repr(adapter), repr(res))

    settings.CACHE_ADAPTER_SET = True
    return res
示例#6
0
def api_string(obj: Any) -> str:
    if isinstance(obj, bool):
        return 'true' if obj else 'false'
    if isinstance(obj, (Decimal, float)):
        return f"{obj:.4f}"
    return stringify(obj)