用PHP实现salt-api调用

场景需求

saltstack是越来越火。由于最近要开发一个运维平台,底层用到了salt-api。经过saltsatck和salt-api的学习后,开始搬砖,首先用PHP实现了对salt-api的调用,后来也实现了Python对salt-api的调用,代码比较初级。

代码实现
先获取token
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function get_token(){ 
global $token;
$url = 'https://ip:8000/login'; //ip是已经配好的api地址如 192.168.1.22
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,False);
curl_setopt($ch,CURLOPT_HTTPHEADER, Array('Accept: application/x-yaml'));
curl_setopt($ch,CURLOPT_POSTFIELDS, 'username=你的用户名&password=用户对应的密码&eauth=pam');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$token = curl_exec($ch);
$token = strstr($token, 'token', false);  //取登录后返回字符串中的token
$token = strstr($token, 'user', true);
$token = explode(" ",$token)\[1]; curl_close($ch);
$token = rtrim($token,"\n"); //删掉token字符串最后面的'\n',不然后面死活登不上去
}
带一个或不带参数的salt exc模块

如 salt * test.ping 或 salt * test.echo “hello”这样的模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function exc_salt($tgt, $fun, $arg, $arg_num){ 
global $token;
global $report;
$url = 'https://ip:8000/';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,False);
curl_setopt($ch,CURLOPT_HTTPHEADER,Array('Accept: application/x-yaml',"X-Auth-Token: $token"));
if ($arg_num)
curl_setopt($ch,CURLOPT_POSTFIELDS,"client=local&tgt=$tgt&fun=$fun&arg=$arg");
else
curl_setopt($ch,CURLOPT_POSTFIELDS,"client=local&tgt=$tgt&fun=$fun");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$report = curl_exec($ch);
curl_close($ch);
return $report;
}

两个参数的salt exc模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function exc_salt_2($tgt, $fun, $arg_1, $arg_2){ 
global $token;
global $report;
$url = 'https://ip:8000/';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,False);
curl_setopt($ch,CURLOPT_HTTPHEADER,Array('Accept: application/x-yaml',"X-Auth-Token: $token"));
curl_setopt($ch,CURLOPT_POSTFIELDS,"client=local&tgt=$tgt&fun=$fun&arg=$arg_1&arg=$arg_2");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$report = curl_exec($ch);
curl_close($ch);
return $report;
}
测试
1
2
3
get_token(); 
print exc_salt('主机key', 'test.echo', 'hello', 1); //带一个参数的
print exc_salt('主机key', 'test.ping', '', 0);  //不带参数的

运行结果如下:

有时间可以将这些函数封装成一个类,方便搬砖。要求不高先这样用用。
salt-api手册参考,也可以直接看源代码。
http://salt-api.readthedocs.org/en/latest/

----------------本文结束 感谢阅读----------------
听说,打赏我的人最后都成了大神(* ̄▽ ̄*)