From: 印象笔记
Date: 2017-10-26
1. ClientAPI 介绍
ClientAPI 官方文档
- # 直接调用多台机器, 用 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 说明
Saltstack 官方 Modules
"""
: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 命令行异步任务
命令行加入参数 --async
- # 发起任务, 返回 job id:JID
- salt -G 'os:windows' --async test.ping
- # 根据 JID 查询任务状态及结果
- salt-run jobs.lookup_jid "$jid" --output=JSON
可以获得先执行完的主机, 未执行完毕的没有结果
5.2 python 中执行异步任务
官方示例
- import salt.client
- local = salt.client.LocalClient()
- local.cmd_async(tgt, fun, kwarg)
查询结果
- 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'}
查询某台主机的执行情况, 会返回状态及 PID
- local.cmd(
- tgt='salt-srvns-01',
- fun='saltutil.find_job',
- kwarg={'jid': '20181102133130044435'}
- )
来源: http://www.bubuko.com/infodetail-3213846.html