21运维原创,转载请注明出处。
在写这篇文章之前,感觉有些多余。因为之前已经写过文章《[原创]Saltstack远程执行学习笔记:模块module使用》 已经详细介绍了 如何查看组件,每个组件有哪些函数可以调用。 赶上朋友问我如何通过salt批量在服务器端执行shell脚本,看来还是有必要再补充一个。即:
[[email protected] shell]# salt "21yunwei" cmd.script salt://shell/etcbak.sh
21yunwei:
----------
pid:
422
retcode:
0
stderr:
tar: Removing leading `/' from member names
stdout:
etc bakup sucess
说明:
1,cmd.script这个组件就是在远程服务器上执行shell脚本使用。具体使用方法可以通过如下命令了解:
[[email protected]]# salt "21yunwei" sys.doc cmd.script
2,要执行的脚本放到/srv/salt下的目录中,这个目录可以理解成根目录,salt://就是等价于/srv/salt。比如我执行的测试脚本就放到了/srv/salt/shell/etcbak.sh
执行的测试脚本内容:
#!/bin/bash
time=`date +%F`
[ ! -d /home/21yunwei/etcbak ] && mkdir -p /home/oldboy/etcbak || echo "etcbak exist"
tar zcf /home/21yunwei/etcbak/etcbak$time.tar.gz /etc
[ $? -eq 0 ] && echo "etc bakup sucess" || echo "etc bakup error,please check"
个人感觉平时遇到salt的处理,可以通过组件以及函数查看,比如这种执行shell,明显是属于远程执行,那么就可以通过cmd的方法来查看。比如我们想了解一个组件有哪些函数,可以通过sys.list_functions查看:
[[email protected] shell]# salt "21yunwei" sys.list_functions cmd
21yunwei:
- cmd.exec_code
- cmd.exec_code_all
- cmd.has_exec
- cmd.retcode
- cmd.run
- cmd.run_all
- cmd.run_chroot
- cmd.run_stderr
- cmd.run_stdout
- cmd.script
- cmd.script_retcode
- cmd.shell
- cmd.shells
- cmd.tty
- cmd.which
- cmd.which_bin
具体某个函数的使用,可以通过sys.doc来查看:
[[email protected] shell]# salt "21yunwei" sys.doc cmd.script
'cmd.script:'
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Arguments for the script can be specified as well.
CLI Example:
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\tmp\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.:
salt '*' cmd.script salt://scripts/runme.sh stdin='one\ntwo\nthree\nfour\nfive\n'