第三方調用saltstack

python api使用

實例及工作原理解析

指定target 函數,命令等等,就可以可以了。

[root@mcw01 ~]# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
[root@mcw01 ~]# 
[root@mcw01 ~]# python3
Python 3.6.8 (default, Nov 14 2023, 16:29:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.client
>>> local = salt.client.LocalClient()
>>> local.cmd('mcw03','cmd.run',['hostname'])
{'mcw03': 'mcw03'}
>>> 

查找導入包的路徑

>>> import salt
>>> salt.__path__
['/usr/lib/python3.6/site-packages/salt']
>>> 

尋找上面LocalClient所在位置:

[root@mcw01 salt]# grep -Rn 'LocalClient' .|egrep 'class|def'
./client/__init__.py:133:class LocalClient:
./config/__init__.py:3997:    :py:class:`~salt.client.LocalClient`.
./netapi/rest_cherrypy/app.py:285:* "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends
./netapi/rest_cherrypy/app.py:504:via the ``expire_responses`` setting, and both :py:class:`LocalClient
./netapi/rest_cherrypy/app.py:505:<salt.client.LocalClient>` and :py:class:`RunnerClient
./netapi/rest_tornado/saltnado.py:1187:            salt.client.LocalClient.run_job, chunk, is_class_method=True
./utils/event.py:999:class LocalClientEvent(MasterEvent):
[root@mcw01 salt]# 

這個文件

[root@mcw01 salt]# less ./client/__init__.py
[root@mcw01 salt]# 
  .. code-block:: python

        import salt.client

        local = salt.client.LocalClient()
        local.cmd('*', 'test.fib', [10])

    """

....
    def cmd(
        self,
        tgt,
        fun,
        arg=(),
        timeout=None,
        tgt_type="glob",
        ret="",
        jid="",
        full_return=False,
        kwarg=None,
        **kwargs
    ):


....

        was_listening = self.event.cpub

        try:
            pub_data = self.run_job(
                tgt,
                fun,
                arg,
                tgt_type,
                ret,
                timeout,
                jid,
                kwarg=kwarg,
                listen=True,
                **kwargs
            )

            if not pub_data:
                return pub_data



運行了run_job



----
   def run_job(
        self,
        tgt,
        fun,
        arg=(),
        tgt_type="glob",
        ret="",
        timeout=None,
        jid="",
        kwarg=None,
        listen=False,
        **kwargs
    ):

        """
        Asynchronously send a command to connected minions

        Prep the job directory and publish a command to any targeted minions.

        :return: A dictionary of (validated) ``pub_data`` or an empty
            dictionary on failure. The ``pub_data`` contains the job ID and a
            list of all minions that are expected to return data.

        .. code-block:: python

            >>> local.run_job('*', 'test.sleep', [300])
            {'jid': '20131219215650131543', 'minions': ['jerry']}
        """
        arg = salt.utils.args.condition_input(arg, kwarg)

        try:
            pub_data = self.pub(
                tgt,
                fun,
                arg,
                tgt_type,
                ret,
                jid=jid,
                timeout=self._get_timeout(timeout),
                listen=listen,
                **kwargs
            )
        except SaltClientError:
            # Re-raise error with specific message
            raise SaltClientError(
                "The salt master could not be contacted. Is master running?"
            )
        except AuthenticationError as err:
            raise
        except AuthorizationError as err:
            raise
        except Exception as general_exception:  # pylint: disable=broad-except
            # Convert to generic client error and pass along message
            raise SaltClientError(general_exception)

        return self._check_pub_data(pub_data, listen=listen)

通過api獲取saltstack配置

獲取master配置信息

[root@mcw01 ~]# python3
Python 3.6.8 (default, Nov 14 2023, 16:29:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.config
>>> master_opts=salt.config.client_config('/etc/salt/master')
>>> dir(master_opts) #查看屬性
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> type(master_opts) #查看類型
<class 'dict'> 
>>> print(dict(master_opts)) #查看master配置,字典形式打印
{'token_file': '/root/salt_token', 'interface': '127.0.0.1', 'publish_port': 4505, 'zmq_backlog': 1000, 'pub_hwm': 1000, 'auth_mode': 1, 'user': 'root', 'worker_threads': 5, 'sock_dir': '/var/run/salt/master', 'sock_pool_size': 1, 'ret_port': 4506, 'timeout': 5, 'keep_jobs': 24, 'archive_jobs': False, 'root_dir': '/', 'pki_dir': '/etc/salt/pki/master', 'key_cache': '', 'cachedir': '/var/cache/salt/master', 'file_roots': {'base': ['/srv/salt/base', '/srv/salt/prod'], 'prod': ['/srv/salt/prod']}, 'master_roots': {'base': ['/srv/salt-master']}, 'pillar_roots': {'base': ['/srv/pillar/base'], 'prod': ['/srv/pillar/prod']}, 'on_demand_ext_pillar': ['libvirt', 'virtkey'], 'decrypt_pillar': [], 'decrypt_pillar_delimiter': ':', 'decrypt_pillar_default': 'gpg', 'decrypt_pillar_renderers': ['gpg'], 'thoriumenv': None, 'thorium_top': 'top.sls', 'thorium_interval': 0.5, 'thorium_roots': {'base': ['/srv/thorium']}, 'top_file_merging_strategy': 'merge', 'env_order': [], 'saltenv': None, 'lock_saltenv': False, 'pillarenv': None, 'default_top': 'base', 'file_client': 'local', 'local': True, 'roots_update_interval': 60, 'azurefs_update_interval': 60, 'gitfs_update_interval': 60, 'git_pillar_update_interval': 60, 'hgfs_update_interval': 60, 'minionfs_update_interval': 60, 's3fs_update_interval': 60, 'svnfs_update_interval': 60, 'git_pillar_base': 'master', 'git_pillar_branch': 'master', 'git_pillar_env': '', 'git_pillar_fallback': '', 'git_pillar_root': '', 'git_pillar_ssl_verify': True, 'git_pillar_global_lock': True, 'git_pillar_user': '', 'git_pillar_password': '', 'git_pillar_insecure_auth': False, 'git_pillar_privkey': '', 'git_pillar_pubkey': '', 'git_pillar_passphrase': '', 'git_pillar_refspecs': ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*'], 'git_pillar_includes': True, 'git_pillar_verify_config': True, 'gitfs_remotes': [], 'gitfs_mountpoint': '', 'gitfs_root': '', 'gitfs_base': 'master', 'gitfs_fallback': '', 'gitfs_user': '', 'gitfs_password': '', 'gitfs_insecure_auth': False, 'gitfs_privkey': '', 'gitfs_pubkey': '', 'gitfs_passphrase': '', 'gitfs_saltenv_whitelist': [], 'gitfs_saltenv_blacklist': [], 'gitfs_global_lock': True, 'gitfs_ssl_verify': True, 'gitfs_saltenv': [], 'gitfs_ref_types': ['branch', 'tag', 'sha'], 'gitfs_refspecs': ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*'], 'gitfs_disable_saltenv_mapping': False, 'hgfs_remotes': [], 'hgfs_mountpoint': '', 'hgfs_root': '', 'hgfs_base': 'default', 'hgfs_branch_method': 'branches', 'hgfs_saltenv_whitelist': [], 'hgfs_saltenv_blacklist': [], 'show_timeout': True, 'show_jid': False, 'unique_jid': False, 'svnfs_remotes': [], 'svnfs_mountpoint': '', 'svnfs_root': '', 'svnfs_trunk': 'trunk', 'svnfs_branches': 'branches', 'svnfs_tags': 'tags', 'svnfs_saltenv_whitelist': [], 'svnfs_saltenv_blacklist': [], 'max_event_size': 1048576, 'master_stats': False, 'master_stats_event_iter': 60, 'minionfs_env': 'base', 'minionfs_mountpoint': '', 'minionfs_whitelist': [], 'minionfs_blacklist': [], 'ext_pillar': [], 'pillar_version': 2, 'pillar_opts': False, 'pillar_safe_render_error': True, 'pillar_source_merging_strategy': 'smart', 'pillar_merge_lists': False, 'pillar_includes_override_sls': False, 'pillar_cache': False, 'pillar_cache_ttl': 3600, 'pillar_cache_backend': 'disk', 'gpg_cache': False, 'gpg_cache_ttl': 86400, 'gpg_cache_backend': 'disk', 'ping_on_rotate': False, 'peer': {}, 'preserve_minion_cache': False, 'syndic_master': 'masterofmasters', 'syndic_failover': 'random', 'syndic_forward_all_events': False, 'syndic_log_file': '/var/log/salt/syndic', 'syndic_pidfile': '/var/run/salt-syndic.pid', 'outputter_dirs': [], 'runner_dirs': [], 'utils_dirs': ['/var/cache/salt/master/extmods/utils'], 'client_acl_verify': True, 'publisher_acl': {}, 'publisher_acl_blacklist': {}, 'sudo_acl': False, 'external_auth': {}, 'token_expire': 43200, 'token_expire_user_override': False, 'permissive_acl': False, 'keep_acl_in_token': False, 'eauth_acl_module': '', 'eauth_tokens': 'localfs', 'extension_modules': '/var/cache/salt/master/extmods', 'module_dirs': [], 'file_recv': False, 'file_recv_max_size': 100, 'file_buffer_size': 1048576, 'file_ignore_regex': [], 'file_ignore_glob': [], 'fileserver_backend': ['roots'], 'fileserver_followsymlinks': True, 'fileserver_ignoresymlinks': False, 'fileserver_limit_traversal': False, 'fileserver_verify_config': True, 'max_open_files': 100000, 'hash_type': 'sha256', 'optimization_order': [0, 1, 2], 'conf_file': '/etc/salt/master', 'open_mode': False, 'auto_accept': False, 'renderer': 'jinja|yaml', 'renderer_whitelist': [], 'renderer_blacklist': [], 'failhard': False, 'state_top': 'top.sls', 'state_top_saltenv': None, 'master_tops': {}, 'master_tops_first': False, 'order_masters': False, 'job_cache': True, 'ext_job_cache': '', 'master_job_cache': 'local_cache', 'job_cache_store_endtime': False, 'minion_data_cache': True, 'enforce_mine_cache': False, 'ipc_mode': 'ipc', 'ipc_write_buffer': 0, 'req_server_niceness': None, 'pub_server_niceness': None, 'fileserver_update_niceness': None, 'mworker_niceness': None, 'mworker_queue_niceness': None, 'maintenance_niceness': None, 'event_return_niceness': None, 'event_publisher_niceness': None, 'reactor_niceness': None, 'ipv6': None, 'tcp_master_pub_port': 4512, 'tcp_master_pull_port': 4513, 'tcp_master_publish_pull': 4514, 'tcp_master_workers': 4515, 'log_file': '/var/log/salt/master', 'log_level': 'warning', 'log_level_logfile': None, 'log_datefmt': '%H:%M:%S', 'log_datefmt_logfile': '%Y-%m-%d %H:%M:%S', 'log_fmt_console': '[%(levelname)-8s] %(message)s', 'log_fmt_logfile': '%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s', 'log_fmt_jid': '[JID: %(jid)s]', 'log_granular_levels': {}, 'log_rotate_max_bytes': 0, 'log_rotate_backup_count': 0, 'pidfile': '/var/run/salt-master.pid', 'publish_session': 86400, 'range_server': 'range:80', 'reactor': [{'salt/test': ['/srv/reactor/test.sls']}, {'salt/minion/Minion/restart': ['/srv/reactor/auto.sls']}], 'reactor_refresh_interval': 60, 'reactor_worker_threads': 10, 'reactor_worker_hwm': 10000, 'engines': [], 'event_return': '', 'event_return_queue': 0, 'event_return_whitelist': [], 'event_return_blacklist': [], 'event_match_type': 'startswith', 'runner_returns': True, 'serial': 'msgpack', 'test': False, 'state_verbose': True, 'state_output': 'full', 'state_output_diff': False, 'state_output_profile': True, 'state_auto_order': True, 'state_events': False, 'state_aggregate': False, 'search': '', 'loop_interval': 60, 'nodegroups': {'mcwgroup1': 'L@mcw01,mcw03 or vm2.cluster.com', 'mcwgroup2': 'G@myname:mcw and L@mcw01,mcw03', 'mcwgroup3': 'G@myname:mcw and N@mcwgroup1', 'mcwgroup4': ['G@myname:mcw', 'or', 'G@myname:xiaoma']}, 'ssh_list_nodegroups': {}, 'ssh_use_home_key': False, 'cython_enable': False, 'enable_gpu_grains': False, 'key_logfile': '/var/log/salt/key', 'verify_env': True, 'permissive_pki_access': False, 'key_pass': None, 'signing_key_pass': None, 'default_include': 'master.d/*.conf', 'winrepo_dir': '/srv/salt/win/repo', 'winrepo_dir_ng': '/srv/salt/win/repo-ng', 'winrepo_cachefile': 'winrepo.p', 'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'], 'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'], 'winrepo_branch': 'master', 'winrepo_fallback': '', 'winrepo_ssl_verify': True, 'winrepo_user': '', 'winrepo_password': '', 'winrepo_insecure_auth': False, 'winrepo_privkey': '', 'winrepo_pubkey': '', 'winrepo_passphrase': '', 'winrepo_refspecs': ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*'], 'syndic_wait': 5, 'jinja_env': {}, 'jinja_sls_env': {}, 'jinja_lstrip_blocks': False, 'jinja_trim_blocks': False, 'tcp_keepalive': True, 'tcp_keepalive_idle': 300, 'tcp_keepalive_cnt': -1, 'tcp_keepalive_intvl': -1, 'sign_pub_messages': True, 'keysize': 2048, 'transport': 'zeromq', 'gather_job_timeout': 10, 'syndic_event_forward_timeout': 0.5, 'syndic_jid_forward_cache_hwm': 100, 'regen_thin': False, 'ssh_passwd': '', 'ssh_priv_passwd': '', 'ssh_port': '22', 'ssh_sudo': False, 'ssh_sudo_user': '', 'ssh_timeout': 60, 'ssh_user': 'root', 'ssh_scan_ports': '22', 'ssh_scan_timeout': 0.01, 'ssh_identities_only': False, 'ssh_log_file': '/var/log/salt/ssh', 'ssh_config_file': '/root/.ssh/config', 'cluster_mode': False, 'sqlite_queue_dir': '/var/cache/salt/master/queues', 'queue_dirs': [], 'cli_summary': False, 'max_minions': 0, 'master_sign_key_name': 'master_sign', 'master_sign_pubkey': False, 'master_pubkey_signature': 'master_pubkey_signature', 'master_use_pubkey_signature': False, 'zmq_filtering': False, 'zmq_monitor': False, 'con_cache': False, 'rotate_aes_key': True, 'cache_sreqs': True, 'dummy_pub': False, 'http_connect_timeout': 20.0, 'http_request_timeout': 3600.0, 'http_max_body': 107374182400, 'cache': 'localfs', 'memcache_expire_seconds': 0, 'memcache_max_items': 1024, 'memcache_full_cleanup': False, 'memcache_debug': False, 'thin_extra_mods': '', 'min_extra_mods': '', 'ssl': None, 'extmod_whitelist': {}, 'extmod_blacklist': {}, 'clean_dynamic_modules': True, 'django_auth_path': '', 'django_auth_settings': '', 'allow_minion_key_revoke': True, 'salt_cp_chunk_size': 98304, 'require_minion_sign_messages': False, 'drop_messages_signature_fail': False, 'discovery': False, 'schedule': {}, 'auth_events': True, 'minion_data_cache_events': True, 'enable_ssh_minions': False, 'netapi_allow_raw_shell': False, 'fips_mode': False, 'detect_remote_minions': False, 'remote_minions_port': 22, '__role': 'master', '__cli': '', 'token_dir': '/var/cache/salt/master/tokens', 'syndic_dir': '/var/cache/salt/master/syndics', 'id': 'mcw01_master', 'master_uri': 'tcp://127.0.0.1:4506'}
>>> 

或者minion的配置信息

[root@mcw01 ~]# python3
Python 3.6.8 (default, Nov 14 2023, 16:29:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.client
>>> minion_opts=salt.config.minion_config('/etc/salt/minion')
>>> dir(minion_opts)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> 
>>> type(minion_opts)
<class 'dict'>
>>> minion_opts.keys()
dict_keys(['interface', 'master', 'master_type', 'master_uri_format', 'source_interface_name', 'source_address', 'source_ret_port', 'source_publish_port', 'master_port', 'master_finger', 'master_shuffle', 'master_alive_interval', 'master_failback', 'master_failback_interval', 'verify_master_pubkey_sign', 'sign_pub_messages', 'always_verify_signature', 'master_sign_key_name', 'syndic_finger', 'user', 'root_dir', 'pki_dir', 'id', 'id_function', 'cachedir', 'append_minionid_config_dirs', 'cache_jobs', 'grains_blacklist', 'grains_cache', 'grains_cache_expiration', 'grains_deep_merge', 'conf_file', 'sock_dir', 'sock_pool_size', 'backup_mode', 'renderer', 'renderer_whitelist', 'renderer_blacklist', 'random_startup_delay', 'failhard', 'autoload_dynamic_modules', 'saltenv', 'lock_saltenv', 'pillarenv', 'pillarenv_from_saltenv', 'pillar_opts', 'pillar_source_merging_strategy', 'pillar_merge_lists', 'pillar_includes_override_sls', 'pillar_cache', 'pillar_cache_ttl', 'pillar_cache_backend', 'gpg_cache', 'gpg_cache_ttl', 'gpg_cache_backend', 'extension_modules', 'state_top', 'state_top_saltenv', 'startup_states', 'sls_list', 'start_event_grains', 'top_file', 'thoriumenv', 'thorium_top', 'thorium_interval', 'thorium_roots', 'file_client', 'local', 'use_master_when_local', 'file_roots', 'top_file_merging_strategy', 'env_order', 'default_top', 'fileserver_limit_traversal', 'file_recv', 'file_recv_max_size', 'file_ignore_regex', 'file_ignore_glob', 'fileserver_backend', 'fileserver_followsymlinks', 'fileserver_ignoresymlinks', 'pillar_roots', 'on_demand_ext_pillar', 'decrypt_pillar', 'decrypt_pillar_delimiter', 'decrypt_pillar_default', 'decrypt_pillar_renderers', 'roots_update_interval', 'azurefs_update_interval', 'gitfs_update_interval', 'git_pillar_update_interval', 'hgfs_update_interval', 'minionfs_update_interval', 's3fs_update_interval', 'svnfs_update_interval', 'git_pillar_base', 'git_pillar_branch', 'git_pillar_env', 'git_pillar_fallback', 'git_pillar_root', 'git_pillar_ssl_verify', 'git_pillar_global_lock', 'git_pillar_user', 'git_pillar_password', 'git_pillar_insecure_auth', 'git_pillar_privkey', 'git_pillar_pubkey', 'git_pillar_passphrase', 'git_pillar_refspecs', 'git_pillar_includes', 'gitfs_remotes', 'gitfs_mountpoint', 'gitfs_root', 'gitfs_base', 'gitfs_fallback', 'gitfs_user', 'gitfs_password', 'gitfs_insecure_auth', 'gitfs_privkey', 'gitfs_pubkey', 'gitfs_passphrase', 'gitfs_saltenv_whitelist', 'gitfs_saltenv_blacklist', 'gitfs_global_lock', 'gitfs_ssl_verify', 'gitfs_saltenv', 'gitfs_ref_types', 'gitfs_refspecs', 'gitfs_disable_saltenv_mapping', 'unique_jid', 'hash_type', 'optimization_order', 'disable_modules', 'disable_returners', 'whitelist_modules', 'module_dirs', 'returner_dirs', 'grains_dirs', 'states_dirs', 'render_dirs', 'outputter_dirs', 'utils_dirs', 'publisher_acl', 'publisher_acl_blacklist', 'providers', 'clean_dynamic_modules', 'open_mode', 'auto_accept', 'autosign_timeout', 'multiprocessing', 'process_count_max', 'mine_enabled', 'mine_return_job', 'mine_interval', 'ipc_mode', 'ipc_write_buffer', 'ipv6', 'file_buffer_size', 'tcp_pub_port', 'tcp_pull_port', 'tcp_authentication_retries', 'tcp_reconnect_backoff', 'log_file', 'log_level', 'log_level_logfile', 'log_datefmt', 'log_datefmt_logfile', 'log_fmt_console', 'log_fmt_logfile', 'log_fmt_jid', 'log_granular_levels', 'log_rotate_max_bytes', 'log_rotate_backup_count', 'max_event_size', 'enable_legacy_startup_events', 'test', 'ext_job_cache', 'cython_enable', 'enable_fqdns_grains', 'enable_gpu_grains', 'enable_zip_modules', 'state_verbose', 'state_output', 'state_output_diff', 'state_output_profile', 'state_auto_order', 'state_events', 'state_aggregate', 'snapper_states', 'snapper_states_config', 'acceptance_wait_time', 'acceptance_wait_time_max', 'rejected_retry', 'loop_interval', 'verify_env', 'grains', 'permissive_pki_access', 'default_include', 'update_url', 'update_restart_services', 'retry_dns', 'retry_dns_count', 'resolve_dns_fallback', 'recon_max', 'recon_default', 'recon_randomize', 'return_retry_timer', 'return_retry_timer_max', 'return_retry_tries', 'random_reauth_delay', 'winrepo_source_dir', 'winrepo_dir', 'winrepo_dir_ng', 'winrepo_cachefile', 'winrepo_cache_expire_max', 'winrepo_cache_expire_min', 'winrepo_remotes', 'winrepo_remotes_ng', 'winrepo_branch', 'winrepo_fallback', 'winrepo_ssl_verify', 'winrepo_user', 'winrepo_password', 'winrepo_insecure_auth', 'winrepo_privkey', 'winrepo_pubkey', 'winrepo_passphrase', 'winrepo_refspecs', 'pidfile', 'range_server', 'reactor_refresh_interval', 'reactor_worker_threads', 'reactor_worker_hwm', 'engines', 'tcp_keepalive', 'tcp_keepalive_idle', 'tcp_keepalive_cnt', 'tcp_keepalive_intvl', 'modules_max_memory', 'grains_refresh_every', 'minion_id_caching', 'minion_id_lowercase', 'minion_id_remove_domain', 'keysize', 'transport', 'auth_timeout', 'auth_tries', 'master_tries', 'master_tops_first', 'auth_safemode', 'random_master', 'cluster_mode', 'restart_on_error', 'ping_interval', 'username', 'password', 'zmq_filtering', 'zmq_monitor', 'cache_sreqs', 'cmd_safe', 'sudo_user', 'http_connect_timeout', 'http_request_timeout', 'http_max_body', 'event_match_type', 'minion_restart_command', 'pub_ret', 'proxy_host', 'proxy_username', 'proxy_password', 'proxy_port', 'minion_jid_queue_hwm', 'ssl', 'multifunc_ordered', 'beacons_before_connect', 'scheduler_before_connect', 'cache', 'salt_cp_chunk_size', 'extmod_whitelist', 'extmod_blacklist', 'minion_sign_messages', 'discovery', 'schedule', 'ssh_merge_pillar', 'disabled_requisites', 'reactor_niceness', 'fips_mode', '__role', '__cli', 'beacons'])
>>> 
>>> print(minion_opts['user'])
root
>>> print(minion_opts['interface'])
0.0.0.0
>>> print(minion_opts['master'])
['10.0.0.11']
>>> 

 

python api的其它模塊

1、LocalClient

>>> import salt.client
>>> local=salt.client.LocalClient()
>>> local.cmd('*','cmd.run',['hostname'])
{'mcw01': 'mcw01', 'mcw03': 'mcw03', 'mcw02': 'mcw02', 'mcw04': 'mcw04'}
>>> 

支持一次執行多個模塊。沒有參數的,寫個空列表

>>> local.cmd('mcw03',['test.ping','cmd.run','test.echo'],[[],['hostname'],['machangwei']])
{'mcw03': {'test.ping': True, 'cmd.run': 'mcw03', 'test.echo': 'machangwei'}}
>>> 

==》異步執行

>>> import salt.client
>>> local=salt.client.LocalClient()
>>> 
>>> local.cmd_async('*','test.sleep',[30])
'20240127075219835882'
>>> 

==》批量執行

>>> import salt.client
>>> local=salt.client.LocalClient()
>>> returns=local.cmd_batch('*','state.highstate',bat='10%')
>>> for ret in returns:
...   print(ret)
... 
{'mcw03': {'pkg_|-pkg-init_|-gcc_|-installed': {'name': 'gcc', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 0, 'start_time': '15:58:27.724974', 'duration': 841.383, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-gcc-c++_|-installed': {'name': 'gcc-c++', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 1, 'start_time': '15:58:28.566603', 'duration': 17.593, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-glibc_|-installed': {'name': 'glibc', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 2, 'start_time': '15:58:28.584326', 'duration': 16.184, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-make_|-installed': {'name': 'make', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 3, 'start_time': '15:58:28.600626', 'duration': 16.191, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-autoconf_|-installed': {'name': 'autoconf', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 4, 'start_time': '15:58:28.616949', 'duration': 24.624, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-openssl_|-installed': {'name': 'openssl', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 5, 'start_time': '15:58:28.641768', 'duration': 20.258, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-openssl-devel_|-installed': {'name': 'openssl-devel', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 6, 'start_time': '15:58:28.662184', 'duration': 18.041, '__id__': 'pkg-init'}, 'file_|-haproxy-install_|-/usr/local/src/haproxy-1.5.19.tar.gz_|-managed': {'changes': {}, 'comment': 'File /usr/local/src/haproxy-1.5.19.tar.gz is in the correct state', 'name': '/usr/local/src/haproxy-1.5.19.tar.gz', 'result': True, '__sls__': 'haproxy.install', '__run_num__': 7, 'start_time': '15:58:28.682118', 'duration': 20.305, '__id__': 'haproxy-install'}, 'cmd_|-haproxy-install_|-cd /usr/local/src && tar zxf haproxy-1.5.19.tar.gz && cd haproxy-1.5.19 && make TARGET=linux26 PREFIX=/usr/local/haproxy && make install PREFIX=/usr/local/haproxy_|-run': {'result': True, 'name': 'cd /usr/local/src && tar zxf haproxy-1.5.19.tar.gz && cd haproxy-1.5.19 && make TARGET=linux26 PREFIX=/usr/local/haproxy && make install PREFIX=/usr/local/haproxy', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'haproxy.install', '__run_num__': 8, 'start_time': '15:58:28.703541', 'duration': 396.225, '__id__': 'haproxy-install'}, 'file_|-/etc/init.d/haproxy_|-/etc/init.d/haproxy_|-managed': {'changes': {}, 'comment': 'File /etc/init.d/haproxy is in the correct state', 'name': '/etc/init.d/haproxy', 'result': True, '__sls__': 'haproxy.install', '__run_num__': 9, 'start_time': '15:58:29.100144', 'duration': 8.864, '__id__': '/etc/init.d/haproxy'}, 'sysctl_|-net.ipv4.ip_nonlocal_bind_|-net.ipv4.ip_nonlocal_bind_|-present': {'name': 'net.ipv4.ip_nonlocal_bind', 'result': True, 'changes': {}, 'comment': 'Sysctl value net.ipv4.ip_nonlocal_bind = 1 is already set', '__sls__': 'haproxy.install', '__run_num__': 10, 'start_time': '15:58:29.109154', 'duration': 8.07, '__id__': 'net.ipv4.ip_nonlocal_bind'}, 'file_|-haproxy-config-dir_|-/etc/haproxy_|-directory': {'name': '/etc/haproxy', 'changes': {}, 'result': True, 'comment': 'The directory /etc/haproxy is in the correct state', '__sls__': 'haproxy.install', '__run_num__': 11, 'start_time': '15:58:29.117415', 'duration': 1.395, '__id__': 'haproxy-config-dir'}, 'cmd_|-haproxy-init_|-chkconfig --add haproxy_|-run': {'result': True, 'name': 'chkconfig --add haproxy', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'haproxy.install', '__run_num__': 12, 'start_time': '15:58:29.119162', 'duration': 11.559, '__id__': 'haproxy-init'}, 'file_|-haproxy_|-/usr/sbin/haproxy_|-managed': {'changes': {}, 'comment': 'File /usr/sbin/haproxy is in the correct state', 'name': '/usr/sbin/haproxy', 'result': True, '__sls__': 'cluster.haproxy-outside', '__run_num__': 13, 'start_time': '15:58:29.131044', 'duration': 16.615, '__id__': 'haproxy'}, 'file_|-haproxy-service_|-/etc/haproxy/haproxy.cfg_|-managed': {'changes': {}, 'comment': 'File /etc/haproxy/haproxy.cfg is in the correct state', 'name': '/etc/haproxy/haproxy.cfg', 'result': True, '__sls__': 'cluster.haproxy-outside', '__run_num__': 14, 'start_time': '15:58:29.147806', 'duration': 83.787, '__id__': 'haproxy-service'}, 'service_|-haproxy-service_|-haproxy_|-running': {'name': 'haproxy', 'changes': {}, 'result': True, 'comment': 'The service haproxy is already running', '__sls__': 'cluster.haproxy-outside', '__run_num__': 15, 'start_time': '15:58:29.232297', 'duration': 15.391, '__id__': 'haproxy-service'}, 'file_|-keepalived-install_|-/usr/local/src/keepalived-1.2.17.tar.gz_|-managed': {'changes': {}, 'comment': 'File /usr/local/src/keepalived-1.2.17.tar.gz is in the correct state', 'name': '/usr/local/src/keepalived-1.2.17.tar.gz', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 16, 'start_time': '15:58:29.247870', 'duration': 154.7, '__id__': 'keepalived-install'}, 'cmd_|-keepalived-install_|-cd /usr/local/src && tar zxf keepalived-1.2.17.tar.gz && cd keepalived-1.2.17 && ./configure --prefix=/user/local/keepalived --disable-fwmark && make && make install_|-run': {'result': True, 'name': 'cd /usr/local/src && tar zxf keepalived-1.2.17.tar.gz && cd keepalived-1.2.17 && ./configure --prefix=/user/local/keepalived --disable-fwmark && make && make install', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'keepalived.install', '__run_num__': 17, 'start_time': '15:58:29.403010', 'duration': 11.247, '__id__': 'keepalived-install'}, 'file_|-/etc/sysconfig/keepalived_|-/etc/sysconfig/keepalived_|-managed': {'changes': {}, 'comment': 'File /etc/sysconfig/keepalived is in the correct state', 'name': '/etc/sysconfig/keepalived', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 18, 'start_time': '15:58:29.414475', 'duration': 10.089, '__id__': '/etc/sysconfig/keepalived'}, 'file_|-/etc/init.d/keepalived_|-/etc/init.d/keepalived_|-managed': {'changes': {}, 'comment': 'File /etc/init.d/keepalived is in the correct state', 'name': '/etc/init.d/keepalived', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 19, 'start_time': '15:58:29.424698', 'duration': 23.094, '__id__': '/etc/init.d/keepalived'}, 'file_|-xiaoma_|-/usr/local/keepalived/sbin/_|-directory': {'name': '/usr/local/keepalived/sbin/', 'changes': {}, 'result': True, 'comment': 'The directory /usr/local/keepalived/sbin is in the correct state', '__sls__': 'keepalived.install', '__run_num__': 20, 'start_time': '15:58:29.447976', 'duration': 1.113, '__id__': 'xiaoma'}, 'file_|-/usr/local/keepalived/sbin/keepalived_|-/usr/local/keepalived/sbin/keepalived_|-managed': {'changes': {}, 'comment': 'File /usr/local/keepalived/sbin/keepalived is in the correct state', 'name': '/usr/local/keepalived/sbin/keepalived', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 21, 'start_time': '15:58:29.449181', 'duration': 10.979, '__id__': '/usr/local/keepalived/sbin/keepalived'}, 'cmd_|-keepalived-init_|-chkconfig --add keepalived_|-run': {'result': True, 'name': 'chkconfig --add keepalived', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'keepalived.install', '__run_num__': 22, 'start_time': '15:58:29.460813', 'duration': 12.972, '__id__': 'keepalived-init'}, 'file_|-/etc/keepalived_|-/etc/keepalived_|-directory': {'name': '/etc/keepalived', 'changes': {}, 'result': True, 'comment': 'The directory /etc/keepalived is in the correct state', '__sls__': 'keepalived.install', '__run_num__': 23, 'start_time': '15:58:29.474007', 'duration': 1.498, '__id__': '/etc/keepalived'}, 'file_|-keepalived-server_|-/etc/keepalived/keepalived.conf_|-managed': {'changes': {}, 'comment': 'File /etc/keepalived/keepalived.conf is in the correct state', 'name': '/etc/keepalived/keepalived.conf', 'result': True, '__sls__': 'cluster.haproxy-outside-keepalived', '__run_num__': 24, 'start_time': '15:58:29.475626', 'duration': 11.162, '__id__': 'keepalived-server'}, 'service_|-keepalived-server_|-keepalived_|-running': {'name': 'keepalived', 'changes': {}, 'result': True, 'comment': 'The service keepalived is already running', '__sls__': 'cluster.haproxy-outside-keepalived', '__run_num__': 25, 'start_time': '15:58:29.487214', 'duration': 13.212, '__id__': 'keepalived-server'}, 'retcode': 0}}
{'mcw02': {'no_|-states_|-states_|-None': {'result': False, 'comment': 'No Top file or master_tops data matches found. Please see master log for details.', 'name': 'No States', 'changes': {}, '__run_num__': 0}, 'retcode': 2}}
{'mcw01': {'pkg_|-pkg-init_|-gcc_|-installed': {'name': 'gcc', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 0, 'start_time': '15:58:36.366094', 'duration': 4993.571, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-gcc-c++_|-installed': {'name': 'gcc-c++', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 1, 'start_time': '15:58:41.359878', 'duration': 17.8, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-glibc_|-installed': {'name': 'glibc', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 2, 'start_time': '15:58:41.377812', 'duration': 16.326, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-make_|-installed': {'name': 'make', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 3, 'start_time': '15:58:41.394249', 'duration': 18.175, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-autoconf_|-installed': {'name': 'autoconf', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 4, 'start_time': '15:58:41.412547', 'duration': 17.6, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-openssl_|-installed': {'name': 'openssl', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 5, 'start_time': '15:58:41.430283', 'duration': 18.768, '__id__': 'pkg-init'}, 'pkg_|-pkg-init_|-openssl-devel_|-installed': {'name': 'openssl-devel', 'changes': {}, 'result': True, 'comment': 'All specified packages are already installed', '__sls__': 'pkg.pkg-init', '__run_num__': 6, 'start_time': '15:58:41.449192', 'duration': 18.149, '__id__': 'pkg-init'}, 'file_|-haproxy-install_|-/usr/local/src/haproxy-1.5.19.tar.gz_|-managed': {'changes': {}, 'comment': 'File /usr/local/src/haproxy-1.5.19.tar.gz is in the correct state', 'name': '/usr/local/src/haproxy-1.5.19.tar.gz', 'result': True, '__sls__': 'haproxy.install', '__run_num__': 7, 'start_time': '15:58:41.484149', 'duration': 107.869, '__id__': 'haproxy-install'}, 'cmd_|-haproxy-install_|-cd /usr/local/src && tar zxf haproxy-1.5.19.tar.gz && cd haproxy-1.5.19 && make TARGET=linux26 PREFIX=/usr/local/haproxy && make install PREFIX=/usr/local/haproxy_|-run': {'result': True, 'name': 'cd /usr/local/src && tar zxf haproxy-1.5.19.tar.gz && cd haproxy-1.5.19 && make TARGET=linux26 PREFIX=/usr/local/haproxy && make install PREFIX=/usr/local/haproxy', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'haproxy.install', '__run_num__': 8, 'start_time': '15:58:41.593702', 'duration': 647.081, '__id__': 'haproxy-install'}, 'file_|-/etc/init.d/haproxy_|-/etc/init.d/haproxy_|-managed': {'changes': {}, 'comment': 'File /etc/init.d/haproxy is in the correct state', 'name': '/etc/init.d/haproxy', 'result': True, '__sls__': 'haproxy.install', '__run_num__': 9, 'start_time': '15:58:42.241102', 'duration': 13.378, '__id__': '/etc/init.d/haproxy'}, 'sysctl_|-net.ipv4.ip_nonlocal_bind_|-net.ipv4.ip_nonlocal_bind_|-present': {'name': 'net.ipv4.ip_nonlocal_bind', 'result': True, 'changes': {}, 'comment': 'Sysctl value net.ipv4.ip_nonlocal_bind = 1 is already set', '__sls__': 'haproxy.install', '__run_num__': 10, 'start_time': '15:58:42.254647', 'duration': 22.134, '__id__': 'net.ipv4.ip_nonlocal_bind'}, 'file_|-haproxy-config-dir_|-/etc/haproxy_|-directory': {'name': '/etc/haproxy', 'changes': {}, 'result': True, 'comment': 'The directory /etc/haproxy is in the correct state', '__sls__': 'haproxy.install', '__run_num__': 11, 'start_time': '15:58:42.277144', 'duration': 2.16, '__id__': 'haproxy-config-dir'}, 'cmd_|-haproxy-init_|-chkconfig --add haproxy_|-run': {'result': True, 'name': 'chkconfig --add haproxy', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'haproxy.install', '__run_num__': 12, 'start_time': '15:58:42.279790', 'duration': 47.565, '__id__': 'haproxy-init'}, 'file_|-haproxy_|-/usr/sbin/haproxy_|-managed': {'changes': {}, 'comment': 'File /usr/sbin/haproxy is in the correct state', 'name': '/usr/sbin/haproxy', 'result': True, '__sls__': 'cluster.haproxy-outside', '__run_num__': 13, 'start_time': '15:58:42.327623', 'duration': 77.964, '__id__': 'haproxy'}, 'file_|-haproxy-service_|-/etc/haproxy/haproxy.cfg_|-managed': {'changes': {}, 'comment': 'File /etc/haproxy/haproxy.cfg is in the correct state', 'name': '/etc/haproxy/haproxy.cfg', 'result': True, '__sls__': 'cluster.haproxy-outside', '__run_num__': 14, 'start_time': '15:58:42.405756', 'duration': 26.32, '__id__': 'haproxy-service'}, 'service_|-haproxy-service_|-haproxy_|-running': {'name': 'haproxy', 'changes': {}, 'result': True, 'comment': 'The service haproxy is already running', '__sls__': 'cluster.haproxy-outside', '__run_num__': 15, 'start_time': '15:58:42.432775', 'duration': 63.086, '__id__': 'haproxy-service'}, 'file_|-keepalived-install_|-/usr/local/src/keepalived-1.2.17.tar.gz_|-managed': {'changes': {}, 'comment': 'File /usr/local/src/keepalived-1.2.17.tar.gz is in the correct state', 'name': '/usr/local/src/keepalived-1.2.17.tar.gz', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 16, 'start_time': '15:58:42.496054', 'duration': 36.791, '__id__': 'keepalived-install'}, 'cmd_|-keepalived-install_|-cd /usr/local/src && tar zxf keepalived-1.2.17.tar.gz && cd keepalived-1.2.17 && ./configure --prefix=/user/local/keepalived --disable-fwmark && make && make install_|-run': {'result': True, 'name': 'cd /usr/local/src && tar zxf keepalived-1.2.17.tar.gz && cd keepalived-1.2.17 && ./configure --prefix=/user/local/keepalived --disable-fwmark && make && make install', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'keepalived.install', '__run_num__': 17, 'start_time': '15:58:42.533378', 'duration': 12.648, '__id__': 'keepalived-install'}, 'file_|-/etc/sysconfig/keepalived_|-/etc/sysconfig/keepalived_|-managed': {'changes': {}, 'comment': 'File /etc/sysconfig/keepalived is in the correct state', 'name': '/etc/sysconfig/keepalived', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 18, 'start_time': '15:58:42.546344', 'duration': 18.967, '__id__': '/etc/sysconfig/keepalived'}, 'file_|-/etc/init.d/keepalived_|-/etc/init.d/keepalived_|-managed': {'changes': {}, 'comment': 'File /etc/init.d/keepalived is in the correct state', 'name': '/etc/init.d/keepalived', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 19, 'start_time': '15:58:42.565465', 'duration': 7.714, '__id__': '/etc/init.d/keepalived'}, 'file_|-xiaoma_|-/usr/local/keepalived/sbin/_|-directory': {'name': '/usr/local/keepalived/sbin/', 'changes': {}, 'result': True, 'comment': 'The directory /usr/local/keepalived/sbin is in the correct state', '__sls__': 'keepalived.install', '__run_num__': 20, 'start_time': '15:58:42.573297', 'duration': 1.14, '__id__': 'xiaoma'}, 'file_|-/usr/local/keepalived/sbin/keepalived_|-/usr/local/keepalived/sbin/keepalived_|-managed': {'changes': {}, 'comment': 'File /usr/local/keepalived/sbin/keepalived is in the correct state', 'name': '/usr/local/keepalived/sbin/keepalived', 'result': True, '__sls__': 'keepalived.install', '__run_num__': 21, 'start_time': '15:58:42.574534', 'duration': 18.528, '__id__': '/usr/local/keepalived/sbin/keepalived'}, 'cmd_|-keepalived-init_|-chkconfig --add keepalived_|-run': {'result': True, 'name': 'chkconfig --add keepalived', 'changes': {}, 'comment': 'unless condition is true', 'skip_watch': True, '__sls__': 'keepalived.install', '__run_num__': 22, 'start_time': '15:58:42.593731', 'duration': 13.178, '__id__': 'keepalived-init'}, 'file_|-/etc/keepalived_|-/etc/keepalived_|-directory': {'name': '/etc/keepalived', 'changes': {}, 'result': True, 'comment': 'The directory /etc/keepalived is in the correct state', '__sls__': 'keepalived.install', '__run_num__': 23, 'start_time': '15:58:42.607105', 'duration': 1.726, '__id__': '/etc/keepalived'}, 'file_|-keepalived-server_|-/etc/keepalived/keepalived.conf_|-managed': {'changes': {}, 'comment': 'File /etc/keepalived/keepalived.conf is in the correct state', 'name': '/etc/keepalived/keepalived.conf', 'result': True, '__sls__': 'cluster.haproxy-outside-keepalived', '__run_num__': 24, 'start_time': '15:58:42.608962', 'duration': 9.11, '__id__': 'keepalived-server'}, 'service_|-keepalived-server_|-keepalived_|-running': {'name': 'keepalived', 'changes': {}, 'result': True, 'comment': 'The service keepalived is already running', '__sls__': 'cluster.haproxy-outside-keepalived', '__run_num__': 25, 'start_time': '15:58:42.618523', 'duration': 19.089, '__id__': 'keepalived-server'}, 'retcode': 0}}
{'mcw04': {'no_|-states_|-states_|-None': {'result': False, 'comment': 'No Top file or master_tops data matches found. Please see master log for details.', 'name': 'No States', 'changes': {}, '__run_num__': 0}, 'retcode': 2}}
>>> 

==》逐個返回結果

>>> import salt.client
>>> local=salt.client.LocalClient()
>>> ret=local.cmd_iter('*','test.ping')
>>> for i in ret:
...   print(i)
... 
{'mcw01': {'ret': True, 'retcode': 0, 'jid': '20240127080133628154'}}
{'mcw03': {'ret': True, 'retcode': 0, 'jid': '20240127080133628154'}}
{'mcw04': {'ret': True, 'retcode': 0, 'jid': '20240127080133628154'}}
{'mcw02': {'ret': True, 'retcode': 0, 'jid': '20240127080133628154'}}
>>> 

==》逐次返回結果,如果沒有結果繼續等待

>>> import salt.client
>>> local=salt.client.LocalClient()
>>> ret=local.cmd_iter_no_block('*','test.ping')
>>> for i in ret:
...   print(i)
... 
None
{'mcw04': {'ret': True, 'retcode': 0, 'jid': '20240127080509099693'}}
{'mcw01': {'ret': True, 'retcode': 0, 'jid': '20240127080509099693'}}
{'mcw03': {'ret': True, 'retcode': 0, 'jid': '20240127080509099693'}}
{'mcw02': {'ret': True, 'retcode': 0, 'jid': '20240127080509099693'}}
>>> 

==》隨機執行

>>> import salt.client
>>> local=salt.client.LocalClient()
>>> local.cmd_subset('*','test.ping',sub=1,progress=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/salt/client/__init__.py", line 557, in cmd_subset
    **kwargs
  File "/usr/lib/python3.6/site-packages/salt/client/__init__.py", line 782, in cmd
    ret[mid] = data if full_return else data.get("ret", {})
AttributeError: 'int' object has no attribute 'get'
>>> 

==》執行命令

>>> import salt.client
>>> local=salt.client.LocalClient()
>>> local.run_job('mcw03','test.ping',[300])
{'jid': '20240127082323390382', 'minions': ['mcw03']}
>>> 

 

2、salt caller

客戶端執行命令salt-call

[root@mcw02 ~]# python3
Python 3.6.8 (default, Nov 14 2023, 16:29:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.client
>>> caller=salt.client.Caller()
>>> caller.cmd('test.ping')
True
>>> caller.function('test.ping')
True
>>> exit()
[root@mcw02 ~]# salt-call test.ping
local:
    True
[root@mcw02 ~]# 

3、RunnerClient 

salt-run的作用,報錯了,回頭再看

[root@mcw01 ~]# python3
Python 3.6.8 (default, Nov 14 2023, 16:29:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.config
>>> opts=salt.config.master_config('/etc/salt/master')
>>> runner=salt.runner.RunnerClient(opts)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'salt' has no attribute 'runner'
>>> runner.cmd('jobs.list_jobs',[])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'runner' is not defined
>>> 

4、wheelclient

一樣,有問題,以後再看看

[root@mcw01 ~]# python3
Python 3.6.8 (default, Nov 14 2023, 16:29:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.config
>>> opts=salt.config.master_config('/etc/salt/master')
>>> wheel=salt.wheel.Wheel(opts)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'salt' has no attribute 'wheel'
>>> wheel.call_func('key.list_all')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'wheel' is not defined
>>> 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章