saltstack常用模块

saltstack常用模块

SaltStack模块介绍

Module是日常使用SaltStack接触最多的一个组件,其用于管理对象操作,这也是SaltStack通过Push的方式进行管理的入口,比如我们日常简单的执行命令、查看包安装情况、查看服务运行情况等工作都是通过SaltStack Module来实现的。

当安装好Master和Minion包后,系统上会安装很多Module,大家可以通过以下命令查看支持的所有Module列表:

//查看所有module列表
[root@master ~]# salt 'node1' sys.list_modulesnode1:
    - acl
    - aliases
    - alternatives
    - apache
    - archive
    - artifactory
    - baredoc
    - beacons
    - bigip
    - btrfs
    - buildout
    - chroot
    - cloud
    - cmd
    - composer
    - config
    - consul
    - container_resource
    - cp
    - cron
    - cryptdev
    - data
    - defaults
    - devinfo
    - devmap
    - disk
    - django
    - dnsmasq
    - dnsutil
    - drbd
    - environ
    - ethtool
    - event
    - extfs
    - file
    - firewalld
    - freezer
    - gem
    - genesis
    - glassfish
    - gnome
    - google_chat
    - grafana4
    - grains
    - group
    - hashutil
    - helm
    - highstate_doc
    - hosts
    - http
    - hue
    - incron
    - ini
    - inspector
    - introspect
    - iosconfig
    - ip
    - ipset
    - iptables
    - jboss7
    - jboss7_cli
    - jinja
    - k8s
    - kernelpkg
    - key
    - keyboard
    - kmod
    - kubeadm
    - locale
    - locate
    - log
    - logrotate
    - lowpkg
    - lvm
    - mandrill
    - match
    - mattermost
    - mine
    - minion
    - modjk
    - mount
    - msteams
    - nagios_rpc
    - namecheap_domains
    - namecheap_domains_dns
    - namecheap_domains_ns
    - namecheap_ssl
    - namecheap_users
    - network
    - nexus
    - nftables
    - nova
    - nspawn
    - nxos
    - nxos_api
    - nxos_upgrade
    - openscap
    - openstack_config
    - opsgenie
    - out
    - pagerduty
    - pagerduty_util
    - pam
    - parallels
    - partition
    - peeringdb
    - pillar
    - pip
    - pkg
    - pkg_resource
    - ps
    - publish
    - pushover
    - pyenv
    - random
    - random_org
    - rbenv
    - rest_sample_utils
    - restartcheck
    - ret
    - rvm
    - s3
    - s6
    - salt_proxy
    - salt_version
    - 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
    - tls
    - travisci
    - tuned
    - udev
    - uptime
    - user
    - vault
    - vbox_guest
    - virtualenv
    - vsphere
    - webutil
    - x509
    - xfs
    - xml
    - zabbix
    - zenoss


//查看指定module的所有function
[root@master ~]# salt 'node1' sys.list_functions cmd
node1:
    - 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


//查看指定module的用法
[root@master ~]# salt 'node1' sys.doc cmd
cmd.exec_code:

    Pass in two strings, the first naming the executable language, aka -
    python2, python3, ruby, perl, lua, etc. the second string containing
    the code you wish to execute. The stdout will be returned.

    All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.

    CLI Example:
......


//SaltStack默认也支持一次执行多个Module,Module之间通过逗号隔开,默认传参之间也是用逗号分隔,也支持指定传参分隔符号--args-separator=@即可
[root@master ~]# salt 'node1' test.echo,cmd.run,service.status hello,date,httpd
node1:
    ----------
    cmd.run:
        Thu Nov  4 08:46:05 CST 2021
    service.status:
        True
    test.echo:
        hello

SaltStack常用模块

SaltStack常用模块之network

network.active_tcp

返回所有活动的tcp连接

[root@master ~]# salt "*" network.active_tcp
node1:
    ----------
    0:
        ----------
        local_addr:
            192.168.172.143
        local_port:
            22
        remote_addr:
            192.168.172.1
        remote_port:
            57518
    1:
        ----------
        local_addr:
            192.168.172.143
        local_port:
            38734
        remote_addr:
            192.168.172.142
        remote_port:
            4505
master:
    ----------
    0:
        ----------
        local_addr:
            192.168.172.142
        local_port:
            22
        remote_addr:
            192.168.172.1
        remote_port:
            57516
    1:
        ----------
        local_addr:
            192.168.172.142
        local_port:
            4505
        remote_addr:
            192.168.172.142
        remote_port:
            44538
    2:
        ----------
        local_addr:
            192.168.172.142
        local_port:
            44538
        remote_addr:
            192.168.172.142
        remote_port:
            4505
    3:
        ----------
        local_addr:
            192.168.172.142
        local_port:
            4505
        remote_addr:
            192.168.172.143
        remote_port:
            38734

network.calc_net

通过IP和子网掩码计算出网段

[root@master ~]# salt node1  network.calc_net 192.168.1.0 255.255.255.0
node1:
    192.168.1.0/24
[root@master ~]# salt node1  network.calc_net 192.168.1.0 255.255.254.0
node1:
    192.168.0.0/23

network.connect

测试minion至某一台服务器的网络是否连通

[root@master ~]# salt node1 network.connect 192.168.172.142 22
node1:
    ----------
    comment:
        Successfully connected to 192.168.172.142 (192.168.172.142) on tcp port 22
    result:
        True

network.default_route

查看默认路由

[root@master ~]# salt node1 network.default_route
node1:
    |_
      ----------
      addr_family:
          inet
      destination:
          0.0.0.0
      flags:
          UG
      gateway:
          192.168.172.2
      interface:
          ens160
      netmask:
          0.0.0.0

network.get_fqdn

查看主机的fqdn(完全限定域名)

[root@master ~]# salt '*' network.get_fqdn
master:
    master
node1:
    node1

network.get_hostname

获取主机名

[root@master ~]# salt '*' network.get_hostname
node1:
    node1
master:
    master

network.get_route

查询到一个目标网络的路由信息

[root@master ~]# salt 'node1' network.get_route 192.168.111.23
node1:
    ----------
    destination:
        192.168.111.23
    gateway:
        192.168.172.2
    interface:
        ens160
    source:
        192.168.172.143

network.hw_addr

返回指定网卡的MAC地址

[root@master ~]# salt node1 network.hw_addr ens160
node1:
    00:0c:29:db:3c:14

network.ifacestartswith

从特定CIDR检索接口名称

[root@master ~]# salt node1 network.ifacestartswith 127.0
node1:
    - lo
[root@master ~]# salt node1 network.ifacestartswith 192.168
node1:
    - ens160

network.in_subnet

判断当前主机是否在某一个网段内

[root@master ~]# salt 'node1' network.in_subnet 192.168.172.0/24
node1:
    True
[root@master ~]# salt 'node1' network.in_subnet 192.168.174.0/24
node1:
    False

network.interface

返回指定网卡的信息

[root@master ~]# salt node1 network.interface ens160
node1:
    |_
      ----------
      address:
          192.168.172.143
      broadcast:
          192.168.172.255
      label:
          ens160
      netmask:
          255.255.255.0

network.interface_ip

返回指定网卡的IP地址

[root@master ~]# salt node1 network.interface_ip ens160 
node1:
    192.168.172.143

network.interfaces

返回当前系统中所有的网卡信息

[root@master ~]# salt node1 network.interfaces
node1:
    ----------
    ens160:
        ----------
        hwaddr:
            00:0c:29:db:3c:14
        inet:
            |_
              ----------
              address:
                  192.168.172.143
              broadcast:
                  192.168.172.255
              label:
                  ens160
              netmask:
                  255.255.255.0
        inet6:
            |_
              ----------
              address:
                  fe80::20c:29ff:fedb:3c14
              prefixlen:
                  64
              scope:
                  link
        up:
            True
    lo:
        ----------
        hwaddr:
            00:00:00:00:00:00
        inet:
            |_
              ----------
              address:
                  127.0.0.1
              broadcast:
                  None
              label:
                  lo
              netmask:
                  255.0.0.0
        inet6:
            |_
              ----------
              address:
                  ::1
              prefixlen:
                  128
              scope:
                  host
        up:
            True

network.ip_addrs

返回一个IPv4的地址列表
该函数将会忽略掉127.0.0.1的地址

[root@master ~]# salt node1 network.ip_addrsnode1:
    - 192.168.172.143

network.netstat

返回所有打开的端口和状态

[root@master ~]# salt node1 network.netstat
node1:
    |_
      ----------
      inode:
          27302
      local-address:
          0.0.0.0:22
      program:
          sshd
      proto:
          tcp
      recv-q:
          0
      remote-address:
          0.0.0.0:*
      send-q:
          128
      state:
          LISTEN
      user:
          0
    |_
      ----------
      inode:
          1244531
      local-address:
          192.168.172.143:22
      program:
          sshd
      proto:
          tcp
      recv-q:
          0
      remote-address:
          192.168.172.1:57518
      send-q:
          0
      state:
          ESTABLISHED
      user:
          0
    |_
      ----------
      inode:
          171847
      local-address:
          192.168.172.143:38734
      program:
          salt-minion
      proto:
          tcp
      recv-q:
          0
      remote-address:
          192.168.172.142:4505
      send-q:
          0
      state:
          ESTABLISHED
      user:
          0
    |_
      ----------
      inode:
          0
      local-address:
          192.168.172.143:51752
      program:
      proto:
          tcp
      recv-q:
          0
      remote-address:
          192.168.172.142:4506
      send-q:
          0
      state:
          TIME-WAIT
      user:
          0
    |_
      ----------
      inode:
          0
      local-address:
          192.168.172.143:51754
      program:
      proto:
          tcp
      recv-q:
          0
      remote-address:
          192.168.172.142:4506
      send-q:
          0
      state:
          TIME-WAIT
      user:
          0
    |_
      ----------
      inode:
          27312
      local-address:
          [::]:22
      program:
          sshd
      proto:
          tcp
      recv-q:
          0
      remote-address:
          [::]:*
      send-q:
          128
      state:
          LISTEN
      user:
          0
    |_
      ----------
      inode:
          28127
      local-address:
          *:80
      program:
          httpd
      proto:
          tcp
      recv-q:
          0
      remote-address:
          *:*
      send-q:
          128
      state:
          LISTEN
      user:
          0

network.ping

使用ping命令测试到某主机的连通性

[root@master ~]# salt node1 network.ping 192.168.172.142
node1:
    PING 192.168.172.142 (192.168.172.142) 56(84) bytes of data.
    64 bytes from 192.168.172.142: icmp_seq=1 ttl=64 time=0.394 ms
    64 bytes from 192.168.172.142: icmp_seq=2 ttl=64 time=0.497 ms
    64 bytes from 192.168.172.142: icmp_seq=3 ttl=64 time=0.298 ms
    64 bytes from 192.168.172.142: icmp_seq=4 ttl=64 time=0.239 ms
    
    --- 192.168.172.142 ping statistics ---
    4 packets transmitted, 4 received, 0% packet loss, time 93ms
    rtt min/avg/max/mdev = 0.239/0.357/0.497/0.097 ms

network.reverse_ip

返回一个指定的IP地址的反向地址

[root@master ~]# salt node1 network.reverse_ip 192.168.172.142
node1:
    142.172.168.192.in-addr.arpa

SaltStack常用模块之service

service.available

判断指定的服务是否可用

[root@master ~]# salt node1 service.available httpd
node1:
    True
[root@master ~]# salt node1 service.available nginx
node1:
    False

service.get_all

获取所有正在运行的服务

[root@master ~]# salt node1 service.get_all
node1:
    - NetworkManager
    - NetworkManager-dispatcher
    - NetworkManager-wait-online
    - auditd
    - autovt@
    - basic.target
    - blk-availability
    - bluetooth.target
    - console-getty
    - container-getty@
    - cpupower
    - crond
    - cryptsetup-pre.target
    - cryptsetup.target
    - ctrl-alt-del.target
    - dbus
    - dbus-org.freedesktop.hostname1
    - dbus-org.freedesktop.locale1
    - dbus-org.freedesktop.login1
    - dbus-org.freedesktop.nm-dispatcher
    - dbus-org.freedesktop.portable1
    - dbus-org.freedesktop.timedate1
    - dbus.socket
    - debug-shell
    - default.target
    - dev-hugepages.mount
    - dev-mqueue.mount
    - dm-event
    - dm-event.socket
    - dnf-makecache
    - dnf-makecache.timer
    - dracut-cmdline
    - dracut-initqueue
    - dracut-mount
    - dracut-pre-mount
    - dracut-pre-pivot
    - dracut-pre-trigger
    - dracut-pre-udev
    - dracut-shutdown
    - ebtables
    - emergency
    - emergency.target
    - exit.target
    - final.target
    - firewalld
    - fstrim
    - fstrim.timer
    - getty-pre.target
    - getty.target
    - getty@
    - graphical.target
    - grub-boot-indeterminate
    - halt-local
    - halt.target
    - hibernate.target
    - htcacheclean
    - httpd
    - httpd.socket
    - httpd@
    - hybrid-sleep.target
    - import-state
    - initrd-cleanup
    - initrd-fs.target
    - initrd-parse-etc
    - initrd-root-device.target
    - initrd-root-fs.target
    - initrd-switch-root
    - initrd-switch-root.target
    - initrd-udevadm-cleanup-db
    - initrd.target
    - iprdump
    - iprinit
    - iprupdate
    - iprutils.target
    - irqbalance
    - kdump
    - kexec.target
    - kmod-static-nodes
    - ldconfig
    - loadmodules
    - local-fs-pre.target
    - local-fs.target
    - lvm2-lvmpolld
    - lvm2-lvmpolld.socket
    - lvm2-monitor
    - lvm2-pvscan@
    - man-db-cache-update
    - messagebus
    - microcode
    - multi-user.target
    - network-online.target
    - network-pre.target
    - network.target
    - nftables
    - nis-domainname
    - nss-lookup.target
    - nss-user-lookup.target
    - paths.target
    - plymouth-halt
    - plymouth-kexec
    - plymouth-poweroff
    - plymouth-quit
    - plymouth-quit-wait
    - plymouth-read-write
    - plymouth-reboot
    - plymouth-start
    - plymouth-switch-root
    - polkit
    - poweroff.target
    - printer.target
    - proc-sys-fs-binfmt_misc.automount
    - proc-sys-fs-binfmt_misc.mount
    - quotaon
    - rc-local
    - rdisc
    - reboot.target
    - remote-cryptsetup.target
    - remote-fs-pre.target
    - remote-fs.target
    - rescue
    - rescue.target
    - rhnsd
    - rhsm
    - rhsm-facts
    - rhsmcertd
    - rngd
    - rngd-wake-threshold
    - rpcbind.target
    - rsyslog
    - runlevel0.target
    - runlevel1.target
    - runlevel2.target
    - runlevel3.target
    - runlevel4.target
    - runlevel5.target
    - runlevel6.target
    - salt-minion
    - salt-proxy@
    - selinux-autorelabel
    - selinux-autorelabel-mark
    - selinux-autorelabel.target
    - serial-getty@
    - shutdown.target
    - sigpwr.target
    - sleep.target
    - slices.target
    - smartcard.target
    - sockets.target
    - sound.target
    - sshd
    - sshd-keygen.target
    - sshd-keygen@
    - sshd.socket
    - sshd@
    - sssd
    - sssd-autofs
    - sssd-autofs.socket
    - sssd-kcm
    - sssd-kcm.socket
    - sssd-nss
    - sssd-nss.socket
    - sssd-pac
    - sssd-pac.socket
    - sssd-pam
    - sssd-pam-priv.socket
    - sssd-pam.socket
    - sssd-ssh
    - sssd-ssh.socket
    - sssd-sudo
    - sssd-sudo.socket
    - suspend-then-hibernate.target
    - suspend.target
    - swap.target
    - sys-fs-fuse-connections.mount
    - sys-kernel-config.mount
    - sys-kernel-debug.mount
    - sysinit.target
    - syslog
    - syslog.socket
    - system-update-cleanup
    - system-update-pre.target
    - system-update.target
    - systemd-ask-password-console
    - systemd-ask-password-console.path
    - systemd-ask-password-plymouth
    - systemd-ask-password-plymouth.path
    - systemd-ask-password-wall
    - systemd-ask-password-wall.path
    - systemd-backlight@
    - systemd-binfmt
    - systemd-coredump.socket
    - systemd-coredump@
    - systemd-exit
    - systemd-firstboot
    - systemd-fsck-root
    - systemd-fsck@
    - systemd-halt
    - systemd-hibernate
    - systemd-hibernate-resume@
    - systemd-hostnamed
    - systemd-hwdb-update
    - systemd-hybrid-sleep
    - systemd-initctl
    - systemd-initctl.socket
    - systemd-journal-catalog-update
    - systemd-journal-flush
    - systemd-journald
    - systemd-journald-audit.socket
    - systemd-journald-dev-log.socket
    - systemd-journald.socket
    - systemd-kexec
    - systemd-localed
    - systemd-logind
    - systemd-machine-id-commit
    - systemd-modules-load
    - systemd-portabled
    - systemd-poweroff
    - systemd-quotacheck
    - systemd-random-seed
    - systemd-reboot
    - systemd-remount-fs
    - systemd-resolved
    - systemd-rfkill
    - systemd-rfkill.socket
    - systemd-suspend
    - systemd-suspend-then-hibernate
    - systemd-sysctl
    - systemd-sysusers
    - systemd-timedated
    - systemd-tmpfiles-clean
    - systemd-tmpfiles-clean.timer
    - systemd-tmpfiles-setup
    - systemd-tmpfiles-setup-dev
    - systemd-udev-settle
    - systemd-udev-trigger
    - systemd-udevd
    - systemd-udevd-control.socket
    - systemd-udevd-kernel.socket
    - systemd-update-done
    - systemd-update-utmp
    - systemd-update-utmp-runlevel
    - systemd-user-sessions
    - systemd-vconsole-setup
    - systemd-volatile-root
    - tcsd
    - teamd@
    - time-sync.target
    - timers.target
    - tmp.mount
    - tuned
    - umount.target
    - unbound-anchor
    - unbound-anchor.timer
    - user-runtime-dir@
    - user@
    - vgauthd
    - vmtoolsd

service.disabled

检查指定服务是否开机不自动启动

[root@master ~]# salt master service.disabled firewalld
master:
    True

service.enabled

检查指定服务是否开机自动启动

[root@master ~]# salt node1 service.enabled httpd
node1:
    True

service.disable

设置指定服务开机不自动启动

[root@master ~]# salt node1 service.disable httpd
node1:
    True
[root@master ~]# salt node1 service.enabled httpd
node1:
    False

service.enable

设置指定服务开机自动启动

[root@master ~]# salt node1 service.enable httpd
node1:
    True
[root@master ~]# salt node1 service.enabled httpd
node1:
    True

service.reload

重新加载指定服务

[root@master ~]# salt node1 service.reload httpd
node1:
    True

service.stop

停止指定服务

[root@master ~]# salt node1 service.stop httpd
node1:
    True

service.start

启动指定服务

[root@master ~]# salt node1 service.start httpd
node1:
    True

service.restart

重启指定服务

[root@master ~]# salt node1 service.restart httpd
node1:
    True

service.status

查看指定服务的状态

[root@master ~]# salt node1 service.status httpd
node1:
    True

SaltStack常用模块之pkg

pkg.download

只下载软件包但不安装
此功能将会下载指定的软件包,但是需要在minion端安装yum-utils,可以使用 cmd.run 进行远程安装

[root@master ~]# salt node1 pkg.download nginx
node1:
    ----------
    nginx:
        /var/cache/yum/packages/nginx-1.14.1-9.module+el8.0.0+4108+af250afe.x86_64.rpm      #下载好的软件放在这里

pkg.file_list

列出指定包或系统中已安装的所有包的文件

//列出已安装的apache软件包提供的所有文件
[root@master ~]# salt node1 pkg.file_list httpd
node1:
    ----------
    errors:
    files:
        - /etc/httpd/conf
        - /etc/httpd/conf.d/autoindex.conf
        - /etc/httpd/conf.d/userdir.conf
        - /etc/httpd/conf.d/welcome.conf
        - /etc/httpd/conf.modules.d
        - /etc/httpd/conf.modules.d/00-base.conf
        - /etc/httpd/conf.modules.d/00-dav.conf
        - /etc/httpd/conf.modules.d/00-lua.conf
        - /etc/httpd/conf.modules.d/00-mpm.conf
        - /etc/httpd/conf.modules.d/00-optional.conf
        - /etc/httpd/conf.modules.d/00-proxy.conf
        - /etc/httpd/conf.modules.d/00-systemd.conf
        - /etc/httpd/conf.modules.d/01-cgi.conf
        - /etc/httpd/conf.modules.d/README
        - /etc/httpd/conf/httpd.conf
        - /etc/httpd/conf/magic
......

//当不提供参数时,将会列出当前系统中所有已安装软件的文件列表
[root@master ~]# salt node1 pkg.file_list 
node1:
    ----------
    errors:
    files:
        VALUE_TRIMMED

pkg.group_info

查看包组的信息

[root@master ~]# salt node1 pkg.group_info 'Development Tools'
node1:
    ----------
    conditional:
    default:
        - asciidoc
        - byacc
        - ctags
        - diffstat
        - git
        - intltool
        - jna
        - ltrace
        - patchutils
        - perl-Fedora-VSP
        - perl-generators
        - pesign
        - source-highlight
        - systemtap
        - valgrind
        - valgrind-devel
    description:
        A basic development environment.
    group:
        Development Tools
    id:
        None
    mandatory:
        - autoconf
        - automake
        - binutils
        - bison
        - flex
        - gcc
        - gcc-c++
        - gdb
        - glibc-devel
        - libtool
        - make
        - pkgconf
        - pkgconf-m4
        - pkgconf-pkg-config
        - redhat-rpm-config
        - rpm-build
        - rpm-sign
        - strace
    optional:
        - cmake
        - expect
        - rpmdevtools
        - rpmlint
    type:
        package group

pkg.group_list

列出系统中所有的包组

[root@master ~]# salt node1 pkg.group_list
node1:
    ----------
    available:
        - Backup Client
        - base-x
        - Conflicts AppStream
        - Container Management
        - Debugging Tools
        - Desktop Debugging and Performance Tools
        - .NET Core Development
        - FTP Server
        - GNOME Applications
        - Graphics Creation Tools
        - Guest Agents
        - Guest Desktop Agents
        - Input Methods
        - Internet Applications
        - Internet Browser
        - Java Platform
        - Legacy X Window System Compatibility
        - Multimedia
        - Office Suite and Productivity
        - Atomic Host ostree support
        - KVM platform specific packages
        - Hyper-v platform specific packages
        - Printing Client
        - Remote Desktop Clients
        - RPM Development Tools
        - TeX formatting system
        - Virtualization Client
        - Virtualization Hypervisor
        - Virtualization Platform
        - Virtualization Tools
        - Basic Web Server
        - Additional Development
        - Anaconda tools
        - Base
        - Conflicts BaseOS
        - Development Tools
        - Dial-up Networking Support
        - File and Storage Server
        - Fonts
        - GNOME
        - Graphical Administration Tools
        - Hardware Monitoring Utilities
        - Hardware Support
        - Headless Management
        - Infiniband Support
        - Large Systems Performance
        - Legacy UNIX Compatibility
        - Mail Server
        - Mainframe Access
        - Network File System Client
        - Network Servers
        - Networking Tools
        - Common NetworkManager submodules
        - Performance Tools
        - Platform Development
        - Python Web
        - Remote Management for Linux
        - Scientific Support
        - Security Tools
        - Server product core
        - Smart Card Support
        - Windows File Server
        - Standard
        - System Tools
        - Workstation product core
    available environments:
        - Server with GUI
        - Server
        - Workstation
        - Virtualization Host
        - Custom Operating System
    available languages:
        ----------
    installed:
        - VMware platform specific packages
        - Core
    installed environments:
        - Minimal Install

pkg.install

安装软件

[root@master ~]# salt node1 pkg.install wget
node1:
    ----------
    wget:
        ----------
        new:
            1.19.5-8.el8_1.1
        old:

pkg.list_downloaded

列出已下载到本地的软件包
下载的软件包安装之后会自动删除

[root@master ~]# salt 'node1' pkg.list_downloaded
node1:
    ----------

pkg.list_pkgs

以字典的方式列出当前已安装的软件包

[root@master ~]# salt 'node1' pkg.list_pkgs
node1:
    ----------
    NetworkManager:
        1:1.22.8-4.el8
    NetworkManager-libnm:
        1:1.22.8-4.el8
    NetworkManager-team:
        1:1.22.8-4.el8
    NetworkManager-tui:
        1:1.22.8-4.el8
    acl:
        2.2.53-1.el8
    apr:
......

pkg.owner

列出指定文件是由哪个包提供的

[root@master ~]# salt 'node1' pkg.owner /usr/sbin/apachectl
node1:
    httpd
[root@master ~]# salt 'node1' pkg.owner /usr/sbin/apachectl /etc/httpd/conf/httpd.conf
node1:
    ----------
    /etc/httpd/conf/httpd.conf:
        httpd
    /usr/sbin/apachectl:
        httpd

pkg.remove

卸载指定软件

[root@master ~]# salt node1 cmd.run 'rpm -qa |grep wget'
node1:
    wget-1.19.5-8.el8_1.1.x86_64
[root@master ~]# salt node1 pkg.remove wget
node1:
    ----------
    wget:
        ----------
        new:
        old:
            1.19.5-8.el8_1.1
# 若要卸载多个文件,中间需要用逗号隔开

pkg.upgrade

升级系统中所有的软件包或升级指定的软件包

[root@master ~]# salt '*' pkg.upgrade name=openssl
master:
    ----------
    openssl:
        ----------
        new:
            1:1.0.2k-16.el7
        old:
            1:1.0.2k-8.el7
    openssl-libs:
        ----------
        new:
            1:1.0.2k-16.el7
        old:
            1:1.0.2k-8.el7
# 若想升级系统中所有的软件包则把 name 参数去掉即可

SaltStack常用模块之state

state.show_highstate

显示当前系统中有哪些高级状态

[root@master ~]# salt 'node1'  state.show_highstate 
node1:
    ----------
    apache-install:
        ----------
        __env__:
            base
        __sls__:
            web.apache.apache
        pkg:
            |_
              ----------
              name:
                  httpd
            - installed
            |_
              ----------
              order:
                  10000
    apache-service:
        ----------
        __env__:
            base
        __sls__:
            web.apache.apache
        service:
            |_
              ----------
              name:
                  httpd
            |_
              ----------
              enable:
                  True
            - running
            |_
              ----------
              order:
                  10001

state.highstate

执行高级状态

[root@master ~]# salt 'node1'  state.highstate  web.apache.apache
node1:
----------
          ID: apache-install
    Function: pkg.installed
        Name: httpd
      Result: True
     Comment: All specified packages are already installed
     Started: 14:46:43.126428
    Duration: 1215.254 ms
     Changes:   
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: None
     Comment: Service httpd is set to start
     Started: 14:46:44.345304
    Duration: 42.196 ms
     Changes:   

Summary for node1
------------
Succeeded: 2 (unchanged=1)
Failed:    0
------------
Total states run:     2
Total run time:   1.257 s

state.show_state_usage

显示当前系统中的高级状态执行情况

[root@master ~]# salt 'node1' state.show_state_usage
node1:
    ----------
    base:
        ----------
        count_all:
            2
        count_unused:
            1
        count_used:
            1
        unused:
            - top
        used:
            - web.apache.apache
    dev:
        ----------
        count_all:
            0
        count_unused:
            0
        count_used:
            0
        unused:
        used:
    prod:
        ----------
        count_all:
            0
        count_unused:
            0
        count_used:
            0
        unused:
        used:
    test:
        ----------
        count_all:
            0
        count_unused:
            0
        count_used:
            0
        unused:
        used:

state.show_top

返回minion将用于highstate的顶级数据

[root@master ~]# salt 'node1'  state.show_top 
node1:
    ----------
    base:
        - web.apache.apache

state.top

执行指定的top file,而不是默认的

[root@master ~]# salt 'node1'   state.top  test.sls
node1:
----------
          ID: apache-install
    Function: pkg.installed
        Name: httpd
      Result: True
     Comment: All specified packages are already installed
     Started: 14:52:15.677734
    Duration: 1218.272 ms
     Changes:   
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: True
     Comment: The service httpd is already running
     Started: 14:52:16.897131
    Duration: 35.889 ms
     Changes:   

Summary for node1
------------
Succeeded: 2
Failed:    0
------------
Total states run:     2
Total run time:   1.254 s

state.show_sls

显示 master 上特定sls或sls文件列表中的状态数据

[root@master ~]# salt '*'  state.show_sls  web.apache.apache
node1:
    ----------
    apache-install:
        ----------
        __env__:
            base
        __sls__:
            web.apache.apache
        pkg:
            |_
              ----------
              name:
                  httpd
            - installed
            |_
              ----------
              order:
                  10000
    apache-service:
        ----------
        __env__:
            base
        __sls__:
            web.apache.apache
        service:
            |_
              ----------
              name:
                  httpd
            |_
              ----------
              enable:
                  True
            - running
            |_
              ----------
              order:
                  10001

SaltStack常用模块之cp

#将被控主机的/etc/hosts文件复制到被控主机本地的salt cache目录(/var/cache/salt/minion/localfiles/)
salt '*' cp.cache_local_file /etc/hosts

#将主控端file_roots指定位置下的目录复制到被控主机/minion/目录下
salt '*' cp.get_dir salt://script/ /minion/

#将主控端file_roots指定位置下的文件复制到被控主机/minion/test.py文件(file为文件名)
salt '*' cp.get_dir salt://script/test.py /minion/test.py

#下载URL内容到被控主机指定位置(/tmp/index.html)
salt '*' cp.get_url http://www.slashdot.ort /tmp/index.html

SaltStack常用模块之user

user.add

在受控端上创建一个用户

[root@master ~]# salt node1 user.add xux
node1:
    True

[root@node1 ~]# id xux
uid=1000(xux) gid=1000(xux) groups=1000(xux)

user.info

返回用户信息。

[root@master ~]# salt node1 user.info xux
node1:
    ----------
    fullname:
    gid:
        1000
    groups:
        - xux
    home:
        /home/xux
    homephone:
    name:
        xux
    other:
    passwd:
        x
    roomnumber:
    shell:
        /bin/bash
    uid:
        1000
    workphone:

user.getent

返回所有系统用户信息的列表

[root@master ~]# salt node1 user.getent
node1:
    |_
      ----------
      fullname:
          root
      gid:
          0
      groups:
          - root
      home:
          /root
      homephone:
      name:

......

user.chgid

修改用户Gid

[root@node1 ~]# id xux
uid=1000(xux) gid=1000(xux) groups=1000(xux)

[root@master ~]# salt 'node1' user.chgid  xux 1020
node1:
    True

[root@node1 ~]# id xux
uid=1000(xux) gid=1020(xux) groups=1000(xux)

user.list_groups

列出指定用户所属组的列表

[root@master ~]# salt node1 user.list_groups xux
node1:
    - xux

user.list_users

返回所有用户的列表

[root@master ~]# salt node1 user.list_users
node1:
    - adm
    - apache
    - bin
    - daemon
    - dbus
    - ftp
    - games
    - halt
    - lp
    - mail
    - nobody
    - operator
    - polkitd
    - rngd
    - root
    - shutdown
    - sshd
    - sssd
    - sync
    - systemd-coredump
    - systemd-resolve
    - tss
    - unbound
    - xux

user.chshell

修改指定用户的登录shell

[root@master ~]# salt node1 user.chshell xux /sbin/nologin
node1:
    True

user.delete

删除用户

[root@master ~]# salt 'node1'  user.delete name=xux remove=True force=True
node1:
    True
[root@node1 ~]# id xux
id: 'xux': no such user

SaltStack常用模块之salt-cp

salt-cp能够很方便的把 master 上的文件批量传到 minion上

#拷贝单个文件到目标主机的/opt目录下
[root@master ~]# salt node1 cmd.run 'ls /root'
node1:
    a
    anaconda-ks.cfg
    b
    c
    test
[root@master ~]# salt-cp node1 /root/a /opt/
node1:
    ----------
	/opt/a:
        True

#拷贝多个文件到目标主机的/opt目录下
[root@master ~]# salt-cp 'node1' /root/b /root/c /opt/
node1:
    ----------
    /opt/b:
        True
    /opt/c:
        True
[root@master ~]# salt 'node1' cmd.run 'ls /opt/'
node1:
    a
    b
    c

SaltStack常用模块之file

file.access

检查指定路径是否存在

[root@master ~]# salt 'node1' cmd.run 'ls /root'
node1:
    a
    anaconda-ks.cfg
    b
    c
    test
[root@master ~]# salt 'node1' file.access /root/a f
node1:
    True
[root@master ~]# salt 'node1' file.access /root/bbb f
node1:
    False

检查指定文件的权限信息

[root@master ~]# salt 'node1' cmd.run 'ls -l  /root'
node1:
    total 4
    -rw-r--r--  1 root root    0 Nov  5 06:28 a
    -rw-------. 1 root root 1184 Jul 21 14:40 anaconda-ks.cfg
    -rw-r--r--  1 root root    0 Nov  5 06:28 b
    -rw-r--r--  1 root root    0 Nov  5 06:28 c
    drwxr-xr-x  2 root root    6 Nov  4 10:40 test
[root@master ~]# salt 'node1' file.access /root/anaconda-ks.cfg r		#是否有读权限
node1:
    True
[root@master ~]# salt 'node1' file.access /root/anaconda-ks.cfg w			#是否有写权限 
node1:
    True
[root@master ~]# salt 'node1' file.access /root/anaconda-ks.cfg x			#是否有执行权限
node1:
    False

file.append

往一个文件里追加内容,若此文件不存在则会报异常

[root@master ~]# salt node1 cmd.run 'ls -l /root/a'
node1:
    -rw-r--r-- 1 root root 0 Nov  5 06:28 /root/a
[root@master ~]# salt node1 file.append /root/a 'alone' 'above'
node1:
    Wrote 2 lines to "/root/a"
[root@master ~]# salt node1 cmd.run 'cat  /root/a'node1:
    alone
    above

file.basename

获取指定路径的基名

[root@master ~]# salt node1 file.basename '/usr/local/debug'
node1:
    debug

file.dirname

获取指定路径的目录名

[root@master ~]# salt node1 file.dirname '/usr/local/debug'
node1:
    /usr/local

file.check_hash

检查指定的文件与hash字符串是否匹配,匹配则返回 True 否则返回 False

[root@master ~]# salt node1 cmd.run 'md5sum /etc/passwd'
node1:
    b1cdb75c099e0af3ea528d0a07888fac  /etc/passwd
[root@master ~]# salt node1 file.check_hash /etc/passwd b1cdb75c099e0af3ea528d0a07888fac
node1:
    True

file.chattr

修改指定文件的属性

属性对文件的意义对目录的意义
a只允许在这个文件之后追加数据,
不允许任何进程覆盖或截断这个文件
只允许在这个目录下建立和修改文件,
而不允许删除任何文件
i不允许对这个文件进行任何的修改,
不能删除、更改、移动
任何的进程只能修改目录之下的文件,
不允许建立和删除文件

给指定文件添加属性

//查看当前属性
[root@master ~]# salt node1 cmd.run 'lsattr /root'
node1:
    -------------------- /root/anaconda-ks.cfg
    -------------------- /root/test
    -------------------- /root/a
    -------------------- /root/b
    -------------------- /root/c

//添加属性
[root@master ~]# salt node1 file.chattr /root/a operator=add attributes=ai
node1:
    True
[root@master ~]# salt node1 cmd.run 'lsattr /root/a'node1:
    ----ia-------------- /root/a
[root@master ~]# salt node1 file.append /root/a 'hello' 
node1:
    The minion function caused an exception: Traceback (most recent call last):
      File "/usr/lib/python3.6/site-packages/salt/minion.py", line 1912, in _thread_return
        function_name, function_args, executors, opts, data
      File "/usr/lib/python3.6/site-packages/salt/minion.py", line 1868, in _execute_job_function
        return_data = self.executors[fname](opts, data, func, args, kwargs)
      File "/usr/lib/python3.6/site-packages/salt/loader/lazy.py", line 149, in __call__
        return self.loader.run(run_func, *args, **kwargs)
      File "/usr/lib/python3.6/site-packages/salt/loader/lazy.py", line 1201, in run
        return self._last_context.run(self._run_as, _func_or_method, *args, **kwargs)
      File "/usr/lib/python3.6/site-packages/contextvars/__init__.py", line 38, in run
        return callable(*args, **kwargs)
      File "/usr/lib/python3.6/site-packages/salt/loader/lazy.py", line 1216, in _run_as
        return _func_or_method(*args, **kwargs)
      File "/usr/lib/python3.6/site-packages/salt/executors/direct_call.py", line 10, in execute
        return func(*args, **kwargs)
      File "/usr/lib/python3.6/site-packages/salt/loader/lazy.py", line 149, in __call__
        return self.loader.run(run_func, *args, **kwargs)
      File "/usr/lib/python3.6/site-packages/salt/loader/lazy.py", line 1201, in run
        return self._last_context.run(self._run_as, _func_or_method, *args, **kwargs)
      File "/usr/lib/python3.6/site-packages/contextvars/__init__.py", line 38, in run
        return callable(*args, **kwargs)
      File "/usr/lib/python3.6/site-packages/salt/loader/lazy.py", line 1216, in _run_as
        return _func_or_method(*args, **kwargs)
      File "/usr/lib/python3.6/site-packages/salt/modules/file.py", line 3384, in append
        with salt.utils.files.fopen(path, "rb+") as ofile:
      File "/usr/lib/python3.6/site-packages/salt/utils/files.py", line 385, in fopen
        f_handle = open(*args, **kwargs)  # pylint: disable=resource-leakage
    PermissionError: [Errno 1] Operation not permitted: '/root/a'
ERROR: Minions returned with non-zero exit code

给指定文件去除属性

[root@master ~]# salt node1 file.chattr /root/a operator=remove attributes=i
node1:
    True
[root@master ~]# salt node1 cmd.run 'lsattr /root/a'node1:
    -----a-------------- /root/a

file.chown

设置指定文件的属主、属组信息

[root@master ~]# salt node1 cmd.run 'ls -l /root/'
node1:
    total 2
    -rw-------. 1 root root 1184 Jul 21 14:40 anaconda-ks.cfg
    drwxr-xr-x  2 root root    6 Nov  4 10:40 test
[root@master ~]# salt node1 file.chown /root/test xux xux
node1:
    None
[root@master ~]# salt node1 cmd.run 'ls -l /root/'
node1:
    total 2
    -rw-------. 1 root root 1184 Jul 21 14:40 anaconda-ks.cfg
    drwxr-xr-x  2 xux  xux     6 Nov  4 10:40 test

file.copy

在远程主机上复制文件或目录

拷贝文件

[root@master ~]# salt node1 cmd.run 'ls -l /root/'
node1:
    total 8
    -rw-r--r--  1 root root   12 Nov  5 06:51 a
    -rw-------. 1 root root 1184 Jul 21 14:40 anaconda-ks.cfg
    -rw-r--r--  1 root root    0 Nov  5 06:28 b
    -rw-r--r--  1 root root    0 Nov  5 06:28 c
    drwxr-xr-x  2 xux  xux     6 Nov  4 10:40 test
[root@master ~]# salt node1 file.copy /root/a /root/aaa
node1:
    True
[root@master ~]# salt node1 cmd.run 'ls -l /root/'
node1:
    total 12
    -rw-r--r--  1 root root   12 Nov  5 06:51 a
    -rw-r--r--  1 root root   12 Nov  5 07:13 aaa
    -rw-------. 1 root root 1184 Jul 21 14:40 anaconda-ks.cfg
    -rw-r--r--  1 root root    0 Nov  5 06:28 b
    -rw-r--r--  1 root root    0 Nov  5 06:28 c
    drwxr-xr-x  2 xux  xux     6 Nov  4 10:40 test

覆盖并拷贝目录,将会覆盖同名文件或目录

[root@master ~]# salt node1 file.copy /root/abc/ /opt/ recurse=true
node1:
    True

删除目标目录中同名的文件或目录并拷贝新内容至其中

[root@node1 opt]# ls
abc
[root@node1 abc]# ls
111  222
[root@master ~]# salt node1 file.copy /root/abc/ /opt/ recurse=true remove_existing=true
node1:
    True
[root@node1 opt]# ls
111  222

file.ditectory_exists

判断指定目录是否存在,存在则返回 True ,否则返回 False

[root@master ~]# salt node1 cmd.run 'ls -l /opt/'
node1:
    total 0
    -rw-r--r-- 1 root root 0 Nov  5 07:21 111
    -rw-r--r-- 1 root root 0 Nov  5 07:21 222
[root@master ~]# salt node1 file.directory_exists /opt/333
node1:
    False

file.diskusage

递归计算指定路径的磁盘使用情况并以字节为单位返回

[root@master ~]# salt node1 cmd.run 'du -sb /opt/'
node1:
    28  /opt/
[root@master ~]# salt node1 file.diskusage /opt
node1:
    0

file.file_exists

判断指定文件是否存在

[root@master ~]# salt node1 cmd.run 'ls -l /opt/111'
node1:
    -rw-r--r-- 1 root root 0 Nov  5 07:21 /opt/111
[root@master ~]# salt node1 file.file_exists /opt/111
node1:
    True

file.find

类似 find 命令并返回符合指定条件的路径列表
The options include match criteria:

name    = path-glob                 # case sensitive
iname   = path-glob                 # case insensitive
regex   = path-regex                # case sensitive
iregex  = path-regex                # case insensitive
type    = file-types                # match any listed type
user    = users                     # match any listed user
group   = groups                    # match any listed group
size    = [+-]number[size-unit]     # default unit = byte
mtime   = interval                  # modified since date
grep    = regex                     # search file contents

and/or actions:

delete [= file-types]               # default type = 'f'
exec    = command [arg ...]         # where {} is replaced by pathname
print  [= print-opts]

and/or depth criteria:

maxdepth = maximum depth to transverse in path
mindepth = minimum depth to transverse before checking files or directories

The default action is print=path

path-glob:

*                = match zero or more chars
?                = match any char
[abc]            = match a, b, or c
[!abc] or [^abc] = match anything except a, b, and c
[x-y]            = match chars x through y
[!x-y] or [^x-y] = match anything except chars x through y
{a,b,c}          = match a or b or c

path-regex: a Python Regex (regular expression) pattern to match pathnames

file-types: a string of one or more of the following:

a: all file types(所有文件类型)
b: block device(块设备)
c: character device(字符设备)
d: directory(目录)
p: FIFO (named pipe)
f: plain file(普通文件)
l: symlink(符号链接)
s: socket(套接字)

users: a space and/or comma separated list of user names and/or uids

groups: a space and/or comma separated list of group names and/or gids
size-unit:

b: bytes
k: kilobytes
m: megabytes
g: gigabytes
t: terabytes

interval:

[<num>w] [<num>d] [<num>h] [<num>m] [<num>s]

where:
    w: week
    d: day
    h: hour
    m: minute
    s: second

print-opts: a comma and/or space separated list of one or more of the following:

group: group name
md5:   MD5 digest of file contents
mode:  file permissions (as integer)
mtime: last modification time (as time_t)
name:  file basename
path:  file absolute path
size:  file size in bytes
type:  file type
user:  user name

示例:

salt '*' file.find / type=f name=\*.bak size=+10m
salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime
salt '*' file.find /var/log name=\*.[0-9] mtime=+30d size=+10m delete

file.get_gid

获取指定文件的gid

[root@master ~]# salt node1 file.get_gid /opt/111
node1:
    0

file.get_group

获取指定文件的组名

[root@master ~]# salt node1 file.get_group /opt/111
node1:
    root

file.get_hash

获取指定文件的hash值,该值通过 sha256 算法得来

[root@master ~]# salt node1 file.get_hash /opt/111
node1:
    e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

file.get_mode

获取指定文件的权限,以数字方式显示

[root@master ~]# salt node1 cmd.run 'ls -l /opt/111'
node1:
    -rw-r--r-- 1 root root 0 Nov  5 07:21 /opt/111
[root@master ~]# salt node1 file.get_mode /opt/111
node1:
    0644

file.get_selinux_context

获取指定文件的 SELINUX 上下文信息

[root@master ~]# salt node1 file.get_selinux_context /root/anaconda-ks.cfg 
node1:
    system_u:object_r:admin_home_t:s0

file.get_sum

按照指定的算法计算指定文件的特征码并显示,默认使用的sha256算法。
该函数可使用的算法参数有:

  • md5
  • sha1
  • sha224
  • sha256 (default)
  • sha384
  • sha512
[root@master ~]# salt node1 cmd.run 'sha256sum /opt/111'
node1:
    e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  /opt/111
[root@master ~]# salt node1 file.get_sum /opt/111
node1:
    e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
[root@master ~]# salt node1 cmd.run 'md5sum /opt/111'
node1:
    d41d8cd98f00b204e9800998ecf8427e  /opt/111
[root@master ~]# salt node1 file.get_sum /opt/111 md5
node1:
    d41d8cd98f00b204e9800998ecf8427e

file.get_uid与file.get_user

获取指定文件的 uid 或 用户名

[root@master ~]# salt node1 cmd.run 'ls -l /opt/111'
node1:
    -rw-r--r-- 1 root root 0 Nov  5 07:21 /opt/111
[root@master ~]# salt node1 file.get_uid /opt/111 
node1:
    0
[root@master ~]# salt node1 file.get_user /opt/111
node1:
    root

file.gid_to_group

将指定的 gid 转换为组名并显示

[root@master ~]#  salt node1 file.gid_to_group 1000
node1:
    xux
[root@master ~]#  salt node1 file.gid_to_group 0
node1:
    root

file.group_to_gid

将指定的组名转换为 gid 并显示

[root@master ~]# salt node1 file.group_to_gid xux
node1:
    1000
[root@master ~]# salt node1 file.group_to_gid root
node1:
    0

file.grep

在指定文件中检索指定内容
该函数支持通配符,若在指定的路径中用通配符则必须用双引号引起来

salt '*' file.grep /etc/passwd nobody
salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i
salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2
salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l

file.is_blkdev

判断指定的文件是否是块设备文件

[root@master ~]# salt node1 cmd.run 'ls -l /dev/sr0'
node1:
    brw-rw---- 1 root cdrom 11, 0 Nov  5 06:22 /dev/sr0
[root@master ~]# salt node1 file.is_blkdev /dev/sr0
node1:
    True

file.lsattr

检查并显示出指定文件的属性信息

[root@master ~]# salt node1 cmd.run 'lsattr /opt/111'
node1:
    -------------------- /opt/111
[root@master ~]# salt node1 cmd.run 'chattr +i /opt/111'
node1:
[root@master ~]# salt node1 cmd.run 'lsattr /opt/111'node1:
    ----i--------------- /opt/111

file.mkdir

创建目录并设置属主、属组及权限

[root@master ~]# salt node1 file.mkdir /root/test01 xux xux 444
node1:
    True
[root@master ~]# salt node1 cmd.run 'ls -l /root/'
node1:
    total 12
    -rw-r--r--  1 root root   12 Nov  5 06:51 a
    -rw-r--r--  1 root root   12 Nov  5 07:13 aaa
    drwxr-xr-x  2 root root   28 Nov  5 07:21 abc
    -rw-------. 1 root root 1184 Jul 21 14:40 anaconda-ks.cfg
    -rw-r--r--  1 root root    0 Nov  5 06:28 b
    -rw-r--r--  1 root root    0 Nov  5 06:28 c
    drwxr-xr-x  2 xux  xux     6 Nov  4 10:40 test
    dr--r--r--  2 xux  xux     6 Nov  5 07:51 test01
    drwxr-xr-x  2 root root    6 Nov  5 07:48 test08

file.move

移动或重命名

[root@master ~]# salt node1 cmd.run 'ls -l /opt'
node1:
    total 0
    -rw-r--r-- 1 root root 0 Nov  5 07:21 111
    -rw-r--r-- 1 root root 0 Nov  5 07:21 222
[root@master ~]# salt node1 file.move /opt/222 /root
node1:
    ----------
    comment:
        '/opt/222' moved to '/root'
    result:
        True
[root@node1 ~]# ls
222  anaconda-ks.cfg

file.prepend

把文本插入指定文件的开头
[root@master ~]# salt node1 cmd.run 'cat /root/222'
node1:
    111
    222
    333
    444
[root@master ~]# salt node1 file.prepend /root/222 "aaa" "bbb"
node1:
    Prepended 2 lines to "/root/222"
[root@master ~]# salt node1 cmd.run 'cat /root/222'node1:
    aaa
    bbb
    111
    222
    333
    444

file.sed

修改文本文件的内容

[root@master ~]# salt node1 cmd.run 'cat /root/222'node1:
    aaa
    bbb
    111
    222
    333
    444
[root@master ~]# salt node1 file.sed /root/222 "222" "good" 
node1:
    ----------
    pid:
        203725
    retcode:
        0
    stderr:
    stdout:
[root@master ~]# salt node1 cmd.run 'cat /root/222'node1:
    aaa
    bbb
    111
    good
    333
    444

file.read

读取文件内容

[root@master ~]# salt node1 file.read /root/222
node1:
    aaa
    bbb
    111
    good
    333
    444

file.readdir

列出指定目录下的所有文件或目录,包括隐藏文件

[root@master ~]# salt node1 file.readdir /root
node1:
    - .
    - ..
    - .bash_logout
    - .bash_profile
    - .bashrc
    - .cshrc
    - .tcshrc
    - anaconda-ks.cfg
    - .bash_history
    - .config
    - .ssh
    - .mysql_history
    - .viminfo
    - 222

file.remove

删除指定的文件或目录,若给出的是目录,将递归删除

[root@master ~]# salt node1 cmd.run "tree /opt/"
node1:
    /opt/
    |-- 1
    |   `-- 2
    |       `-- 3
    |           `-- 4
    `-- 111
    
    4 directories, 1 file
[root@master ~]# salt node1 file.remove "/opt/1/"
node1:
    True
[root@master ~]# salt node1 cmd.run "tree /opt/"
node1:
    /opt/
    `-- 111
    
    0 directories, 1 file

file.rename

重命名文件或目录

[root@master ~]# salt node1 cmd.run "ls /root/"
node1:
    anaconda-ks.cfg
    good

file.set_mode

给指定文件设置权限

[root@master ~]# salt node1 cmd.run "ls -l /root/good"
node1:
    -rw-r--r-- 1 root root 25 Nov  8 07:05 /root/good
[root@master ~]# salt node1 file.set_mode  /root/good 0777
node1:
    0777
[root@master ~]# salt node1 cmd.run "ls -l /root/good"
node1:
    -rwxrwxrwx 1 root root 25 Nov  8 07:05 /root/good

file.symlink

给指定的文件创建软链接

[root@master ~]# salt node1 file.symlink /root/good /mnt/test
node1:
    True
[root@master ~]# salt node1 cmd.run 'ls -l /mnt/test'
node1:
    lrwxrwxrwx 1 root root 10 Nov  8 07:14 /mnt/test -> /root/good

file.touch

创建空文件或更新时间戳

[root@master ~]# salt node1 file.touch /opt/test
node1:
    True
[root@master ~]# salt node1 cmd.run 'ls -l /opt/'
node1:
    total 0
    -rw-r--r-- 1 root root 0 Nov  5 07:21 111
    -rw-r--r-- 1 root root 0 Nov  8 07:15 test

file.uid_to_user

将指定的 uid 转换成用户名显示出来

[root@master ~]# salt node1 file.uid_to_user 0
node1:
    root

file.user_to_uid

将指定的用户转换成 uid 并显示出来

[root@master ~]# salt node1 file.user_to_uid xux
node1:
    1000

file.write

往一个指定的文件里覆盖写入指定内容

[root@master ~]# salt node1 cmd.run 'cat /root/good'
node1:
    aaa
    bbb
    111
    good
    333
    444
[root@master ~]# salt 'node1' file.write /root/good "hello" "hi"
node1:
    Wrote 2 lines to "/root/good"
[root@master ~]# salt node1 cmd.run 'cat /root/good'node1:
    hello
    hi
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值