第一:安裝前準備:
聲明我用的是ubuntu 16.04的系統?
1.修改主機名,并保證兩臺機器可以互相ping同主機名
ip1 master_hostname
ip2 slave_hostname
第二:安裝
服務器安裝 yum install salt-master -y客戶端安裝 yum install salt-minion -y
ubuntu16.04的安裝完會自動啟動
第三:配置:
更改minion端的
master: master的ip地址(注意: “:后面有一個空格”)
第四:認證:
master創建的key:
minion創建的key:
等待認證的key:
查看等待同意的key:
執行接受操作:
?查看key的位置,原本在pre下面,現在跑到了minion下面了
以上是簡單的查看了key的認證,下面我們看下salt-key的詳細用法:


# salt-key -h Usage: salt-key [options]Salt key is used to manage Salt authentication keysOptions:--version show program's version number and exit--versions-report show program's dependencies version number and exit-h, --help show this help message and exit--saltfile=SALTFILE Specify the path to a Saltfile. If not passed, onewill be searched for in the current working directory-c CONFIG_DIR, --config-dir=CONFIG_DIRPass in an alternative configuration directory.Default: /etc/salt-u USER, --user=USER Specify user to run salt-key--hard-crash Raise any original exception rather than exitinggracefully Default: False-q, --quiet Suppress output-y, --yes Answer Yes to all questions presented, defaults toFalse--rotate-aes-key=ROTATE_AES_KEYSetting this to False prevents the master fromrefreshing the key session when keys are deleted orrejected, this lowers the security of the keydeletion/rejection operation. Default is True.Logging Options:Logging options which override any settings defined on theconfiguration files.--log-file=LOG_FILELog file path. Default: /var/log/salt/key.--log-file-level=LOG_LEVEL_LOGFILELogfile logging log level. One of 'all', 'garbage','trace', 'debug', 'profile', 'info', 'warning','error', 'critical', 'quiet'. Default: 'warning'.Output Options:Configure your preferred output format--out=OUTPUT, --output=OUTPUTPrint the output from the 'salt-key' command using thespecified outputter. The builtins are 'key', 'yaml','overstatestage', 'highstate', 'newline_values_only','pprint', 'txt', 'raw', 'virt_query', 'compact','json', 'nested', 'quiet', 'no_return'.--out-indent=OUTPUT_INDENT, --output-indent=OUTPUT_INDENTPrint the output indented by the provided value inspaces. Negative values disables indentation. Onlyapplicable in outputters that support indentation.--out-file=OUTPUT_FILE, --output-file=OUTPUT_FILEWrite the output to the specified file--out-file-append, --output-file-appendAppend the output to the specified file--no-color, --no-colourDisable all colored output--force-color, --force-colourForce colored output--state-output=STATE_OUTPUT, --state_output=STATE_OUTPUTOverride the configured state_output value for minionoutput. One of full, terse, mixed, changes or filter.Default: full.--state-verbose=STATE_VERBOSE, --state_verbose=STATE_VERBOSEOverride the configured state_verbose value for minionoutput. Set to True or FalseDefault: TrueActions:-l ARG, --list=ARG List the public keys. The args "pre", "un", and"unaccepted" will list unaccepted/unsigned keys. "acc"or "accepted" will list accepted/signed keys. "rej" or"rejected" will list rejected keys. "den" or "denied"will list denied keys. Finally, "all" will list allkeys.-L, --list-all List all public keys. (Deprecated: use "--list all") #查看認證信息-a ACCEPT, --accept=ACCEPTAccept the specified public key (use --include-all tomatch rejected keys in addition to pending keys).Globs are supported.-A, --accept-all Accept all pending keys #接受全部的pending 狀態的minion-r REJECT, --reject=REJECTReject the specified public key (use --include-all tomatch accepted keys in addition to pending keys).Globs are supported.-R, --reject-all Reject all pending keys--include-all Include non-pending keys when accepting/rejecting-p PRINT, --print=PRINTPrint the specified public key-P, --print-all Print all public keys-d DELETE, --delete=DELETE Delete the specified key. Globs are supported.-D, --delete-all Delete all keys #刪除指定key-f FINGER, --finger=FINGERPrint the specified key's fingerprint-F, --finger-all Print all keys' fingerprints Key Generation Options:--gen-keys=GEN_KEYSSet a name to generate a keypair for use with salt--gen-keys-dir=GEN_KEYS_DIRSet the directory to save the generated keypair, onlyworks with "gen_keys_dir" option; default=.--keysize=KEYSIZE Set the keysize for the generated key, only works withthe "--gen-keys" option, the key size must be 2048 orhigher, otherwise it will be rounded up to 2048; ;default=2048--gen-signature Create a signature file of the masters public-keynamed master_pubkey_signature. The signature can besend to a minion in the masters auth-reply and enablesthe minion to verify the masters public-keycryptographically. This requires a new signing-key-pair which can be auto-created with the --auto-createparameter--priv=PRIV The private-key file to create a signature with--signature-path=SIGNATURE_PATHThe path where the signature file should be written--pub=PUB The public-key file to create a signature for--auto-create Auto-create a signing key-pair if it does not yetexistYou can find additional help about salt-key issuing "man salt-key" or on http://docs.saltstack.com #更多查看官網
第五:saltstack遠程執行命令:
1.測試與minion的通信是否正常
出現如上圖所示的情況,解決辦法:
?/etc/salt/master的配置文件中,將file_ignore_glob組的注釋全部打開,重啟master即可
2.遠程執行命令:
salt '*' cmd.run 'ls -l /etc'
?3.查看磁盤信息:


# salt '*' disk.usage host-minion:----------/:----------1K-blocks:94326644available:87738788capacity:2%filesystem:/dev/mapper/ubuntu--vg-rootused:1773216/boot:----------1K-blocks:482922available:399773capacity:13%filesystem:/dev/sda1used:58215/dev:----------1K-blocks:4067252available:4067252capacity:0%filesystem:udevused:0/dev/shm:----------1K-blocks:4087280available:4087268capacity:1%filesystem:tmpfsused:12/run:----------1K-blocks:817460available:773752capacity:6%filesystem:tmpfsused:43708/run/lock:----------1K-blocks:5120available:5120capacity:0%filesystem:tmpfsused:0/run/user/1000:----------1K-blocks:817460available:817460capacity:0%filesystem:tmpfsused:0/sys/fs/cgroup:----------1K-blocks:4087280available:4087280capacity:0%filesystem:tmpfsused:0
4.查看網絡信息?salt '*' network.interfaces
5.查看幫助文檔信息 ?salt '*' sys.doc
6.匹配相關minion:
salt -G 'os:Ubuntu' test.ping
salt -E 'minion[0-9]' test.ping
salt -L 'minion1,minion2' test.ping
更多模塊的用法請查看官網文檔:
https://docs.saltstack.com
第六:列舉幾個常用的模塊:
列出當前版本支持的模塊:


# salt '*' sys.list_modules host:- acl- aliases- alternatives- archive- artifactory- at- beacons- bigip- blockdev- btrfs- buildout- cloud- cmd- composer- config- consul- container_resource- cp- cpan- cron- data- debconf- defaults- devmap- dig- disk- django- dnsmasq- dnsutil- drbd- elasticsearch- environ- etcd- event- extfs- file- gem- genesis- git- grains- group- grub- hashutil- hg- hipchat- hosts- http- img- incron- ini- introspect- ip- iptables- jboss7- jboss7_cli- key- keyboard- kmod- locale- locate- logrotate- lowpkg- lvm- match- mine- modjk- mount- mysql- nagios_rpc- network- node- nspawn- openstack_config- pagerduty- pagerduty_util- partition- pillar- pip- pkg- pkg_resource- pkgbuild- publish- pushover- pyenv- raid- random- random_org- rbenv- rest_sample_utils- ret- rsync- runit- rvm- s3- saltutil- schedule- scsi- sdb- seed- serverdensity_device- service- shadow- slack- slsutil- smbios- smtp- splay- sqlite3- ssh- state- status- supervisord- sys- sysctl- syslog_ng- system- temp- test- timezone- tls- udev- uptime- user- vbox_guest- virtualenv- xfs- zfs
test.ping的api調用方式:
import salt.client client = salt.client.LocalClient() ret = client.cmd('*','test.ping') print(ret)
cmd模塊:遠程執行命令(上面已經列出)
#獲取所欲被控主機的內存使用情況
salt '*' cmd.run 'free -m'
API調用方式:
import salt.client client = salt.client.LocalClient() free = client.cmd('*','cmd.run',['free -m']) print(free)
crontab 模塊
#為指定被控主機、root用戶添加計劃任務/usr/local/weekly任務 salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly #刪除指定被控主機、root用戶crontab的/usr/local/weekly任務 salt '*' cron.rm_job root /usr/local/weekly
crontab的api調用:
增加crontab方式: client.cmd('*','cron.set_job',['root','*','*','*','*',1,'/usr/local/weekly'])刪除crontab的方式: client.cmd('*','cron.rm_job',['root','/usr/local/weekly'])
?
?
file模塊:
#校驗所有被控主機/etc/fstab文件的md5值是否為xxxxxxxxxxxxx,一致則返回True值 salt '*' file.check_hash /etc/fstab md5:a4e398d752713d5f12880a92c7dfd557#校驗所有被控主機文件的加密信息,支持md5、sha1、sha224、shs256、sha384、sha512加密算法 salt '*' file.get_sum /etc/passwd md5#修改所有被控主機/etc/passwd文件的屬組、用戶權限、等價于chown root:root /etc/passwd salt '*' file.chown /etc/passwd root root#復制所有被控主機/path/to/src文件到本地的/path/to/dst文件 salt '*' file.copy /path/to/src /path/to/dst#檢查所有被控主機/etc目錄是否存在,存在則返回True,檢查文件是否存在使用file.file_exists方法 salt '*' file.directory_exists /etc#獲取所有被控主機/etc/passwd的stats信息 salt '*' file.stats /etc/passwd#獲取所有被控主機/etc/passwd的權限mode,如755,644 salt '*' file.get_mode /etc/passwd#修改所有被控主機/etc/passwd的權限mode為0644 salt '*' file.set_mode /etc/passwd 0644#在所有被控主機創建/opt/test目錄 salt '*' file.mkdir /opt/test#將所有被控主機/etc/httpd/httpd.conf文件的LogLevel參數的warn值修改為info salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'#給所有被控主機的/tmp/test/test.conf文件追加內容‘maxclient 100’ salt '*' file.append /tmp/test/test.conf 'maxclient 100'#刪除所有被控主機的/tmp/foo文件 salt '*' file.remove /tmp/foo
service服務模塊:
#開啟(enable)、禁用(disable)nginx開機自啟動腳本 salt '*' service.enable nginx salt '*' service.disable nginx#針對nginx服務的reload、restart、start、stop、status操作 salt '*' service.reload nginx salt '*' service.restart nginx salt '*' service.start nginx salt '*' service.stop nginx salt '*' service.status nginx
service的API調用:
client.cmd('*','service.stop',['nginx'])
cp模塊:
# cp /opt/getfile.txt /srv/salt/ # salt '*' cp.get_file salt://getfile.txt /opt/getfile.txt salt-client:/opt/getfile.txt