From: 印象筆記html
Date: 2017-10-26node
1. ClientAPI介紹
ClientAPI官方文檔python
# 直接調用多臺機器,用list >>> local.cmd(tgt_type='list', tgt=['centos7_161019', 'centos7-170624'], fun='test.ping') {'centos7-170624': False, 'centos7_161019': True} # 經過grains調用含指定信息的機器 >>> local.cmd(tgt_type='grain', tgt='os:Centos', fun='test.ping') {'centos7-170624': False, 'centos7_161019': True} # 調用全部機器 >>> local.cmd(tgt='*', fun='test.ping') {'centos7-170624': False, 'centos7_161019': True}
1.1 tgt_type說明
""" :param tgt_type: The type of ``tgt``. Allowed values: * ``glob`` - Bash glob completion - Default * ``pcre`` - Perl style regular expression * ``list`` - Python list of hosts * ``grain`` - Match based on a grain comparison * ``grain_pcre`` - Grain comparison with a regex * ``pillar`` - Pillar data comparison * ``pillar_pcre`` - Pillar data comparison with a regex * ``nodegroup`` - Match on nodegroup * ``range`` - Use a Range server for matching * ``compound`` - Pass a compound match string * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address. """
1.2 func說明
""" :param fun: The module and function to call on the specified minions of the form ``module.function``. For example ``test.ping`` or ``grains.items``. Compound commands Multiple functions may be called in a single publish by passing a list of commands. This can dramatically lower overhead and speed up the application communicating with Salt. This requires that the ``arg`` param is a list of lists. The ``fun`` list and the ``arg`` list must correlate by index meaning a function that does not take arguments must still have a corresponding empty list at the expected index. :type fun: string or list of strings :param arg: A list of arguments to pass to the remote function. If the function takes no arguments ``arg`` may be omitted except when executing a compound command. :type arg: list or list-of-lists :param kwarg: A dictionary with keyword arguments for the function. :param kwargs: Optional keyword arguments. Authentication credentials may be passed when using :conf_master:`external_auth`. For example: ``local.cmd('*', 'test.ping', username='saltdev', password='saltdev', eauth='pam')``. Or: ``local.cmd('*', 'test.ping', token='5871821ea51754fdcea8153c1c745433')`` """
2. 操做案例
# which方式:返回cmds列表裏第一個找到的值 >>> local.cmd(tgt='centos7_161019', fun='cmd.which_bin', kwarg={'cmds': ['python', 'python2']}) {'centos7_161019': '/usr/bin/python'} # 執行一個普通的date命令 >>> local.cmd(tgt='centos7_161019', fun='cmd.run', kwarg={'cmd': 'date'}) {'centos7_161019': 'Wed Oct 18 11:16:41 CST 2017'} # 查看root用戶的crontab列表 >>> local.cmd(tgt='centos7_161019', fun='cron.ls', kwarg={'user': 'root'}) { "centos7_161019": { "env": [], "crons": [], "special": [], "pre": [ "0 0 * * * /home/work/log.sh", "*/3 * * * * /usr/sbin/ntpdate 1.cn.pool.ntp.org", "*/1 * * * * /home/work/grafana/insert_test_data.sh" ] } } # 跑iostate >>> local.cmd(tgt='centos7_161019', fun='disk.iostat', kwarg={'interval': 1, 'count': 5}) { "centos7_161019": { "sda": { "await": 0.17, "wkB/s": 5.34, "w_await": 0.35, "avgqu-sz": 0.0, "w/s": 0.11, "svctm": 0.11, "%util": 0.04, "r/s": 0.6, "avgrq-sz": 10.71, "wrqm/s": 1.16, "rrqm/s": 0.21, "r_await": 0.14, "rkB/s": 13.67 }, "dm-0": { "await": 0.18, "wkB/s": 0.57, "w_await": 0.41, "avgqu-sz": 0.0, "w/s": 0.08, "svctm": 0.11, "%util": 0.03, "r/s": 0.56, "avgrq-sz": 8.15, "wrqm/s": 0.0, "rrqm/s": 0.0, "r_await": 0.15, "rkB/s": 12.49 }, "dm-1": { "await": 0.36, "wkB/s": 4.7, "w_await": 0.41, "avgqu-sz": 0.0, "w/s": 1.18, "svctm": 0.01, "%util": 0.0, "r/s": 0.25, "avgrq-sz": 1.6, "wrqm/s": 0.0, "rrqm/s": 0.0, "r_await": 0.1, "rkB/s": 1.0 }, "sys": { "%steal": 0.0, "%system": 0.57, "%user": 0.76, "%idle": 98.65, "%iowait": 0.01, "%nice": 0.0 } } } # 校驗服務器文件的哈希值 >>> local.cmd(tgt='centos7_161019', fun='file.check_hash', kwarg={'path': '/tmp/a', 'file_hash': '939916e1974db06f4d4963320a64c55d'}) {'centos7_161019': True} # 修改文件屬性:正確返回None >>> local.cmd(tgt='centos7_161019', fun='file.chown', kwarg={'path': '/tmp/a', 'user': 'nobody', 'group': 'nobody'}) {'centos7_161019': None} # 從本地(salt-master)發送文件a到遠端服務器的send_file_to_server >>> local.cmd(tgt='centos7_161019', fun='file.copy', kwarg={'src': '/tmp/a', 'dst': '/tmp/send_file_to_server'}) {'centos7_161019': True}
3. Windows官方Modules
模塊名稱 | 說明 | 備註 |
---|---|---|
salt.modules.win_autoruns | 列出windows自啓動服務 | |
salt.modules.win_certutil module | 管理cert管理器(https) | |
salt.modules.win_dacl | 管理訪問控制 | |
salt.modules.win_disk | 磁盤信息 | |
salt.modules.win_dism module | 部署映像服務和管理 | |
salt.modules.win_dns_client | 管理dns配置 | |
salt.modules.win_dsc | * | |
salt.modules.win_file | 管理和查看文件屬性 | |
salt.modules.win_firewall | windows防火牆 | |
salt.modules.win_groupadd | 查看和管理用戶羣組 | |
salt.modules.win_iis module | IIS管理 | |
salt.modules.win_ip | windows網卡 | |
salt.modules.win_lgpo | 本地策略(組策略,例如gpedit.msc) | |
salt.modules.win_license module | windows正版序列號 | |
salt.modules.win_network | 網絡信息,網絡連通性 | |
salt.modules.win_ntp | 獲取、設置ntp server | |
salt.modules.win_path | win系統環境變量 | |
salt.modules.win_pkg | 軟件包管理 | 須要windows repo |
salt.modules.win_pki module | 經過pki client管理「證書管理器」 | |
salt.modules.win_powercfg | 電源管理器 | |
salt.modules.win_psget module | 經過psget管理powershell | powershellget |
salt.modules.win_repo | 管理windows software repo | |
salt.modules.win_servermanager | 經過server manager powershell管理服務器 | 服務的安裝包 |
salt.modules.win_service | 管理windows服務 | |
salt.modules.win_shadow | windows帳號管理 | 用戶禁用啓用、改密碼,登錄超時 |
salt.modules.win_smtp_server module | 管理IIS下的smtp服務器 | |
salt.modules.win_snmp module | snmp服務 | |
salt.modules.win_status | 服務器狀態 | cpu,磁盤,進程數,salt內存,uptime |
salt.modules.win_system | 主機管理(基本信息、關機重啓) | 主機名、工做組、域等 |
salt.modules.win_task | Windows Task Scheduler | 計劃任務? |
salt.modules.win_timezone | 時區 | hwclock也在這裏 |
salt.modules.win_update | windows更新 | 廢棄,使用win_wua |
salt.modules.win_useradd | 帳號管理,增刪查、改密碼、功能多 | 功能和依賴都比shadow多不少 |
salt.modules.win_wua | 下載安裝卸載均可 | 最低要2008,沒找到列出已更新 |
4. Windows補丁安裝測試
4.1 完整代碼段
import salt.client import json result = local.cmd(tgt_type='grain', tgt='os_family:Windows', fun='win_wua.download', kwarg={'names': ['KB2911501']}, timeout=999999999) result_str = json.dumps(result, indent=4, ensure_ascii=False) print(result_str)
4.2 windows更新下載測試
# 執行 result = local.cmd(tgt_type='grain', tgt='os_family:Windows', fun='win_wua.download', kwarg={'names': ['KB2911501']}, timeout=999999999) # 結果 { "win7_160130": { "Updates": { "bd4aa95a-8bcb-4061-a2f2-c9ba118d705d": { "AlreadyDownloaded": false, "Result": "Download Succeeded", "Title": "用於 x64 系統的 Windows 7 和 Windows Server 2008 R2 SP1 上的 Microsoft .NET Framework 3.5.1 的安全更新程序 (KB2911501)" } }, "Success": true, "Message": "Download Succeeded" } }
4.3 windows更新安裝測試
# 下載完後安裝,失敗了,錯誤不明 result = local.cmd(tgt_type='grain', tgt='os_family:Windows', fun='win_wua.install', kwarg={'names': ['KB2911501']}, timeout=999999999) # 結果1失敗 { "win7_160130": "ERROR: Unknown Failure: (-2147352567, '發生意外。', (0, None, None, None, 0, -2147012866), None)" } # 再執行一次,結果2成功 # 結果 { "win7_160130": { "Updates": { "bd4aa95a-8bcb-4061-a2f2-c9ba118d705d": { "Result": "Installation Succeeded", "Title": "用於 x64 系統的 Windows 7 和 Windows Server 2008 R2 SP1 上的 Microsoft .NET Framework 3.5.1 的安全更新程序 (KB2911501)", "AlreadyInstalled": false, "RebootBehavior": "Poss Reboot" } }, "Success": true, "NeedsReboot": false, "Message": "Installation Succeeded" } }
5. salt異步方案
5.1 命令行異步任務
命令行加入參數--asyncshell
# 發起任務,返回job id:JID salt -G 'os:windows' --async test.ping # 根據JID查詢任務狀態及結果 salt-run jobs.lookup_jid "$jid" --output=json
能夠得到先執行完的主機,未執行完畢的沒有結果express
5.2 python中執行異步任務
官方示例json
import salt.client local = salt.client.LocalClient() local.cmd_async(tgt, fun, kwarg)
查詢結果windows
In [1]: import salt.runner In [2]: opts = salt.config.master_config('/etc/salt/master') In [3]: runner = salt.runner.RunnerClient(opts) In [4]: a = runner.cmd(fun='jobs.lookup_jid', kwarg={'jid': '20181102114908937128'}) salt-srvns-01: Fri Nov 2 11:49:09 CST 2018 Fri Nov 2 11:49:39 CST 2018 In [5]: a Out[5]: {'salt-srvns-01': 'Fri Nov 2 11:49:09 CST 2018\nFri Nov 2 11:49:39 CST 2018'}
查詢某臺主機的執行狀況,會返回狀態及PIDcentos
local.cmd( tgt='salt-srvns-01', fun='saltutil.find_job', kwarg={'jid': '20181102133130044435'} )