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'} )