### Manage Passwd Map Entries (Python) Source: https://context7.com/google/nsscache/llms.txt Demonstrates how to create and manage NSS passwd map entries using the `nss_cache.maps.passwd` module. It covers manual entry creation, adding entries to a map, and iterating through the map. Default values for attributes are also highlighted. ```python from nss_cache.maps import passwd # Create passwd entry manually entry = passwd.PasswdMapEntry({ 'name': 'jdoe', 'uid': 1001, 'gid': 1001, 'passwd': 'x', 'gecos': 'John Doe,Room 123,x5678', 'dir': '/home/jdoe', 'shell': '/bin/bash' }) print(f"Username: {entry.name}") print(f"UID: {entry.uid}") print(f"GID: {entry.gid}") print(f"Home: {entry.dir}") print(f"Shell: {entry.shell}") # Create map and add entries passwd_map = passwd.PasswdMap() passwd_map.Add(entry) entry2 = passwd.PasswdMapEntry() entry2.name = 'jsmith' entry2.uid = 1002 entry2.gid = 1002 entry2.gecos = 'Jane Smith' entry2.dir = '/home/jsmith' entry2.shell = '/bin/zsh' passwd_map.Add(entry2) print(f"Total entries: {len(passwd_map)}") # Iterate entries for user_entry in passwd_map: print(f"{user_entry.name}:{user_entry.uid}:{user_entry.shell}") # Default values if not set: # - passwd: 'x' # - gecos: '' # - dir: '' # - shell: '' ``` -------------------------------- ### Synchronize Automount Maps with LDAP (Bash) Source: https://context7.com/google/nsscache/llms.txt This section details how to configure and use `nsscache` to synchronize automount maps from LDAP. It includes configuration settings for `nsscache.conf`, the command to update the cache, expected LDAP structure, and the resulting output files that autofs uses. It also shows how to restart autofs and test the mount. ```bash # Configuration in nsscache.conf [automount] ldap_base = ou=automounts,dc=example,dc=com ldap_filter = (objectclass=automountMap) cache = files files_cache_filename_suffix = files_local_automount_master = no # Command to cache automount maps nsscache update --map automount # Expected LDAP structure: # dn: cn=auto.master,ou=automounts,dc=example,dc=com # objectClass: automountMap # cn: auto.master # # dn: cn=/home,cn=auto.master,ou=automounts,dc=example,dc=com # objectClass: automount # cn: /home # automountInformation: auto.home # # dn: cn=auto.home,ou=automounts,dc=example,dc=com # objectClass: automountMap # cn: auto.home # # dn: cn=*,cn=auto.home,ou=automounts,dc=example,dc=com # objectClass: automount # cn: * # automountInformation: -rw,soft,intr nfs-server.example.com:/export/home/& # Expected output files: # /etc/auto.master: # /home auto.home # # /etc/auto.home: # * -rw,soft,intr nfs-server.example.com:/export/home/& # autofs configuration (/etc/auto.master): # +auto.master # Restart autofs to load cached maps: # systemctl restart autofs # Test mount: # ls /home/jdoe # Expected: Triggers automount of nfs-server.example.com:/export/home/jdoe ``` -------------------------------- ### Write NSS Data to Local Files Cache Source: https://context7.com/google/nsscache/llms.txt This snippet demonstrates how to use the files cache handler to write NSS maps (specifically passwd) to local text files with a '.cache' suffix. It shows the configuration of the cache handler, creating a sample passwd map with an entry, writing the cache to disk, and verifying its integrity. The expected file output and index file format are also described. ```python from nss_cache import config from nss_cache.caches import cache_factory from nss_cache.maps import passwd # Create cache handler conf = config.Config({ 'cache': 'files', 'files_dir': '/etc', 'files_cache_filename_suffix': 'cache' }) cache = cache_factory.Create(conf, 'passwd', 'files') # Create sample passwd map passwd_map = passwd.PasswdMap() entry = passwd.PasswdMapEntry({ 'name': 'jdoe', 'uid': 1001, 'gid': 1001, 'passwd': 'x', 'gecos': 'John Doe', 'dir': '/home/jdoe', 'shell': '/bin/bash' }) passwd_map.Add(entry) # Write cache to disk try: written = cache.Write(passwd_map) if written: print(f"Wrote {len(passwd_map)} entries to {cache.GetCacheFilename()}") # Output: Wrote 1 entries to /etc/passwd.cache except Exception as e: print(f"Cache write failed: {e}") # Verify cache try: is_valid = cache.Verify(passwd_map) if is_valid: print("Cache verification successful") except Exception as e: print(f"Cache verification failed: {e}") # Expected file output (/etc/passwd.cache): # jdoe:x:1001:1001:John Doe:/home/jdoe:/bin/bash # Expected index file (/etc/passwd.cache.ixname): # Binary index format for fast name-based lookups # Used by libnss-cache module for efficient getpwnam() calls ``` -------------------------------- ### Programmatic Control with NssCacheApp Python Library Source: https://context7.com/google/nsscache/llms.txt The NssCacheApp class from the nss_cache.app module serves as the main entry point for programmatic control of nsscache. It handles argument parsing, configuration loading, and command dispatching. This allows for integrating nsscache operations into Python scripts, with specific return codes indicating success or different types of failures. ```python #!/usr/bin/env python3 import os import sys from nss_cache import app # Create application instance nsscache_app = app.NssCacheApp() # Run update command programmatically return_code = nsscache_app.Run(['update', '--full'], os.environ) if return_code != 0: print(f"Update failed with code {return_code}", file=sys.stderr) sys.exit(return_code) # Run with custom config env = os.environ.copy() env['NSSCACHE_CONFIG'] = '/etc/nsscache-dev.conf' return_code = nsscache_app.Run(['-v', 'update', '--map', 'passwd'], env) # Run verify command return_code = nsscache_app.Run(['verify'], os.environ) if return_code == 0: print("All caches verified successfully") # Expected behavior: # - Returns 0 (EX_OK) on success # - Returns 75 (EX_TEMPFAIL) for temporary source failures # - Returns 78 (EX_CONFIG) for configuration errors # - Returns 71 (EX_OSERR) for system errors # - Logs to syslog when not on TTY # - Logs to stderr with timestamps when on TTY ``` -------------------------------- ### Create Mock Object with unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Replaces `self.mox.CreateMock({})` with `mock.create_autospec({})` for creating mock objects that mimic the signature of the original object. ```python import unittest.mock as mock # PyMox: # self.mox.CreateMock({}) # unittest.mock: original_object = {} mock_object = mock.create_autospec(original_object) ``` -------------------------------- ### Handle Multiple Return Values with unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Shows how to configure a mock to return a sequence of values or raise exceptions on successive calls using the `side_effect` attribute, analogous to PyMox's multiple return values. ```python import unittest.mock as mock # PyMox: # multiple return values -> side_effect=[...] # unittest.mock: mock_obj = mock.Mock() # Returning different values on each call mock_obj.method.side_effect = ['first_return', 'second_return', 'third_return'] # Example usage: # print(mock_obj.method()) # print(mock_obj.method()) # print(mock_obj.method()) ``` -------------------------------- ### Create Generic Mock Object with unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Translates `self.mox.CreateMockAnything()` to `mock.Mock()`, which creates a generic mock object that can be used when the specific type or signature is not important. ```python import unittest.mock as mock # PyMox: # self.mox.CreateMockAnything() # unittest.mock: mock_anything = mock.Mock() ``` -------------------------------- ### Configure LDAP Source for NSS Data Source: https://context7.com/google/nsscache/llms.txt This configuration section details how to set up nsscache to fetch NSS data from an LDAP directory service. It supports TLS, SASL authentication, pagination, nested groups, and both RFC 2307 and RFC 2307bis schemas. Specific settings for Active Directory, connection resilience, and nested group expansion are provided. ```python # Configuration in nsscache.conf # LDAP source with TLS and authentication [DEFAULT] source = ldap ldap_uri = ldaps://ad.example.com:636 ldap_base = dc=example,dc=com ldap_bind_dn = cn=svc-nsscache,ou=services,dc=example,dc=com ldap_bind_password = SecurePassword123 ldap_tls_require_cert = demand ldap_tls_cacertfile = /etc/ssl/certs/ca-bundle.crt # Active Directory specific settings ldap_ad = 1 ldap_use_rid = 1 ldap_offset = 10000 ldap_override_shell = /bin/bash ldap_home_dir = 1 # Connection resilience ldap_retry_max = 5 ldap_retry_delay = 10 ldap_timelimit = 60 # SASL/GSSAPI authentication ldap_use_sasl = True ldap_sasl_mech = gssapi # RFC 2307bis schema (member DN lists) ldap_rfc2307bis = 1 # Nested group expansion [group] ldap_base = ou=groups,dc=example,dc=com ldap_filter = (objectclass=group) ldap_nested_groups = 1 # Command line usage: # export KRB5CCNAME=/tmp/krb5cc_0 # kinit svc-nsscache@EXAMPLE.COM # nsscache update # Expected behavior: # - Connects to LDAP using TLS # - Authenticates with SASL GSSAPI or simple bind # - Fetches users, groups, shadow, netgroup, automount maps # - Handles pagination for large directories # - Converts Active Directory RIDs to Unix UIDs/GIDs # - Expands nested group memberships recursively ``` -------------------------------- ### Raise Exceptions with Mock using unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Demonstrates how to make a mock raise a specific exception when called, using `side_effect` with an exception instance, equivalent to PyMox's `AndRaise(r)`. ```python import unittest.mock as mock # PyMox: # {}.AndRaise(r) # unittest.mock: mock_obj = mock.Mock() # Configure the mock to raise a ValueError mock_obj.method.side_effect = ValueError('Something went wrong') # Example usage: # try: # mock_obj.method() # except ValueError as e: # print(f'Caught expected exception: {e}') ``` -------------------------------- ### Replace Attribute with Mock using unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Shows how to replace an attribute of an object with a mock using `mock.patch.object` (or direct assignment for simpler cases), equivalent to `self.mox.StubOutWithMock(a, b)`. ```python import unittest.mock as mock class TargetClass: def __init__(self): self.attribute_to_mock = None # PyMox: # self.mox.StubOutWithMock(a, b) # unittest.mock (using patch decorator): # @mock.patch.object(TargetClass, 'attribute_to_mock') # def test_method(self, mock_attribute): # # mock_attribute is now a mock object # pass # unittest.mock (direct assignment): obj = TargetClass() obj.attribute_to_mock = mock.Mock() ``` -------------------------------- ### Replace Class with Mock using unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Illustrates replacing an entire class with a mock using the `@mock.patch` decorator, which is the `unittest.mock` equivalent of PyMox's `StubOutClassWithMocks`. ```python import unittest.mock as mock class ClassToMock: pass # PyMox: # self.moxk.StubOutClassWithMocks(a, b) # unittest.mock: # @mock.patch('__main__.ClassToMock') # Use the string path to the class # def test_method(self, MockClass): # # MockClass is now a mock object representing ClassToMock # instance = MockClass() # pass ``` -------------------------------- ### Retrieve SSH Keys for User (Python) Source: https://context7.com/google/nsscache/llms.txt This Python script retrieves SSH public keys for a given username from a cache file. It handles cases where a user might have multiple keys or keys are stored in a list format. The script exits with a status code indicating success (0) or failure (1). ```python #!/usr/bin/python3 from ast import literal_eval import sys import errno DEFAULT_SSHKEY_CACHE = "/etc/sshkey.cache" def get_keys_for_user(username, cache_file=DEFAULT_SSHKEY_CACHE): """Retrieve SSH public keys for a user from the cache.""" try: with open(cache_file, 'r') as f: for line in f: cache_user, key_data = line.split(':', 1) if cache_user != username: continue key_data = key_data.strip() # Handle both single key and list formats if key_data.startswith('[') and key_data.endswith(']'): keys = [k.strip() for k in literal_eval(key_data)] else: keys = [key_data] for key in keys: print(key) return 0 except IOError as err: if err.errno not in [errno.EPERM, errno.ENOENT]: raise return 1 if __name__ == "__main__": if len(sys.argv) < 2: sys.exit(1) username = sys.argv[1] sys.exit(get_keys_for_user(username)) ``` -------------------------------- ### Display Cache Status using nsscache CLI Source: https://context7.com/google/nsscache/llms.txt The 'nsscache status' command displays the current state of cache files. It shows the last update time, entry counts, and modification timestamps. Options include specifying individual maps or using verbose output for detailed information. This helps diagnose synchronization issues and verify cache freshness. ```bash # Show status of all configured maps nsscache status # Show status of specific maps nsscache status --map passwd # Verbose status with detailed information nsscache -v status # Expected output: # passwd: # Cache file: /etc/passwd.cache # Last update: 2026-01-11 10:15:23 # Entries: 1523 # File size: 89234 bytes # Index exists: yes # # group: # Cache file: /etc/group.cache # Last update: 2026-01-11 10:15:25 # Entries: 234 # File size: 12456 bytes # Index exists: yes ``` -------------------------------- ### Configure SSH Public Key Caching from LDAP Source: https://context7.com/google/nsscache/llms.txt This snippet explains how to configure nsscache to cache SSH public keys from LDAP. It shows the necessary configuration in nsscache.conf, including LDAP base and filter settings. It also provides the command to update the SSH key cache and details the expected format of the cached SSH keys file. Additionally, it includes sample `sshd_config` settings for using an `AuthorizedKeysCommand` script. ```ini # Configuration in nsscache.conf [sshkey] ldap_base = ou=people,dc=example,dc=com ldap_filter = (objectclass=posixAccount) # Command to cache SSH keys # nsscache update --map sshkey # Expected cache format (/etc/sshkey.cache): # jdoe:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDm7... user@host # jsmith:['ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...', 'ssh-ed25519 AAAAC3NzaC1lZDI...'] # sshd_config configuration: # AuthorizedKeysCommand /usr/local/bin/authorized-keys-command.py # AuthorizedKeysCommandUser nobody ``` -------------------------------- ### Configure HTTP Source for NSS Data Source: https://context7.com/google/nsscache/llms.txt This configuration enables nsscache to retrieve NSS data from HTTP or HTTPS endpoints. It's useful for distributing static NSS data or custom directory exports. The configuration includes proxy settings, map-specific URLs, TLS certificate validation, and retry logic for network resilience. The expected server response format matches standard /etc/passwd and /etc/group files. ```python # Configuration in nsscache.conf [DEFAULT] source = http http_proxy = http://proxy.example.com:8080 # Map-specific URLs passwd_url = https://nss.example.com/exports/passwd.txt group_url = https://nss.example.com/exports/group.txt shadow_url = https://nss.example.com/exports/shadow.txt sshkey_url = https://nss.example.com/exports/sshkey.txt netgroup_url = https://nss.example.com/exports/netgroup.txt # TLS certificate validation http_tls_cacertfile = /etc/ssl/certs/ca-certificates.crt # Retry configuration http_retry_max = 3 http_retry_delay = 5 # Command line usage: # nsscache update --full # Expected server response format for passwd: # username:x:1001:1001:John Doe:/home/username:/bin/bash # jsmith:x:1002:1002:Jane Smith:/home/jsmith:/bin/zsh # Expected server response format for group: # developers:x:2001:jdoe,jsmith,alee # admins:x:2002:root,admin # Expected behavior: # - Downloads data via HTTPS with certificate verification # - Parses standard /etc/passwd and /etc/group format # - Supports compressed (bzip2) responses # - Implements retry logic with exponential backoff # - Writes to /etc/passwd.cache, /etc/group.cache, etc. ``` -------------------------------- ### Mock Method Return Value with unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Demonstrates how to set the return value of a mocked method using `mock.Mock().return_value = ret`, contrasting with PyMox's `AndReturn(ret)`. ```python import unittest.mock as mock # PyMox: # {}.fn(args...).AndReturn(ret) # unittest.mock: mock_obj = mock.Mock() # Assume 'fn' is a method on mock_obj mock_obj.fn.return_value = 'expected_return_value' # Later, to assert the call: # mock_obj.fn.assert_called_with(args) ``` -------------------------------- ### Ignore Arguments in Mock Calls with unittest.mock Source: https://github.com/google/nsscache/blob/main/doc/mox_to_mock.md Explains that `mock.ANY` in `unittest.mock` serves the same purpose as `mox.IgnoreArg()` in PyMox, allowing flexible argument matching during mock assertions. ```python import unittest.mock as mock # PyMox: # mox.IgnoreArg() # unittest.mock: mock_obj = mock.Mock() # Call the mock with any arguments mock_obj.some_method('any_value', 123) # Assert that it was called, ignoring specific arguments mock_obj.some_method.assert_called_with(mock.ANY, mock.ANY) ``` -------------------------------- ### Configure and Update S3 Source for NSS Data Source: https://context7.com/google/nsscache/llms.txt This snippet details how to configure the nsscache to use S3 as a source for NSS data (passwd, group, shadow, sshkey). It outlines the configuration parameters in nsscache.conf, AWS credential management, and the command-line usage for updating the cache. The expected S3 object format for passwd and group files is also provided. ```ini # Configuration in nsscache.conf [DEFAULT] source = s3 bucket = my-company-nsscache passwd_object = nss/passwd.txt group_object = nss/group.txt shadow_object = nss/shadow.txt sshkey_object = nss/sshkey.txt # AWS credentials from environment, instance profile, or ~/.aws/credentials # export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE # export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY # export AWS_DEFAULT_REGION=us-east-1 # Command line usage: # nsscache update # Expected S3 object format (passwd.txt): # jdoe:x:1001:1001:John Doe:/home/jdoe:/bin/bash # jsmith:x:1002:1002:Jane Smith:/home/jsmith:/bin/bash # Expected S3 object format (group.txt): # developers:x:2001:jdoe,jsmith # operations:x:2002:alee,bwong ``` ```python import boto3 s3_client = boto3.client('s3') # Upload passwd file with open('/tmp/passwd.txt', 'rb') as f: s3_client.put_object( Bucket='my-company-nsscache', Key='nss/passwd.txt', Body=f, ServerSideEncryption='AES256' ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.