前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Python读取Excel将命令行命令批量运行

使用Python读取Excel将命令行命令批量运行

作者头像
繁华是客
修改2024-05-14 10:36:02
1030
修改2024-05-14 10:36:02
举报

我们知道使用Alibaba Cloud CLI是可以列出信息甚至可以做修改。但是如果我有批量的修改需求,那么我怎么去做呢

以下命令行代码,其实没有意义,只是用于展示。读取Excel的VPC ID和VSwitchID然后将实例列出来。

你可以修改为例如根据InstanceID修改安全组,或者根据InstaceID修改Tag等各种实用功能

pandas.read_excel具体说明请参考pandas官方文档

利用Python快速实现

代码语言:javascript
复制
pip install pandas
pip install openpyxl
代码语言:javascript
复制
import pandas as pd
import subprocess

# Path to your Excel file
excel_file_path = 'D:\\PycharmProjects\\something\\vpc.xlsx'

# Load the Excel file
df = pd.read_excel(excel_file_path, engine='openpyxl')

# Iterate over each row in the DataFrame
for index, row in df.iterrows():
    vpc = row['vpc']
    vsw = row['vsw']
    instance_id = row ['InstanceId']



    # Construct the CLI command
    cli_command = f'aliyun ecs DescribeInstances --VpcId {vpc} --VSwitchId {vsw} --output cols="OSNameEn,InstanceId,InstanceName,VpcAttributes.VpcId, VpcAttributes.VSwitchId" rows="Instances.Instance[]"'

    try:
        # Execute the CLI command
        subprocess.run(cli_command, check=True, shell=True)
        print(f"Successfully run command for instance ID: {instance_id} {vpc} {vsw}")
    except subprocess.CalledProcessError as e:
        # If there's an error executing the CLI command, print it
        print(f"Failed to run {instance_id}. Error: {str(e)}")

示例:加入资源组

将云盘批量加入资源组

代码语言:javascript
复制
import pandas as pd
import subprocess

# Path to your Excel file
excel_file_path = 'D:\\yes\\instance-resourcegroup.xlsx'

# Load the Excel file
df = pd.read_excel(excel_file_path, engine='openpyxl', sheet_name="Result")

# Iterate over each row in the DataFrame
for index, row in df.iterrows():
    instance_id = row['InstanceId']
    disk_id = row['DiskId']
    resource_group_id = row['ResourceGroupId']




    # Construct the CLI command
   cli_command = f'aliyun ecs JoinResourceGroup --ResourceId {disk_id} --ResourceGroupId {resource_group_id} --ResourceType disk --profile CLI-exampleProfile'

    try:
        # Execute the CLI command
        subprocess.run(cli_command, check=True, shell=True)
        print(f"Successfully changed the resource group for Disk ID: {instance_id} {disk_id} {resource_group_id}")
    except subprocess.CalledProcessError as e:
        # If there's an error executing the CLI command, print it
        print(f"Failed to change the resource group for Disk ID: {disk_id}. Error: {str(e)}")

加ECS到资源组

例如,如果我们修改以下cli_command和少部分代码,即可将大量ecs添加到对应的资源组内。建议额外在excel加rowid, 这样错误提示可以加上是哪一行报错。

代码语言:sh
复制
# 加ECS到资源组
aliyun ecs JoinResourceGroup --ResourceId {instance_id} --ResourceGroupId {resource_group_id} --ResourceType instance

加安全组到资源组

在已将ECS添加到资源组的情况下,因为安全组不会自动转组。所以需要人工转。而且有可能一个ECS存在多个安全组,而其中一个安全组是大安全组,不需要加资源组。所以需要人工干预,例如全部转组后再转回来。或者先在Excel筛选处理后再用python。

Step 1: 基于实例获得安全组及其资源组

Step 2: 获得安全组及对应的资源组并删除已有资源组的。

代码语言:sh
复制
aliyun ecs DescribeSecurityGroups --output cols="SecurityGroupName,SecurityGroupId,ResourceGroupId" rows="SecurityGroups.SecurityGroup[]" --pager

Step 3: 根据实例获得的表格(Step 1) 做安全组的Excel表格处理:删除空格->替换空格为, ->删除,, ->将,作为分列符。使得一个实例,对应一列是一个安全组,额外一列是另一个安全组,最后一列是实例的资源组。

Step 4: 假设我们最多有3个安全组,也就是在分成3列。假设列数是C,D,E。我们通过xlookup与Step 2获得的安全组做对比,从而获得在该列中的安全组的实例资源组。通过对这3列做xlookup后,再做聚合。

Step 5: 因为xlookup会出现两种可能,一种是0,也就是该列未找到资源组。另一种是#N/A,也就是在完整的安全组该列中未找到改安全组。而如果找到了资源组则开头一定是rg-,所以我们Excel表达式如下:

代码语言:sh
复制
=IFERROR(IF(AND(ISNUMBER(SEARCH("rg-",C2)),NOT(ISERROR(C2)),C2<>0),C2,IF(AND(ISNUMBER(SEARCH("rg-",D2)),NOT(ISERROR(D2)),D2<>0),D2,IF(AND(ISNUMBER(SEARCH("rg-",E2)),NOT(ISERROR(E2)),E2<>0),E2,""))),"")

这就是聚合后在安全组每个的资源组情况了。

Step 6, 替换python命令即可。

代码语言:sh
复制
aliyun ecs JoinResourceGroup --ResourceId {sg_id} --ResourceGroupId {resource_group_id} --ResourceType securitygroup

关于resourcemanager API

我们这里使用的其实是ECS的加入资源组API, 但是可不可以用resourcemanger的API呢?

resourcemanager是中心化的,他的endpoint不是区域+aliyuncs。在默认情况下运行CLI是不可行的,也不可以region_id为空,所以需要额外指定endpoint。例如:

代码语言:sh
复制
aliyun resourcemanager ListResourceGroups --endpoint resourcemanager.aliyuncs.com
本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-05-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 利用Python快速实现
  • 示例:加入资源组
    • 加ECS到资源组
      • 加安全组到资源组
      • 关于resourcemanager API
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
      http://www.vxiaotou.com