环境准备

系统环境

CentOS Linux release 7.2.1511 (Core)

[root@localhost ~]# cat /proc/version 
Linux version 3.10.0-327.el7.x86_64 (builder@kbuilder.dev.centos.org) (gcc version 4.8.3 20140911 (Red Hat 4.8.3-9) (GCC) ) #1 SMP Thu Nov 19 22:10:57 UTC 2015
[root@localhost ~]# 
[root@localhost ~]# uname -a
Linux localhost.localdomain 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
[root@localhost ~]# 
[root@localhost ~]# python -V
Python 2.7.5

软件环境

[root@localhost ~]#  yum groupinstall "Development Tools"
[root@localhost ~]#  yum install python-setuptools ntsysv python-devel setuptool

[root@localhost ~]#  pip install setuptools
[root@localhost ~]#  pip install aliyun-python-sdk-core
[root@localhost ~]#  pip install aliyun-python-sdk-slb

脚本编写

#!/usr/bin/env python
#coding=utf-8

import sys
import json
from aliyunsdkcore import client
from aliyunsdkslb.request.v20140515 import SetVServerGroupAttributeRequest
from aliyunsdkslb.request.v20140515 import DescribeVServerGroupAttributeRequest

clt = client.AcsClient('<accessKeyId>','<accessSecret>','cn-hangzhou')

# 查询
## 设置参数
request = DescribeVServerGroupAttributeRequest.DescribeVServerGroupAttributeRequest()
request.set_accept_format('json')

request.add_query_param('RegionId', 'cn-beijing')
request.add_query_param('VServerGroupId', 'rsp-2zef……5p80')

## 发起请求
response = clt.do_action_with_exception(request)

## 输出结果
print "查询结果:", response, '\n'

# 处理
weight = json.loads(response)["BackendServers"]["BackendServer"]

for i in range(len(weight)):
    weight[i]["Weight"] = sys.argv[i+1]
    print "参数设置Client"+str(i+1)+':', weight[i]["Weight"], '\n'

weight = json.dumps(weight)


# 设置
## 设置参数
request = SetVServerGroupAttributeRequest.SetVServerGroupAttributeRequest()
request.set_accept_format('json')

request.add_query_param('RegionId', 'cn-beijing')
request.add_query_param('BackendServers', weight)
request.add_query_param('VServerGroupId', 'rsp-2z……p80')

## 发起请求
response = clt.do_action_with_exception(request)

## 输出结果
print "设置结果:", response, '\n'

使用方法

  • 执行脚本传入参数即可。
[root@localhost ~]#  python ali-slb.py  <weight1>  <weight2> <weight3> ……

结果展示

  • 操作前

  • 执行脚本

  • 结果展示

欢迎大佬,批评指正!