centos7.4之saltstack的系列(二)常用模块的使用

一、内置模块

  1、使用salt  ‘minionid’  sys.list_modules查看saltstack内置模块。

- acl
    - aliases
    - alternatives
    - archive
    - artifactory
    - beacons
    - bigip
    - btrfs
    - buildout
    - cloud
    - cmd
    - composer
    - config
    - consul
    - container_resource
    - cp
    - cron
    - cryptdev
    - data
    - defaults
    - devmap
    - disk
    - django
    - dnsmasq
    - dnsutil
    - drbd
    - environ
    - etcd
    - ethtool
    - event
    - extfs
    - file
    - firewalld
    - gem
    - genesis
    - glassfish
    - gnome
    - grafana4
    - grains
    - group
    - hashutil
    - highstate_doc
    - hipchat
    - hosts
    - http
    - incron
    - ini
    - inspector
    - introspect
    - ip
    - ipset
    - iptables
    - jboss7
    - jboss7_cli
    - k8s
    - kernelpkg
    - key
    - keyboard
    - kmod
    - locale
    - locate
    - log
    - logrotate
    - lowpkg
    - mandrill
    - match
    - mattermost
    - mine
    - minion
    - modjk
    - mount
    - msteams
    - nagios_rpc
    - namecheap_domains
    - namecheap_domains_dns
    - namecheap_domains_ns
    - namecheap_ssl
    - namecheap_users
    - network
    - nexus
    - nova
    - nspawn
    - openscap
    - openstack_config
    - opsgenie
    - out
    - pagerduty
    - pagerduty_util
    - pam
    - partition
    - pillar
    - pkg
    - pkg_resource
    - postfix
    - ps
    - publish
    - pushover
    - pyenv
    - random
    - random_org
    - rbenv
    - rest_sample_utils
    - restartcheck
    - ret
    - rvm
    - s3
    - s6
    - salt_proxy
    - saltcheck
    - saltutil
    - schedule
    - scsi
    - sdb
    - seed
    - serverdensity_device
    - service
    - shadow
    - slack
    - slsutil
    - smbios
    - smtp
    - solrcloud
    - sqlite3
    - ssh
    - state
    - status
    - statuspage
    - supervisord
    - sys
    - sysctl
    - sysfs
    - syslog_ng
    - system
    - telegram
    - telemetry
    - temp
    - test
    - timezone
    - tuned
    - udev
    - uptime
    - user
    - vault
    - vbox_guest
    - virtualenv
    - vsphere
    - xfs
    - zenoss
内置模块

  2、知道了有哪些模块还不行,那怎么看每个模块有哪些方法呢?

salt  ‘minionid’   sys.list_functions  模块名称
[root@bogon ~]#  salt 'dasha_ceshi_172.16.5.239' sys.list_functions  cmd
dasha_ceshi_172.16.5.239:
    - cmd.exec_code
    - cmd.exec_code_all
    - cmd.has_exec
    - cmd.powershell
    - cmd.powershell_all
    - cmd.retcode
    - cmd.run
    - cmd.run_all
    - cmd.run_bg
    - cmd.run_chroot
    - cmd.run_stderr
    - cmd.run_stdout
    - cmd.script
    - cmd.script_retcode
    - cmd.shell
    - cmd.shell_info
    - cmd.shells
    - cmd.tty
    - cmd.which
    - cmd.which_bin

  3、知道了模块里面有哪些方法也不行,我能得看他的介绍,如果多个模块中间用逗号隔开。

 salt 'minionid'  sys.doc  模块名称
   1 If an equal sign (``=``) appears in an argument to a Salt command it is
   2     interpreted as a keyword argument in the format ``key=val``. That
   3     processing can be bypassed in order to pass an equal sign through to the
   4     remote shell command by manually specifying the kwarg:
   5 
   6         salt '*' cmd.run cmd='sed -e s/=/:/g'
   7     
   8 
   9 cmd.run_all:
  10 
  11     Execute the passed command and return a dict of return data
  12 
  13     :param str cmd: The command to run. ex: ``ls -lart /home``
  14 
  15     :param str cwd: The directory from which to execute the command. Defaults
  16         to the home directory of the user specified by ``runas`` (or the user
  17         under which Salt is running if ``runas`` is not specified).
  18 
  19     :param str stdin: A string of standard input can be specified for the
  20         command to be run using the ``stdin`` parameter. This can be useful in
  21         cases where sensitive information must be read from standard input.
  22 
  23     :param str runas: Specify an alternate user to run the command. The default
  24         behavior is to run as the user under which Salt is running. If running
  25         on a Windows minion you must also use the ``password`` argument, and
  26         the target user account must be in the Administrators group.
  27 
  28     :param str password: Windows only. Required when specifying ``runas``. This
  29         parameter will be ignored on non-Windows platforms.
  30 
  31         New in version 2016.3.0
  32 
  33     :param str shell: Specify an alternate shell. Defaults to the system's
  34         default shell.
  35 
  36     :param bool python_shell: If False, let python handle the positional
  37         arguments. Set to True to use shell features, such as pipes or
  38         redirection.
  39 
  40     :param dict env: Environment variables to be set prior to execution.
  41 
  42         Note:
  43             When passing environment variables on the CLI, they should be
  44             passed as the string representation of a dictionary.
  45 
  46                 salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
  47 
  48     :param bool clean_env: Attempt to clean out all other shell environment
  49         variables and set only those provided in the 'env' argument to this
  50         function.
  51 
  52     :param str prepend_path: $PATH segment to prepend (trailing ':' not
  53         necessary) to $PATH
  54 
  55         New in version 2018.3.0
  56 
  57     :param str template: If this setting is applied then the named templating
  58         engine will be used to render the downloaded file. Currently jinja,
  59         mako, and wempy are supported.
  60 
  61     :param bool rstrip: Strip all whitespace off the end of output before it is
  62         returned.
  63 
  64     :param str umask: The umask (in octal) to use when running the command.
  65 
  66     :param str output_encoding: Control the encoding used to decode the
  67         command's output.
  68 
  69         Note:
  70             This should not need to be used in most cases. By default, Salt
  71             will try to use the encoding detected from the system locale, and
  72             will fall back to UTF-8 if this fails. This should only need to be
  73             used in cases where the output of the command is encoded in
  74             something other than the system locale or UTF-8.
  75 
  76             To see the encoding Salt has detected from the system locale, check
  77             the `locale` line in the output of :py:func:`test.versions_report
  78             <salt.modules.test.versions_report>`.
  79 
  80         New in version 2018.3.0
  81 
  82     :param str output_loglevel: Control the loglevel at which the output from
  83         the command is logged to the minion log.
  84 
  85         Note:
  86             The command being run will still be logged at the ``debug``
  87             loglevel regardless, unless ``quiet`` is used for this value.
  88 
  89     :param bool ignore_retcode: If the exit code of the command is nonzero,
  90         this is treated as an error condition, and the output from the command
  91         will be logged to the minion log. However, there are some cases where
  92         programs use the return code for signaling and a nonzero exit code
  93         doesn't necessarily mean failure. Pass this argument as ``True`` to
  94         skip logging the output if the command has a nonzero exit code.
  95 
  96     :param bool hide_output: If ``True``, suppress stdout and stderr in the
  97         return data.
  98 
  99         Note:
 100             This is separate from ``output_loglevel``, which only handles how
 101             Salt logs to the minion log.
 102 
 103         New in version 2018.3.0
 104 
 105     :param int timeout: A timeout in seconds for the executed process to
 106         return.
 107 
 108     :param bool use_vt: Use VT utils (saltstack) to stream the command output
 109         more interactively to the console and the logs. This is experimental.
 110 
 111     :param bool encoded_cmd: Specify if the supplied command is encoded.
 112        Only applies to shell 'powershell'.
 113 
 114        New in version 2018.3.0
 115 
 116     :param bool redirect_stderr: If set to ``True``, then stderr will be
 117         redirected to stdout. This is helpful for cases where obtaining both
 118         the retcode and output is desired, but it is not desired to have the
 119         output separated into both stdout and stderr.
 120 
 121         New in version 2015.8.2
 122 
 123     :param str password: Windows only. Required when specifying ``runas``. This
 124         parameter will be ignored on non-Windows platforms.
 125 
 126           New in version 2016.3.0
 127 
 128     :param bool bg: If ``True``, run command in background and do not await or
 129         deliver its results
 130 
 131         New in version 2016.3.6
 132 
 133     CLI Example:
 134 
 135         salt '*' cmd.run_all "ls -l | awk '/foo/{print \$2}'"
 136 
 137     The template arg can be set to 'jinja' or another supported template
 138     engine to render the command arguments before execution.
 139     For example:
 140 
 141         salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \$2}'"
 142 
 143     A string of standard input can be specified for the command to be run using
 144     the ``stdin`` parameter. This can be useful in cases where sensitive
 145     information must be read from standard input.
 146 
 147         salt '*' cmd.run_all "grep f" stdin='one\ntwo\nthree\nfour\nfive\n'
 148     
 149 
 150 cmd.run_bg:
 151 
 152     .. versionadded: 2016.3.0
 153 
 154     Execute the passed command in the background and return it's PID
 155 
 156     Note:
 157 
 158         If the init system is systemd and the backgrounded task should run even
 159         if the salt-minion process is restarted, prepend ``systemd-run
 160         --scope`` to the command. This will reparent the process in its own
 161         scope separate from salt-minion, and will not be affected by restarting
 162         the minion service.
 163 
 164     :param str cmd: The command to run. ex: ``ls -lart /home``
 165 
 166     :param str cwd: The directory from which to execute the command. Defaults
 167         to the home directory of the user specified by ``runas`` (or the user
 168         under which Salt is running if ``runas`` is not specified).
 169 
 170     :param str output_encoding: Control the encoding used to decode the
 171         command's output.
 172 
 173         Note:
 174             This should not need to be used in most cases. By default, Salt
 175             will try to use the encoding detected from the system locale, and
 176             will fall back to UTF-8 if this fails. This should only need to be
 177             used in cases where the output of the command is encoded in
 178             something other than the system locale or UTF-8.
 179 
 180             To see the encoding Salt has detected from the system locale, check
 181             the `locale` line in the output of :py:func:`test.versions_report
 182             <salt.modules.test.versions_report>`.
 183 
 184         New in version 2018.3.0
 185 
 186     :param str output_loglevel: Control the loglevel at which the output from
 187         the command is logged to the minion log.
 188 
 189         Note:
 190             The command being run will still be logged at the ``debug``
 191             loglevel regardless, unless ``quiet`` is used for this value.
 192 
 193     :param bool ignore_retcode: If the exit code of the command is nonzero,
 194         this is treated as an error condition, and the output from the command
 195         will be logged to the minion log. However, there are some cases where
 196         programs use the return code for signaling and a nonzero exit code
 197         doesn't necessarily mean failure. Pass this argument as ``True`` to
 198         skip logging the output if the command has a nonzero exit code.
 199 
 200     :param str runas: Specify an alternate user to run the command. The default
 201         behavior is to run as the user under which Salt is running. If running
 202         on a Windows minion you must also use the ``password`` argument, and
 203         the target user account must be in the Administrators group.
 204 
 205     :param str password: Windows only. Required when specifying ``runas``. This
 206         parameter will be ignored on non-Windows platforms.
 207 
 208         New in version 2016.3.0
 209 
 210     :param str shell: Specify an alternate shell. Defaults to the system's
 211         default shell.
 212 
 213     :param bool python_shell: If False, let python handle the positional
 214         arguments. Set to True to use shell features, such as pipes or
 215         redirection.
 216 
 217     :param dict env: Environment variables to be set prior to execution.
 218 
 219         Note:
 220             When passing environment variables on the CLI, they should be
 221             passed as the string representation of a dictionary.
 222 
 223                 salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
 224 
 225     :param bool clean_env: Attempt to clean out all other shell environment
 226         variables and set only those provided in the 'env' argument to this
 227         function.
 228 
 229     :param str prepend_path: $PATH segment to prepend (trailing ':' not
 230         necessary) to $PATH
 231 
 232         New in version 2018.3.0
 233 
 234     :param str template: If this setting is applied then the named templating
 235         engine will be used to render the downloaded file. Currently jinja,
 236         mako, and wempy are supported.
 237 
 238     :param str umask: The umask (in octal) to use when running the command.
 239 
 240     :param int timeout: A timeout in seconds for the executed process to return.
 241 
 242     Warning:
 243 
 244         This function does not process commands through a shell unless the
 245         ``python_shell`` argument is set to ``True``. This means that any
 246         shell-specific functionality such as 'echo' or the use of pipes,
 247         redirection or &&, should either be migrated to cmd.shell or have the
 248         python_shell=True flag set here.
 249 
 250         The use of ``python_shell=True`` means that the shell will accept _any_
 251         input including potentially malicious commands such as 'good_command;rm
 252         -rf /'.  Be absolutely certain that you have sanitized your input prior
 253         to using ``python_shell=True``.
 254 
 255     CLI Example:
 256 
 257         salt '*' cmd.run_bg "fstrim-all"
 258 
 259     The template arg can be set to 'jinja' or another supported template
 260     engine to render the command arguments before execution.
 261     For example:
 262 
 263         salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
 264 
 265     Specify an alternate shell with the shell parameter:
 266 
 267         salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
 268 
 269     If an equal sign (``=``) appears in an argument to a Salt command it is
 270     interpreted as a keyword argument in the format ``key=val``. That
 271     processing can be bypassed in order to pass an equal sign through to the
 272     remote shell command by manually specifying the kwarg:
 273 
 274         salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
 275     
 276 
 277 cmd.run_chroot:
 278 
 279     New in version 2014.7.0
 280 
 281     This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
 282     within a chroot, with dev and proc mounted in the chroot
 283 
 284     :param str root: Path to the root of the jail to use.
 285 
 286     :param str cmd: The command to run. ex: ``ls -lart /home``
 287 
 288     :param str cwd: The directory from which to execute the command. Defaults
 289         to the home directory of the user specified by ``runas`` (or the user
 290         under which Salt is running if ``runas`` is not specified).
 291 
 292     :parar str stdin: A string of standard input can be specified for the
 293         command to be run using the ``stdin`` parameter. This can be useful in
 294         cases where sensitive information must be read from standard input.
 295 
 296     :param str runas: Specify an alternate user to run the command. The default
 297         behavior is to run as the user under which Salt is running. If running
 298         on a Windows minion you must also use the ``password`` argument, and
 299         the target user account must be in the Administrators group.
 300 
 301     :param str shell: Specify an alternate shell. Defaults to the system's
 302         default shell.
 303 
 304     :param bool python_shell: If False, let python handle the positional
 305         arguments. Set to True to use shell features, such as pipes or
 306         redirection.
 307 
 308     :param dict env: Environment variables to be set prior to execution.
 309 
 310         Note:
 311             When passing environment variables on the CLI, they should be
 312             passed as the string representation of a dictionary.
 313 
 314                 salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
 315 
 316     :param dict clean_env: Attempt to clean out all other shell environment
 317         variables and set only those provided in the 'env' argument to this
 318         function.
 319 
 320     :param str template: If this setting is applied then the named templating
 321         engine will be used to render the downloaded file. Currently jinja,
 322         mako, and wempy are supported.
 323 
 324     :param bool rstrip:
 325         Strip all whitespace off the end of output before it is returned.
 326 
 327     :param str umask:
 328          The umask (in octal) to use when running the command.
 329 
 330     :param str output_encoding: Control the encoding used to decode the
 331         command's output.
 332 
 333         Note:
 334             This should not need to be used in most cases. By default, Salt
 335             will try to use the encoding detected from the system locale, and
 336             will fall back to UTF-8 if this fails. This should only need to be
 337             used in cases where the output of the command is encoded in
 338             something other than the system locale or UTF-8.
 339 
 340             To see the encoding Salt has detected from the system locale, check
 341             the `locale` line in the output of :py:func:`test.versions_report
 342             <salt.modules.test.versions_report>`.
 343 
 344         New in version 2018.3.0
 345 
 346     :param str output_loglevel: Control the loglevel at which the output from
 347         the command is logged to the minion log.
 348 
 349         Note:
 350             The command being run will still be logged at the ``debug``
 351             loglevel regardless, unless ``quiet`` is used for this value.
 352 
 353     :param bool ignore_retcode: If the exit code of the command is nonzero,
 354         this is treated as an error condition, and the output from the command
 355         will be logged to the minion log. However, there are some cases where
 356         programs use the return code for signaling and a nonzero exit code
 357         doesn't necessarily mean failure. Pass this argument as ``True`` to
 358         skip logging the output if the command has a nonzero exit code.
 359 
 360     :param bool hide_output: If ``True``, suppress stdout and stderr in the
 361         return data.
 362 
 363         Note:
 364             This is separate from ``output_loglevel``, which only handles how
 365             Salt logs to the minion log.
 366 
 367         New in version 2018.3.0
 368 
 369     :param int timeout:
 370         A timeout in seconds for the executed process to return.
 371 
 372     :param bool use_vt:
 373         Use VT utils (saltstack) to stream the command output more
 374         interactively to the console and the logs. This is experimental.
 375 
 376     CLI Example:
 377 
 378         salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
 379     
 380 
 381 cmd.run_stderr:
 382 
 383     Execute a command and only return the standard error
 384 
 385     :param str cmd: The command to run. ex: ``ls -lart /home``
 386 
 387     :param str cwd: The directory from which to execute the command. Defaults
 388         to the home directory of the user specified by ``runas`` (or the user
 389         under which Salt is running if ``runas`` is not specified).
 390 
 391     :param str stdin: A string of standard input can be specified for the
 392         command to be run using the ``stdin`` parameter. This can be useful in
 393         cases where sensitive information must be read from standard input.
 394 
 395     :param str runas: Specify an alternate user to run the command. The default
 396         behavior is to run as the user under which Salt is running. If running
 397         on a Windows minion you must also use the ``password`` argument, and
 398         the target user account must be in the Administrators group.
 399 
 400     :param str password: Windows only. Required when specifying ``runas``. This
 401         parameter will be ignored on non-Windows platforms.
 402 
 403         New in version 2016.3.0
 404 
 405     :param str shell: Specify an alternate shell. Defaults to the system's
 406         default shell.
 407 
 408     :param bool python_shell: If False, let python handle the positional
 409         arguments. Set to True to use shell features, such as pipes or
 410         redirection.
 411 
 412     :param dict env: Environment variables to be set prior to execution.
 413 
 414         Note:
 415             When passing environment variables on the CLI, they should be
 416             passed as the string representation of a dictionary.
 417 
 418                 salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
 419 
 420     :param bool clean_env: Attempt to clean out all other shell environment
 421         variables and set only those provided in the 'env' argument to this
 422         function.
 423 
 424     :param str prepend_path: $PATH segment to prepend (trailing ':' not
 425         necessary) to $PATH
 426 
 427         New in version 2018.3.0
 428 
 429     :param str template: If this setting is applied then the named templating
 430         engine will be used to render the downloaded file. Currently jinja,
 431         mako, and wempy are supported.
 432 
 433     :param bool rstrip: Strip all whitespace off the end of output before it is
 434         returned.
 435 
 436     :param str umask: The umask (in octal) to use when running the command.
 437 
 438     :param str output_encoding: Control the encoding used to decode the
 439         command's output.
 440 
 441         Note:
 442             This should not need to be used in most cases. By default, Salt
 443             will try to use the encoding detected from the system locale, and
 444             will fall back to UTF-8 if this fails. This should only need to be
 445             used in cases where the output of the command is encoded in
 446             something other than the system locale or UTF-8.
 447 
 448             To see the encoding Salt has detected from the system locale, check
 449             the `locale` line in the output of :py:func:`test.versions_report
 450             <salt.modules.test.versions_report>`.
 451 
 452         New in version 2018.3.0
 453 
 454     :param str output_loglevel: Control the loglevel at which the output from
 455         the command is logged to the minion log.
 456 
 457         Note:
 458             The command being run will still be logged at the ``debug``
 459             loglevel regardless, unless ``quiet`` is used for this value.
 460 
 461     :param bool ignore_retcode: If the exit code of the command is nonzero,
 462         this is treated as an error condition, and the output from the command
 463         will be logged to the minion log. However, there are some cases where
 464         programs use the return code for signaling and a nonzero exit code
 465         doesn't necessarily mean failure. Pass this argument as ``True`` to
 466         skip logging the output if the command has a nonzero exit code.
 467 
 468     :param bool hide_output: If ``True``, suppress stdout and stderr in the
 469         return data.
 470 
 471         Note:
 472             This is separate from ``output_loglevel``, which only handles how
 473             Salt logs to the minion log.
 474 
 475         New in version 2018.3.0
 476 
 477     :param int timeout: A timeout in seconds for the executed process to
 478         return.
 479 
 480     :param bool use_vt: Use VT utils (saltstack) to stream the command output
 481         more interactively to the console and the logs. This is experimental.
 482 
 483     CLI Example:
 484 
 485         salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \$2}'"
 486 
 487     The template arg can be set to 'jinja' or another supported template
 488     engine to render the command arguments before execution.
 489     For example:
 490 
 491         salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \$2}'"
 492 
 493     A string of standard input can be specified for the command to be run using
 494     the ``stdin`` parameter. This can be useful in cases where sensitive
 495     information must be read from standard input.
 496 
 497         salt '*' cmd.run_stderr "grep f" stdin='one\ntwo\nthree\nfour\nfive\n'
 498     
 499 
 500 cmd.run_stdout:
 501 
 502     Execute a command, and only return the standard out
 503 
 504     :param str cmd: The command to run. ex: ``ls -lart /home``
 505 
 506     :param str cwd: The directory from which to execute the command. Defaults
 507         to the home directory of the user specified by ``runas`` (or the user
 508         under which Salt is running if ``runas`` is not specified).
 509 
 510     :param str stdin: A string of standard input can be specified for the
 511         command to be run using the ``stdin`` parameter. This can be useful in
 512         cases where sensitive information must be read from standard input.
 513 
 514     :param str runas: Specify an alternate user to run the command. The default
 515         behavior is to run as the user under which Salt is running. If running
 516         on a Windows minion you must also use the ``password`` argument, and
 517         the target user account must be in the Administrators group.
 518 
 519     :param str password: Windows only. Required when specifying ``runas``. This
 520         parameter will be ignored on non-Windows platforms.
 521 
 522         New in version 2016.3.0
 523 
 524     :param str shell: Specify an alternate shell. Defaults to the system's
 525         default shell.
 526 
 527     :param bool python_shell: If False, let python handle the positional
 528         arguments. Set to True to use shell features, such as pipes or
 529         redirection.
 530 
 531     :param dict env: Environment variables to be set prior to execution.
 532 
 533         Note:
 534             When passing environment variables on the CLI, they should be
 535             passed as the string representation of a dictionary.
 536 
 537                 salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
 538 
 539     :param bool clean_env: Attempt to clean out all other shell environment
 540         variables and set only those provided in the 'env' argument to this
 541         function.
 542 
 543     :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
 544         to $PATH
 545 
 546         New in version 2018.3.0
 547 
 548     :param str template: If this setting is applied then the named templating
 549         engine will be used to render the downloaded file. Currently jinja,
 550         mako, and wempy are supported.
 551 
 552     :param bool rstrip: Strip all whitespace off the end of output before it is
 553         returned.
 554 
 555     :param str umask: The umask (in octal) to use when running the command.
 556 
 557     :param str output_encoding: Control the encoding used to decode the
 558         command's output.
 559 
 560         Note:
 561             This should not need to be used in most cases. By default, Salt
 562             will try to use the encoding detected from the system locale, and
 563             will fall back to UTF-8 if this fails. This should only need to be
 564             used in cases where the output of the command is encoded in
 565             something other than the system locale or UTF-8.
 566 
 567             To see the encoding Salt has detected from the system locale, check
 568             the `locale` line in the output of :py:func:`test.versions_report
 569             <salt.modules.test.versions_report>`.
 570 
 571         New in version 2018.3.0
 572 
 573     :param str output_loglevel: Control the loglevel at which the output from
 574         the command is logged to the minion log.
 575 
 576         Note:
 577             The command being run will still be logged at the ``debug``
 578             loglevel regardless, unless ``quiet`` is used for this value.
 579 
 580     :param bool ignore_retcode: If the exit code of the command is nonzero,
 581         this is treated as an error condition, and the output from the command
 582         will be logged to the minion log. However, there are some cases where
 583         programs use the return code for signaling and a nonzero exit code
 584         doesn't necessarily mean failure. Pass this argument as ``True`` to
 585         skip logging the output if the command has a nonzero exit code.
 586 
 587     :param bool hide_output: If ``True``, suppress stdout and stderr in the
 588         return data.
 589 
 590         Note:
 591             This is separate from ``output_loglevel``, which only handles how
 592             Salt logs to the minion log.
 593 
 594         New in version 2018.3.0
 595 
 596     :param int timeout: A timeout in seconds for the executed process to
 597         return.
 598 
 599     :param bool use_vt: Use VT utils (saltstack) to stream the command output
 600         more interactively to the console and the logs. This is experimental.
 601 
 602     CLI Example:
 603 
 604         salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \$2}'"
 605 
 606     The template arg can be set to 'jinja' or another supported template
 607     engine to render the command arguments before execution.
 608     For example:
 609 
 610         salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \$2}'"
 611 
 612     A string of standard input can be specified for the command to be run using
 613     the ``stdin`` parameter. This can be useful in cases where sensitive
 614     information must be read from standard input.
 615 
 616         salt '*' cmd.run_stdout "grep f" stdin='one\ntwo\nthree\nfour\nfive\n'
 617     
 618 
 619 cmd.script:
 620 
 621     Download a script from a remote location and execute the script locally.
 622     The script can be located on the salt master file server or on an HTTP/FTP
 623     server.
 624 
 625     The script will be executed directly, so it can be written in any available
 626     programming language.
 627 
 628     :param str source: The location of the script to download. If the file is
 629         located on the master in the directory named spam, and is called eggs,
 630         the source string is salt://spam/eggs
 631 
 632     :param str args: String of command line args to pass to the script. Only
 633         used if no args are specified as part of the `name` argument. To pass a
 634         string containing spaces in YAML, you will need to doubly-quote it:
 635 
 636             salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
 637 
 638     :param str cwd: The directory from which to execute the command. Defaults
 639         to the home directory of the user specified by ``runas`` (or the user
 640         under which Salt is running if ``runas`` is not specified).
 641 
 642     :param str stdin: A string of standard input can be specified for the
 643         command to be run using the ``stdin`` parameter. This can be useful in
 644         cases where sensitive information must be read from standard input.
 645 
 646     :param str runas: Specify an alternate user to run the command. The default
 647         behavior is to run as the user under which Salt is running. If running
 648         on a Windows minion you must also use the ``password`` argument, and
 649         the target user account must be in the Administrators group.
 650 
 651     :param str password: Windows only. Required when specifying ``runas``. This
 652         parameter will be ignored on non-Windows platforms.
 653 
 654         New in version 2016.3.0
 655 
 656     :param str shell: Specify an alternate shell. Defaults to the system's
 657         default shell.
 658 
 659     :param bool python_shell: If False, let python handle the positional
 660         arguments. Set to True to use shell features, such as pipes or
 661         redirection.
 662 
 663     :param bool bg: If True, run script in background and do not await or
 664         deliver it's results
 665 
 666     :param dict env: Environment variables to be set prior to execution.
 667 
 668         Note:
 669             When passing environment variables on the CLI, they should be
 670             passed as the string representation of a dictionary.
 671 
 672                 salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
 673 
 674     :param str template: If this setting is applied then the named templating
 675         engine will be used to render the downloaded file. Currently jinja,
 676         mako, and wempy are supported.
 677 
 678     :param str umask: The umask (in octal) to use when running the command.
 679 
 680     :param str output_encoding: Control the encoding used to decode the
 681         command's output.
 682 
 683         Note:
 684             This should not need to be used in most cases. By default, Salt
 685             will try to use the encoding detected from the system locale, and
 686             will fall back to UTF-8 if this fails. This should only need to be
 687             used in cases where the output of the command is encoded in
 688             something other than the system locale or UTF-8.
 689 
 690             To see the encoding Salt has detected from the system locale, check
 691             the `locale` line in the output of :py:func:`test.versions_report
 692             <salt.modules.test.versions_report>`.
 693 
 694         New in version 2018.3.0
 695 
 696     :param str output_loglevel: Control the loglevel at which the output from
 697         the command is logged to the minion log.
 698 
 699         Note:
 700             The command being run will still be logged at the ``debug``
 701             loglevel regardless, unless ``quiet`` is used for this value.
 702 
 703     :param bool ignore_retcode: If the exit code of the command is nonzero,
 704         this is treated as an error condition, and the output from the command
 705         will be logged to the minion log. However, there are some cases where
 706         programs use the return code for signaling and a nonzero exit code
 707         doesn't necessarily mean failure. Pass this argument as ``True`` to
 708         skip logging the output if the command has a nonzero exit code.
 709 
 710     :param bool hide_output: If ``True``, suppress stdout and stderr in the
 711         return data.
 712 
 713         Note:
 714             This is separate from ``output_loglevel``, which only handles how
 715             Salt logs to the minion log.
 716 
 717         New in version 2018.3.0
 718 
 719     :param int timeout: If the command has not terminated after timeout
 720         seconds, send the subprocess sigterm, and if sigterm is ignored, follow
 721         up with sigkill
 722 
 723     :param bool use_vt: Use VT utils (saltstack) to stream the command output
 724         more interactively to the console and the logs. This is experimental.
 725 
 726     CLI Example:
 727 
 728         salt '*' cmd.script salt://scripts/runme.sh
 729         salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
 730         salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\tmp\infile.txt' shell='powershell'
 731 
 732 
 733         salt '*' cmd.script salt://scripts/runme.sh stdin='one\ntwo\nthree\nfour\nfive\n'
 734     
 735 
 736 cmd.script_retcode:
 737 
 738     Download a script from a remote location and execute the script locally.
 739     The script can be located on the salt master file server or on an HTTP/FTP
 740     server.
 741 
 742     The script will be executed directly, so it can be written in any available
 743     programming language.
 744 
 745     The script can also be formatted as a template, the default is jinja.
 746 
 747     Only evaluate the script return code and do not block for terminal output
 748 
 749     :param str source: The location of the script to download. If the file is
 750         located on the master in the directory named spam, and is called eggs,
 751         the source string is salt://spam/eggs
 752 
 753     :param str args: String of command line args to pass to the script. Only
 754         used if no args are specified as part of the `name` argument. To pass a
 755         string containing spaces in YAML, you will need to doubly-quote it:
 756         "arg1 'arg two' arg3"
 757 
 758     :param str cwd: The directory from which to execute the command. Defaults
 759         to the home directory of the user specified by ``runas`` (or the user
 760         under which Salt is running if ``runas`` is not specified).
 761 
 762     :param str stdin: A string of standard input can be specified for the
 763         command to be run using the ``stdin`` parameter. This can be useful in
 764         cases where sensitive information must be read from standard input.
 765 
 766     :param str runas: Specify an alternate user to run the command. The default
 767         behavior is to run as the user under which Salt is running. If running
 768         on a Windows minion you must also use the ``password`` argument, and
 769         the target user account must be in the Administrators group.
 770 
 771     :param str password: Windows only. Required when specifying ``runas``. This
 772         parameter will be ignored on non-Windows platforms.
 773 
 774         New in version 2016.3.0
 775 
 776     :param str shell: Specify an alternate shell. Defaults to the system's
 777         default shell.
 778 
 779     :param bool python_shell: If False, let python handle the positional
 780         arguments. Set to True to use shell features, such as pipes or
 781         redirection.
 782 
 783     :param dict env: Environment variables to be set prior to execution.
 784 
 785         Note:
 786             When passing environment variables on the CLI, they should be
 787             passed as the string representation of a dictionary.
 788 
 789                 salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
 790 
 791     :param str template: If this setting is applied then the named templating
 792         engine will be used to render the downloaded file. Currently jinja,
 793         mako, and wempy are supported.
 794 
 795     :param str umask: The umask (in octal) to use when running the command.
 796 
 797     :param str output_encoding: Control the encoding used to decode the
 798         command's output.
 799 
 800         Note:
 801             This should not need to be used in most cases. By default, Salt
 802             will try to use the encoding detected from the system locale, and
 803             will fall back to UTF-8 if this fails. This should only need to be
 804             used in cases where the output of the command is encoded in
 805             something other than the system locale or UTF-8.
 806 
 807             To see the encoding Salt has detected from the system locale, check
 808             the `locale` line in the output of :py:func:`test.versions_report
 809             <salt.modules.test.versions_report>`.
 810 
 811         New in version 2018.3.0
 812 
 813     :param str output_loglevel: Control the loglevel at which the output from
 814         the command is logged to the minion log.
 815 
 816         Note:
 817             The command being run will still be logged at the ``debug``
 818             loglevel regardless, unless ``quiet`` is used for this value.
 819 
 820     :param bool ignore_retcode: If the exit code of the command is nonzero,
 821         this is treated as an error condition, and the output from the command
 822         will be logged to the minion log. However, there are some cases where
 823         programs use the return code for signaling and a nonzero exit code
 824         doesn't necessarily mean failure. Pass this argument as ``True`` to
 825         skip logging the output if the command has a nonzero exit code.
 826 
 827     :param int timeout: If the command has not terminated after timeout
 828         seconds, send the subprocess sigterm, and if sigterm is ignored, follow
 829         up with sigkill
 830 
 831     :param bool use_vt: Use VT utils (saltstack) to stream the command output
 832         more interactively to the console and the logs. This is experimental.
 833 
 834     CLI Example:
 835 
 836         salt '*' cmd.script_retcode salt://scripts/runme.sh
 837         salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
 838         salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\tmp\infile.txt' shell='powershell'
 839 
 840     A string of standard input can be specified for the command to be run using
 841     the ``stdin`` parameter. This can be useful in cases where sensitive
 842     information must be read from standard input.
 843 
 844         salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\ntwo\nthree\nfour\nfive\n'
 845     
 846 
 847 cmd.shell:
 848 
 849     Execute the passed command and return the output as a string.
 850 
 851     New in version 2015.5.0
 852 
 853     :param str cmd: The command to run. ex: ``ls -lart /home``
 854 
 855     :param str cwd: The directory from which to execute the command. Defaults
 856         to the home directory of the user specified by ``runas`` (or the user
 857         under which Salt is running if ``runas`` is not specified).
 858 
 859     :param str stdin: A string of standard input can be specified for the
 860         command to be run using the ``stdin`` parameter. This can be useful in
 861         cases where sensitive information must be read from standard input.
 862 
 863     :param str runas: Specify an alternate user to run the command. The default
 864         behavior is to run as the user under which Salt is running. If running
 865         on a Windows minion you must also use the ``password`` argument, and
 866         the target user account must be in the Administrators group.
 867 
 868     :param str password: Windows only. Required when specifying ``runas``. This
 869         parameter will be ignored on non-Windows platforms.
 870 
 871         New in version 2016.3.0
 872 
 873     :param int shell: Shell to execute under. Defaults to the system default
 874         shell.
 875 
 876     :param bool bg: If True, run command in background and do not await or
 877         deliver its results
 878 
 879     :param dict env: Environment variables to be set prior to execution.
 880 
 881         Note:
 882             When passing environment variables on the CLI, they should be
 883             passed as the string representation of a dictionary.
 884 
 885                 salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
 886 
 887     :param bool clean_env: Attempt to clean out all other shell environment
 888         variables and set only those provided in the 'env' argument to this
 889         function.
 890 
 891     :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
 892         to $PATH
 893 
 894         New in version 2018.3.0
 895 
 896     :param str template: If this setting is applied then the named templating
 897         engine will be used to render the downloaded file. Currently jinja,
 898         mako, and wempy are supported.
 899 
 900     :param bool rstrip: Strip all whitespace off the end of output before it is
 901         returned.
 902 
 903     :param str umask: The umask (in octal) to use when running the command.
 904 
 905     :param str output_encoding: Control the encoding used to decode the
 906         command's output.
 907 
 908         Note:
 909             This should not need to be used in most cases. By default, Salt
 910             will try to use the encoding detected from the system locale, and
 911             will fall back to UTF-8 if this fails. This should only need to be
 912             used in cases where the output of the command is encoded in
 913             something other than the system locale or UTF-8.
 914 
 915             To see the encoding Salt has detected from the system locale, check
 916             the `locale` line in the output of :py:func:`test.versions_report
 917             <salt.modules.test.versions_report>`.
 918 
 919         New in version 2018.3.0
 920 
 921     :param str output_loglevel: Control the loglevel at which the output from
 922         the command is logged to the minion log.
 923 
 924         Note:
 925             The command being run will still be logged at the ``debug``
 926             loglevel regardless, unless ``quiet`` is used for this value.
 927 
 928     :param bool ignore_retcode: If the exit code of the command is nonzero,
 929         this is treated as an error condition, and the output from the command
 930         will be logged to the minion log. However, there are some cases where
 931         programs use the return code for signaling and a nonzero exit code
 932         doesn't necessarily mean failure. Pass this argument as ``True`` to
 933         skip logging the output if the command has a nonzero exit code.
 934 
 935     :param bool hide_output: If ``True``, suppress stdout and stderr in the
 936         return data.
 937 
 938         Note:
 939             This is separate from ``output_loglevel``, which only handles how
 940             Salt logs to the minion log.
 941 
 942         New in version 2018.3.0
 943 
 944     :param int timeout: A timeout in seconds for the executed process to
 945         return.
 946 
 947     :param bool use_vt: Use VT utils (saltstack) to stream the command output
 948         more interactively to the console and the logs. This is experimental.
 949 
 950     Warning:
 951 
 952         This passes the cmd argument directly to the shell without any further
 953         processing! Be absolutely sure that you have properly sanitized the
 954         command passed to this function and do not use untrusted inputs.
 955 
 956     CLI Example:
 957 
 958         salt '*' cmd.shell "ls -l | awk '/foo/{print \$2}'"
 959 
 960     The template arg can be set to 'jinja' or another supported template
 961     engine to render the command arguments before execution.
 962     For example:
 963 
 964         salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \$2}'"
 965 
 966     Specify an alternate shell with the shell parameter:
 967 
 968         salt '*' cmd.shell "Get-ChildItem C:\ " shell='powershell'
 969 
 970     A string of standard input can be specified for the command to be run using
 971     the ``stdin`` parameter. This can be useful in cases where sensitive
 972     information must be read from standard input.
 973 
 974         salt '*' cmd.shell "grep f" stdin='one\ntwo\nthree\nfour\nfive\n'
 975 
 976     If an equal sign (``=``) appears in an argument to a Salt command it is
 977     interpreted as a keyword argument in the format ``key=val``. That
 978     processing can be bypassed in order to pass an equal sign through to the
 979     remote shell command by manually specifying the kwarg:
 980 
 981         salt '*' cmd.shell cmd='sed -e s/=/:/g'
 982     
 983 
 984 cmd.shell_info:
 985 
 986     New in version 2016.11.0
 987 
 988     Provides information about a shell or script languages which often use
 989     ``#!``. The values returned are dependent on the shell or scripting
 990     languages all return the ``installed``, ``path``, ``version``,
 991     ``version_raw``
 992 
 993     Args:
 994         shell (str): Name of the shell. Support shells/script languages include
 995         bash, cmd, perl, php, powershell, python, ruby and zsh
 996 
 997         list_modules (bool): True to list modules available to the shell.
 998         Currently only lists powershell modules.
 999 
1000     Returns:
1001         dict: A dictionary of information about the shell
1002 
1003         {'version': '<2 or 3 numeric components dot-separated>',
1004          'version_raw': '<full version string>',
1005          'path': '<full path to binary>',
1006          'installed': <True, False or None>,
1007          '<attribute>': '<attribute value>'}
1008 
1009     Note:
1010         - ``installed`` is always returned, if ``None`` or ``False`` also
1011           returns error and may also return ``stdout`` for diagnostics.
1012         - ``version`` is for use in determine if a shell/script language has a
1013           particular feature set, not for package management.
1014         - The shell must be within the executable search path.
1015 
1016     CLI Example:
1017 
1018         salt '*' cmd.shell_info bash
1019         salt '*' cmd.shell_info powershell
1020 
1021     :codeauthor: Damon Atkins <https://github.com/damon-atkins>
1022     
1023 
1024 cmd.shells:
1025 
1026     Lists the valid shells on this system via the /etc/shells file
1027 
1028     New in version 2015.5.0
1029 
1030     CLI Example::
1031 
1032         salt '*' cmd.shells
1033     
1034 
1035 cmd.tty:
1036 
1037     Echo a string to a specific tty
1038 
1039     CLI Example:
1040 
1041         salt '*' cmd.tty tty0 'This is a test'
1042         salt '*' cmd.tty pts3 'This is a test'
1043     
1044 
1045 cmd.which:
1046 
1047     Returns the path of an executable available on the minion, None otherwise
1048 
1049     CLI Example:
1050 
1051         salt '*' cmd.which cat
1052     
1053 
1054 cmd.which_bin:
1055 
1056     Returns the first command found in a list of commands
1057 
1058     CLI Example:
1059 
1060         salt '*' cmd.which_bin '[pip2, pip, pip-python]'
例cmd模块里面可以用方法

 二、常用模块

  以下这些模块都是肯定会用到的,必须要勤加练习。

  2.1.1 cmd.has_exec的用法(如果可执行文件在minion上可用,则可用返回true,否则返回false)

#最后面的命令可以不加引号,但是如果遇到 ip addr这用中间有空格的命令就直接报错,建议不管命令中有没有空格都加上引号。
salt 'dasha_ceshi_172.16.5.239' cmd.has_exec 'ipconfig'

  2.1.2 cmd.retcode的用法(在minion端执行一个shell命令并返回命令的返回码。0表示成功。0以外表示失败有问题,有提示1或者直接报错的。)。注意,后面的命令只能是linux标准的写法,例如ls -l ,要是协程ll就直接报错。

salt 'dasha_ceshi_172.16.5.239' cmd.retcode  'ls -l /etc/hostname'

  2.1.3 cmd.run的用法(这个执行shell命令跟cmd.retcode类似,但是不同的是,cmd.run就像再本地执行一样,执行完命令直接返回信息。cmd.run_stderr意思只会在出问题的时候返回信息,如果你命令出错直接像本地一样提示。)

[root@bogon ~]#  salt 'dasha_ceshi_172.16.5.239' cmd.run  'ls -l /etc/hostname'
dasha_ceshi_172.16.5.239:
    -rw-r--r--. 1 root root 22 Mar  9 23:47 /etc/hostname

  2.1.4 cmd.script和cmd.script_retcode(从远程salt服务器或者ftp服务器或者http服务器下载脚本到本地执行)。如果想使用cmd.script命令,首先需要修改master配置文件,添加salt根目录,方法如下:

#修改方法如下,我这里把/root目录作为salt的根目录,如果多个目录可以在下面加,修改完需要重启salt-master服务。
vim /etc/salt/master
---------------------------------
file_roots:
  base:
    - /root/
---------------------------------

    cmd.script:

    首先新建一个可执行的.sh文件,如test.sh,不用给可执行权限也可以执行的。添加内容如下:

#!/bin/bash
ifconfig

    然后执行命令,注意,我们在配置文件中已经修改了/root就是salt的根目录,所以这里直接写脚本名字即可,不用再写绝对路径,否则会报错。

salt 'dasha_ceshi_172.16.5.239' cmd.script  salt://test.sh
dasha_ceshi_172.16.5.239:
    ----------
    pid:
        1519
    retcode:
        0
    stderr:
    stdout:
        ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
                inet 172.16.5.239  netmask 255.255.255.0  broadcast 172.16.5.255
                inet6 fe80::20c:29ff:fe8d:abf8  prefixlen 64  scopeid 0x20<link>
                ether 00:0c:29:8d:ab:f8  txqueuelen 1000  (Ethernet)
                RX packets 2027  bytes 219750 (214.5 KiB)
                RX errors 0  dropped 0  overruns 0  frame 0
                TX packets 2091  bytes 1419213 (1.3 MiB)
                TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
                device interrupt 19  base 0x2000  
        
        lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
                inet 127.0.0.1  netmask 255.0.0.0
                inet6 ::1  prefixlen 128  scopeid 0x10<host>
                loop  txqueuelen 1  (Local Loopback)
                RX packets 136  bytes 11816 (11.5 KiB)
                RX errors 0  dropped 0  overruns 0  frame 0
                TX packets 136  bytes 11816 (11.5 KiB)
                TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
返回信息

    cmd.script_retcode:

#只返回执行状态码,0表示成功,其它表示失败
salt 'dasha_ceshi_172.16.5.239' cmd.script_retcode  salt://test.sh

  2.1.5 cmd.shell和cmd.shells(cmd.shell跟cmd.run一样,一般用cmd.run,cmd.shells是通过/ etc / shells文件列出此系统上的有效shell):

 

2.1.6 cmd.which和cmd.which_bin的用法(就是查找执行文件所在的位置,which命令嘛都不陌生)

  cmd.which(其实跟本地直接which ifconfig命令返回信息相同):

[root@bogon ~]# salt 'dasha_ceshi_172.16.5.239'  cmd.which  'cat'
dasha_ceshi_172.16.5.239:
    /usr/bin/cat

  cmd.which_bin:

[root@bogon ~]# salt 'dasha_ceshi_172.16.5.239'  cmd.which_bin  '[cat]'
dasha_ceshi_172.16.5.239:
    /usr/bin/cat

  

2.2 cp模块的常用使用方法

  2.2.1 cp.get_dir和cp.get_file的用法(就是从master端cp目录或者文件到minion端的目录,get_dir支持与get_file相同的模板和gzip参数。对应的是cp.push:,cp.push_dir:,就是把客户端的文件或者目录推送到master端的cachedir,默认为/var/cache/salt/master/minions/minion-id/files,但是这种用法是禁用状态,一般不让minion端的文件或目录发送到master端,这里只是记录一下有这种用法。)

  注意:这里也需要配置master配置文件里面的salt根目录,详情见2.1.4 

   例子:

#salt '*' cp.get_dir salt://path/to/dir/ /minion/dest    #从salt master递归复制目录到minion客户端的/minion/dest目录下面。

#salt '*' cp.get_file salt://path/to/file /minion/dest     #从服务端拷贝单个文件到minion端的/minion/dest目录下面。

   2.2.2 cp.get_url(用于从URL获取单个文件)

  例子:

  # salt '*' cp.get_url salt://cptest1/cptest1file /tmp/test  #将salt://cptest1/cptest1file文件里面的内容写入到/tmp/test文件里面,每次都会覆盖里面的内容。这种就跟cp.get_file相似。不同的是复制到minion以后文件名直接变成index.html,以后直接覆盖内容,除非你执行客户端的文件名,不过后缀肯定是html。

  # salt '*' cp.get_url http://www.51niux.com/?id=116 /root/test.html   #如这种就把一个页面的html信息写入到了客户端的/tmp/test.html文件,切记只能是这种文本形式的文件,但是感觉这个没有什么用。这里我用到的是下载安装包,然后传给客户端,如果这样的话客户端指定路径就行,无需指定文件名。

    salt '*' cp.get_url  #正确用法

[root@bogon ~]# salt '*' cp.get_url http://down1.chinaunix.net/distfiles/utelnetd-0.1.9.tar.gz     /root/
dasha_ceshi_172.16.5.239:
    /root/utelnetd-0.1.9.tar.gz
dasha_ceshi_172.16.5.240:
    /root/utelnetd-0.1.9.tar.gz

  2.2.3 cp.list_master和cp.list_master_dirs的用法(这个就是查看salt master本地的file服务器又哪些文件或者目录)

salt 'dasha_ceshi_172.16.5.239' cp.list_master
salt 'dasha_ceshi_172.16.5.239' cp.list_master_dirs

2.3 file模块的常用使用方法

 2.3.1 file.access的用法(f代表存在,rwx分别代表读、写、执行权限)还有file.file_exists、file.get_mode和file.stats的用法。

#需要后面加参数f,如果指定minion有这文件就返回True,否则False。加参数x,如果有执行权限就返回True,否则False。
[root@localhost master]# salt '*' file.access /root/test.sh f
dasha_ceshi_172.16.5.239:
    True
dasha_ceshi_172.16.5.240:
    True


#不要加参数,如果指定minion有指定文件就返回True,否则返回False
[root@localhost master]# salt '*' file.file_exists  /root/test.sh 
dasha_ceshi_172.16.5.239:
    True
dasha_ceshi_172.16.5.240:
    False
1 f:测试路径的存在性
2 r:测试路径的可读性
3 w:测试路径的可写性
4 x:测试路径是否可以执行
参数介绍

 

# salt '*' file.get_mode /etc/passwd  #file.get_mode后面指定目录或者文件,可以查看其授权情况,如文件一般是0644,如果文件或目录不存在无信息(当然还有:file.is_blkdev检查文件是否存在并且是块设备,file.is_chrdev检查文件是否存在并且是字符设备,file.is_fifo检查文件是否存在并且是FIFO,file.is_link检查路径是否是符号链接)

# salt '*' file.stats /etc/passwd  #file.stats返回一个文件或目录的统计信息,这里是返回/etc/passwd文件的统计信息(类型,时间,属组,权限等)。

科普:  

1>访问时间(access time 简写为atime)

2>修改时间(modify time 简写为mtime)

3>状态修改时间(change time 简写为ctime)

1 import time
2 
3 t_time = 1529463570
4 timeArray=time.localtime(t_time)
5 print(time.strftime("%Y-%m-%d %H:%M:%S",timeArray))
6 2018-06-20 10:59:30
使用python计算时间方法

 2.3.2 file.append和file.write的用法(前者将内容追加到文件的末尾,后者是直接覆盖类似于echo >,但是格式跟前者一样。)

#file.append类似于>>
[root@bogon ~]# salt '*' file.append /root/test.sh 'This is file.append test!' 'test line two'
dasha_ceshi_172.16.5.239:
    Wrote 2 lines to "/root/test.sh"
dasha_ceshi_172.16.5.240:
    Wrote 2 lines to "/root/test.sh"
#file.write类似于>,直接覆盖目标文件
[root@bogon ~]# salt '*' file.write  /root/test.sh 'This is file.append test!' 'test line two'
dasha_ceshi_172.16.5.239:
    Wrote 2 lines to "/root/test.sh"
dasha_ceshi_172.16.5.240:
    Wrote 2 lines to "/root/test.sh"

  注意:如果想换行的话,每一行一个单独的引号,中间用空格隔开,就算是换行。

 问题来了,如果我们输入的文件不止纯文本或者换号呢?事实也是。

案例一、

[root@bogon ~]#  salt '*' file.append /root/test.sh  args='Hostname=`hostname`' 
dasha_ceshi_172.16.5.240:
    Wrote 1 lines to "/root/test.sh"
dasha_ceshi_172.16.5.239:
    Wrote 1 lines to "/root/test.sh"
[root@bogon ~]#  salt '*' file.append /root/test.sh  args='Hostname='hostname'' 
dasha_ceshi_172.16.5.239:
    Wrote 1 lines to "/root/test.sh"
dasha_ceshi_172.16.5.240:
    Wrote 1 lines to "/root/test.sh"

  注意:上面第一个例子单引号的问题,内单引号是Esc下面的按键

  

案例二、

注意,在这种情况下我们需要每行并排两个的话直接用[]就行,但是如果想换行的话只需中间加一个逗号即可

[root@bogon ~]# salt '*' file.append /root/test.sh  args=['Hostname=`hostname`''rel=`cat /etc/redhat-release`']
dasha_ceshi_172.16.5.239:
    Wrote 1 lines to "/root/test.sh"
dasha_ceshi_172.16.5.240:
    Wrote 1 lines to "/root/test.sh"
[root@bogon ~]# salt '*' file.append /root/test.sh  args=['Hostname=`hostname`','rel=`cat /etc/redhat-release`']
dasha_ceshi_172.16.5.239:
    Wrote 2 lines to "/root/test.sh"
dasha_ceshi_172.16.5.240:
    Wrote 2 lines to "/root/test.sh"

案例三、

  这个可就NB了,之间作为变量直接给文件赋值,写法上注意最外侧的双引号。

[root@bogon ~]# salt '*' file.append /root/test.sh  args="['Hostname=`hostname`','rel=`cat /etc/redhat-release`']"
dasha_ceshi_172.16.5.239:
    Wrote 2 lines to "/root/test.sh"
dasha_ceshi_172.16.5.240:
    Wrote 2 lines to "/root/test.sh"

 总结:

  1、如果添加的不是变量直接用单引号引住就行,如果需要换行,只需要每行单独用单引号引住就行,每行用空格隔开,如果中间有等号,前面需要以args开通。

  2、如果添加的静态变量,值需要用Esc下面的引号。

  3、如果需要多个静态变量并排,需要args=[]引住,引号里面内容写法如上2写法,中间不用逗号或空格。如果需要换号中间只需要加逗号即可。

  4、如果添加的是动态变量,最外围需要用双引号。

 2.3.3 file.chgrp、file.chown和file.set_mode用法(前者是更改文件的属组,中者是更改文件数的属主属组,后者是更改文件或目录的权限)

  注意:

  1、minion没有这个用户会提示Group does not exist,如果有提示None

  2、file.chown,用户和组中间用空格隔开,加权限前面需要加0.

  

2.3.4 file.comment和file.comment_line的用法(注释指定内容的行,每次操作前都会更新文件名命令的.bak备份文件)

  file.comment:匹配的全部注释

  file.uncomment:匹配的全部取消注释

#注释
salt '*' file.comment /root/test.sh Hostname
#取消注释
salt '*' file.uncomment /root/test.sh Hostname

  正则匹配和指定注释符号

案例一、
#以Hostname开头,以hostname结尾,注意如果中间有=号一定要用.代表,否则报错。
salt '*' file.comment  /root/test.sh Hostname.hostname

#后面也可以直接跟注释符号,默认#
salt '*' file.comment  /root/test.sh Hostname.hostname '!!!'

案例二、
#以Host开通,点表示任意符号,*表示匹配多次。以hostname结尾。
salt '*' file.comment  /root/test.sh Host.*hostname$
#你也可以后面表明用什么注释符号
salt '*' file.comment  /root/test.sh Host.*hostname$ '@'

  注意:

  1、以什么方式注释,必须一什么方式去掉注释(注释直接在comment前加un即可)。

  2、注释或消除注释,都会生成一个bak文件。你更改后最多只能反悔一次,因为bak文件只保存最后一次更改的状态。

 2.3.5 file.copy用法(复制文件或目录到指定的目录下面,成功返回True,失败会有提示的。另外还有file.move,移动文件的用法。)

  复制单个文件

#类似cp命令,目标必须指定文件名
salt '*' file.copy /root/test.sh  /var/test.sh

  复制整个目录下的文件,下面是将整个root目录下的放到/var/test/目录下

#需要加上recurse=True参数,否则报错
salt '*' file.copy /root/   /var/test/ recurse=True

  复制整个目录,相当目标下没有root目录的话,直接新建,等于直接把源root整个目录连目录一起放到了/var/test/下,相当于添加。

  recurse=True

salt '*' file.copy /root/   /var/test/root/ recurse=True

  复制整个目录,相当目标下没有root目录的话,直接新建,等于直接把源root整个目录连目录一起放到了/var/test/下,比上面牛逼的是原来要是root目录下有东西直接给你先全部删除,再把源文件复制过来。相当于目标清楚所有,在添加。

  remove_existing=True

salt '*' file.copy /root/   /var/test/root/ recurse=True remove_existing=True

2.3.6 'file.directory_exists和file.dirname的用法(前者检查一个目录是否存在,后者取文件的路径)

例:
# salt "*" file.directory_exists /var/test  #/var/test 目录存在就会返回True,不存在就会返回False 

# salt "*" file.dirname  '/var/test/'  #取出来的结果是/var/test/,这就是末尾加/,认为这两个都是目录,当然不管是否有这个目录

# salt "*" file.dirname  '/var/test/test.sh #取出来的结果是/var/test,但如果你在test.sh后面加上/,返回结果就是/var/test/test.sh

2.3.7 file.find方法(类似于linux下面的find命令)

  #salt '*' file.find / type=f name=\*.bak size=+10m  #查找/目录下,文件类型为文件的(a:所有文件类型,b:块设备 ,c:字符设备,d:目录, p:FIFO(命名管道), f:普通文件 ,l:符号链接 ,s:套接字),名称为.bak结尾的(这里支持正则表达式),大小大于10MB的文件(b:字节,k:千字节,m:兆字节,g:GB,t:太字节也是TB)。

  #salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime  #这里是查找/var目录下,最后一次更改时间是30天以前(w:周,d:天,h:小时,
m:分钟,s:秒),大小大于10MB的文件,并打印文件的路径,大小,更改时间(可打印的内容有:group:组名,md5:文件内容的MD5摘要,mode:文件权限(以整数形式),mtime:最后修改时间,name:文件基础名称,path:文件绝对路径,size:文件大小(以字节为单位),type:文件类型,user:用户名)。
  #salt '*' file.find /var/log name=\*.[0-9] mtime=+30d size=+10m delete   #find的匹配条件有(name区分大小写,iname不区分大小写,type类型,user用户,group用户组,size[+-]大小,mtime修改时间,grep搜索文件内容),最后执行的动作除了delete和print,还有exec command。

 2.3.8 file.get_gid、file.get_uid 和file.get_group、file.get_user的用法(前一组返回文件或目录的gid号和uid号,后一组返回文件或目录group和user)

# salt '*' file.get_user /etc  #查看/etc目录的属组,如果文件或目录不存在返回ERROR: Path not found:。

# salt '*' file.get_uid /etc  #查看/etc目录的属组的uid号。如果目录或者文件不存在返回ERROR: Path not found:.
2.3.9 file.grep的用法(类似于linux上面的grep命令)

# salt '*' file.grep /etc/passwd nobody  #过滤/ect/passwd文件中包含nobody的行。(会输出:pid:是grep运行的pid号,retcode:为状态码,0是成功过滤1为非成功过滤,stderr:错误输出,stdout:正常输出也就是我们要过滤的内容。)

# salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-ens33 ipaddr " -i"  #“-i”的目的是不区分大小写,注意-i前面有空格,额外的参数之间都有空格。


#salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-ens33 ipaddr  ' -i' ' -B2'  ' -A2' #-B2是上面两行,-A2指下面两行。注意,写法是,每个参数必须用单引号或双引号分开,而且每个参数开头需要用空格隔开。或者按照官方介绍下面的写法。


#salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-ens33 ipaddr  -- -i -B2 -A2   #开头用两个-- 然后每个参数前加一个-,每个参数之间用空格分开

2.3.10 file.link和file.symlink的用法(前者是创建文件的硬链接,后者是创建符号链接也就是软链接)

例:

# salt '*' file.link /tmp/1 /tmp/2  #为/tmp/1创建一个硬链接是/tmp/2,只能是文件。

#salt '*' file.symlink /tmp/1 /tmp/2 #成功返回True,失败返回ERROR

2.3.11 file.mkdir和file.makedirs方法(两种都是创建目录。前者类似于mkdir -p,后者只是madir)

成功后返回True,失败返回None,类似于mkdir -p
#salt '*' file.mkdir /opt/cs/ds 

#成功返回True,失败返回None,类似于直接建目录mkdir
#salt '*' file.makedirs  /opt/cs/ds

2.3.12 file.remove、file.rmdir和file.rename用法(前者是删除文件或者目录,中间是删除目录但是目录一定要为空、后者是重命名文件或目录)

# salt '*' file.remove /opt/cs/  #删除/opt目录下面的cs目录

# salt '*' file.rmdir /opt/cs  #删除/opt/cs目录,如果cs目录下面有内容会提示目录不会空删除失败提示Directory not empty,如果为空则会执行并返回True

#salt '*' file.rename  /opt/cs /opt/ds #将/opt下的cs目录改名为ds成功返回True,失败报错,文件和目录都可操作。

2.3.13 file.touch和file.truncate的用法

# salt '*' file.touch /opt/test #文件不存在则创建此文件,如果文件存在里面的内容不会发生变化,但是它的time信息会更新,上级目录必须存在。

# salt '*' file.truncate /opt/test 3  #将/opt/test 第三个字符以后的内容全删除掉了,字符的顺序意思是操作到右,从上到下。

#salt '*' sys.doc hosts #通过这个命令可以查看详细用法,我们生产中如果没有用内建DNS服务,使用hosts模块修改/etc/hosts还是经常会用到的。

#salt "*" hosts.add_host 172.16.5.240 salt-miniontow #添加一条host记录方便幻想解析,如果有就直接追加,如果没有就添加。

#salt '*' hosts.set_host 172,.16.5.239  foreman.puppet  #感觉这个条用的比较多,他是以IP地址为准,有这个IP的解析就覆盖,没有就添加。


#salt "*"  hosts.rm_host  172.16.5.239 salt-minion #删除一条172.16.5.239 salt-minion解析记录

#salt "*"  hosts.get_ip  salt-minion  #查看name叫salt-minion的ip地址。

#salt "*"  hosts.get_alias  172.16.5.239  #查看解析为172.16.5.239ip地址的name。

#salt '*' hosts.list_hosts  #查看指定minion下的所有解析。

#salt '*' hosts.has_pair 172.16.5.240 salt-miniontow #查看hosts里面有没有这条解析,有返回True,没有返回False

2.5 cron模块的常用使用方法

2.5.1 cron.raw_cron的用法(cron.list_tab和cron.ls和跟其效果一样,格式也一样必须要指定某一个用户,都是显示指定用户crontab文件里面的定时任务)

# salt '*' cron.raw_cron root  #必须指定用户,这里是显示root的crontab文件里面的内容,注释的行也会显示

2.5.2 cron.set_job的用法(为指定用户设置一个定时任务)

# salt '*' cron.set_job root '0' '0' '*' '*' '*' '/bin/bash /opt/scripts/scp.sh >/dev/null 2>&1'  #如果'/bin/bash /opt/scripts/scp.sh >/dev/null 2>&1'这一部分存在了,那么这一步操作就是update,也就是更新前面执行crontab的时间,如果不存在,这就相当于一条添加定时任务的操作返回内容为new。

2.5.3 cron.rm_job的用法(删除指定用户指定的的定时任务)

# salt '*' cron.rm_job root '/bin/bash /opt/scripts/scp.sh >/dev/null 2>&1'   #注意格式是用户 后面跟要删除的任务,不要加前面的时间,成功会返回removed,如果没有这条记录会返回absent。

 2.6 network模块的常用使用方法

#salt '*' network.get_hostname  #返回minion的主机名

# salt '*' network.hw_addr ens33#返回指定网络接口的mac地址

# salt '*' network.in_subnet 172.16.5.0/24  #查看主机在某个子网内就返回True,如果不在的话就返回False,多子网用空格隔开。

# salt '*' network.ip_addrs #查看minion端绑定的IP地址,多IP也会显示出来,127.0.0.1除外。(#salt '*' network.interfaces会显示所有接口的详细信息,但是别名的网卡类似于eth0:1这种不会显示。)

# salt '*' network.interface_ip ens33#显示指定网卡接口上面的IP,只会显示IP不会显示其他内容。(network.interface会连网关子网掩码也显示,跟前面的salt '*' salt '*' network.ip_addrs很相似)

# salt 'dasha_ceshi_172.16.5.239' network.mod_hostname  minion_test #修改某一个minion的主机名,显然这一步操作只适合在初始化的时候而且不适合执行所有主机。

# salt '*' network.ping www.baidu.com return_boolean=True timeout=3 #如果不加return_boolean=True显示的是ping的结果信息,加了就是如果ping通了就返回True,ping不通就返回False。timeout=3就是ping的时间,3秒超时这样能快速返回结果。这个其实挺好用的,比如我们可以测试哪些主机的DNS设置有问题不能正常解析啊,或者是我们内网DNS指向了一个非公网的域名解析,可以通过这个看哪些主机设置了内网DNS而哪些没设置内网DNS。

#salt '*' network.subnets #返回主机所属的子网

2.7 sys模块的常用使用方法

2.7.1 sys.argspec的用法(返回Salt执行模块中函数的参数说明。对于我们后期写.sls文件很有帮助)

#salt '*' sys.argspec pkg.install  #查看pkg.install函数的参数说明
#salt '*' sys.argspec sys   #查看sys模块里面所有函数的规则说明,或者#salt '*' sys.argspec 'sys.*'

2.7.2 sys.doc的用法(显示模块下函数的使用文档信息类似于man帮助,前面已介绍过,多模块或者多函数之间用空格隔开)

2.7.3 sys.list_functions和sys.list_modules的用法(前者就是列出所有模块下面的函数,多模块也是用空格隔开。后者是将所有模块列出来.)

# salt '*' sys.list_functions 'sys.list_*'  #可以用这种方法将所有sys.list开头的函数列出来。

# salt '*' sys.list_modules #列出所有的模块

# salt '*' sys.list_modules 's*' #列出所有以s开头的模块。

2.8 service模块的常用使用方法

#salt '*' service.available sshd  #查看某个命令的服务是否可用,这里是查看sshd服务是否可用,可用返回True,不可用返回False.

# salt '*' service.disable postfix  #禁止某个服务开机启动,这里是禁止postfix服务开机启动,成功返回True。

# salt '*' service.disabled postfix #查看某个服务是否已经开机不启动,这里是以postfix服务为例,开机不启动返回True,否则返回False.

# salt '*' service.enable postfix  #设置某个服务开机启动,这里以postfix为例

# salt '*' service.enabled postfix #查看某个服务是否开机启动,这里以postfix服务为例,开机启动返回True,否则False。

# salt '*' service.get_all #查看所有的服务项

# salt '*' service.get_enabled #查看所有开机启动的服务

# salt '*' service.reload <service name> #重新加载指定名称的服务

# salt '*' service.restart <service name> #重新启动指定名称的服务

# salt '*' service.start <service name>  #启动指定名称的服务

# salt '*' service.status <service name> #查看指定服务的状态,启动状态是True,关闭状态是False。

# salt '*' service.stop <service name> #关闭指定名称的服务

2.9 pkg模块的常用使用方法

2.9.1 pkg.install的用法(安装传递的包,在安装包之前,添加refresh = True来清理yum数据库。)

参数介绍:

name:要安装的软件包的名称。如果传递了“pkgs”或“sources“”此参数则会被忽略

# salt '*' pkg.install httpd  #如这就相当于在minion端执行yum install httpd -y操作

# salt '*' pkg.install httpd refresh=True  #如果是第一个yum的话,还是可以refresh参数,相当于yum clean all操作。

skip_verify:跳过GPG验证检查

version:安装包的特定版本

fromrepo:指定从哪个repo库来安装软件。

pkgs : 指定多个软件包,一定是要以列表传递。

#salt '*' pkg.install pkgs='["foo", "bar"]'

#salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4.el5"}]'

sources:要安装的RPM软件包列表。 其中的键是包名称,值作为包的源URI或本地路径。

#salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'

2.9.2 pkg.latest_version的用法(更新软件包至最新版本)

#salt '*' pkg.latest_version <package name>  #更新指定的软件包
#salt '*' pkg.latest_version <package name> fromrepo=epel-testing  #指定repo源来更新软件包

#salt '*' pkg.latest_version <package1> <package2> <package3> ...  #多个要更新的软件之间用空格隔开

2.9.3 pkg.remove的用法(删除软件的操作)

# salt '*' pkg.remove <package name>  #卸载指定的软件
# salt '*' pkg.remove <package1>,<package2>,<package3>  #多软件可以用空格隔开
# salt '*' pkg.remove pkgs='["foo", "bar"]'  #也可以用pkgs使用python列表的形式

2.9.4 salt '*' pkg.version的用法(查看软件的版本)

# salt '*' pkg.version <package name>  #查看指定软件的版本号
#  salt '*' pkg.version <package1> <package2> <package3> ...  #查看多软件版本号

posted @ 2018-06-20 08:06  Charles.L  阅读(709)  评论(0)    收藏  举报