前言: 在给nagios开发监控插件的时候,不论是用哪种语言写插件,最好能从命令行获得参数(警告值和报警值:-w warning_value -c critical_value),而不是在插件里把这两个值写进去,通常情况下会随着环境改变而更改警告和报警值。 python: 通过sys模块实现官方文档: sys.argv The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string. 举个简单的例子: #!/usr/bin/env python import sys def PrintArgv(): # 如果需要list中的index,可以用内置的enumerate函数实现; print('all para(s):', sys.argv) print('script name:', sys.argv[0]) if sys.argv[1:]: index = 1 for para in sys.argv[1:]: print('para', index, ':', para) index += 1 import sys PrintArgv() >python test.py all para(s): ['test.py'] script name: test.py >python test.py 'name' 913 all para(s): ['test.py', "'name'", '913'] script name: test.py para 1 : 'name' para 2 : 913 >python test.py 'name' 913 [1,2] all para(s): ['test.py', "'name'", '913', '[1,2]'] script name: test.py para 1 : 'name' para 2 : 913 para 3 : [1,2] 可以看出,参数默认为字符串类型,同input一样,需要转换为int类型的传入参数时需要注意。 shell实现:$变量 shell脚本中可以通过变量的方式调用命令传入的参数,$0为脚本名,第一个参数$1,第二个参数$2,以此类推。特别的,$#表示参数个数,$@表示所有参数。 简单例子: # --para.sh-- [root@oam shell]# ./para.sh all para(s): script name: para.sh [root@oam shell]# ./para.sh hello lei 2014 all para(s): hello lei 2014 script name: para.sh para 1: hello para 2: lei para 3: 2014 C/C++实现 C和C++都允许从命令行给main函数传入参数:int main(int argc, char*argv[]),argc表示有几个参数将传给main函数,参数以字符串数组argv[]的形式传递。同样argv[0]表示二进制文件名,argv[1]表示第一个参数,argv[2]表示第二个参数,依此类推。 简单的例子: #include<iostream> using namespace std; int main(int argc, char *argv[]) { cout << "file name: " << argv[0] << endl; cout << "para num: " << argc << endl; for (int i=1; i<argc; i++) { cout << "para " << i << ": " << argv[i] << endl; } return 0; } |
|