首页 > 其他分享 >脚本阿里云安全组 ECS 白名单

脚本阿里云安全组 ECS 白名单

时间:2024-07-30 11:52:35浏览次数:10  
标签:String ip client 阿里 ECS aliyun 白名单 import com

脚本阿里云安全组 ECS 白名单

公司外网ip 重启路由 啥的 就会变ip,如果需要访问 esc 之前ip白名单失效

参考

/**
 * https://api.aliyun.com/document/Ecs/2014-05-26/DescribeSecurityGroups
 * api 地址
 * @throws ExecutionException
 * @throws InterruptedException
 *
 * https://ifconfig.me/ip  获取客户端出网ip
 */

代码

import com.aliyun.sdk.service.ecs20140526.models.*;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
@Slf4j
public class AliEcsUtil {

    private static final String DESC = "脚本执行";

    /**
     * 阿里云 esc 获取客户端
     * @return
     */
    private static AsyncClient getAsyncClient(){
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId("")
                .accessKeySecret("")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        return client;
    }


    public static String getLocalIp() throws IOException {
      Document parse = Jsoup.parse(new URL("https://ifconfig.me/ip"), 30000);

      return parse.body().text();
    }


    public static void update() throws ExecutionException, InterruptedException, IOException {

        String localIp = getLocalIp();
        AsyncClient client = getAsyncClient();
        DescribeSecurityGroupAttributeRequest request = DescribeSecurityGroupAttributeRequest.builder()
                .regionId("")
                .securityGroupId("")
                .build();
        CompletableFuture<DescribeSecurityGroupAttributeResponse> response = client.describeSecurityGroupAttribute(request);
        DescribeSecurityGroupAttributeResponseBody.Permissions permissions = response.get().getBody().getPermissions();
        List<DescribeSecurityGroupAttributeResponseBody.Permission> permissionList = permissions.getPermission();
        // 获取所有安全组 判断本地ip 在不在里面,不在里面 修改对应的ip
        for (int i = 0; i < permissionList.size(); i++) {
            DescribeSecurityGroupAttributeResponseBody.Permission permission = permissionList.get(i);
            String description = permission.getDescription();
            if(Objects.equals(DESC,description)){
                String ip = localIp;
                String destCidrIp = permission.getSourceCidrIp();
                // ip 不相等 更新
                if(!Objects.equals(ip,destCidrIp)){
                    updateIp(client,permission.getDestCidrIp(),ip,permission.getSecurityGroupRuleId());
                    return;
                }
            }
        }
    }


    private static void updateIp(AsyncClient client, String sourceRegionId, String ip, String securityGroupRuleId) throws ExecutionException, InterruptedException {
        ModifySecurityGroupRuleRequest modifySecurityGroupRuleRequest = ModifySecurityGroupRuleRequest.builder()
                .sourceRegionId(sourceRegionId)
                .portRange("-1/-1")
                .description(DESC)
                .sourceCidrIp(ip)
                .sourcePortRange("-1/-1")
                .securityGroupId("")
                .securityGroupRuleId(securityGroupRuleId)
                .regionId("")
                .ipProtocol("ALL")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        CompletableFuture<ModifySecurityGroupRuleResponse> res = client.modifySecurityGroupRule(modifySecurityGroupRuleRequest);
        // Synchronously get the return value of the API request
        ModifySecurityGroupRuleResponse resp = res.get();
        log.info("修改ip白名单 {}",resp.getBody());
        client.close();
    }
}

定时任务

  @Scheduled(cron = "0 0 0/1 * * ?")
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void ip(){
        log.info("ip 白名单 任务");
        try {
            AliEcsUtil.update();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

标签:String,ip,client,阿里,ECS,aliyun,白名单,import,com
From: https://www.cnblogs.com/lyc88/p/18332051

相关文章

  • Golang试用阿里通义千问大语言模型
    一、控制台配置通义千问密匙官方操作指南地址控制台地址注意:一个密匙申请之后,官方给了一个月期限共计100万条Token的额度 二、代码阶段1、DashScopRequest结构体 typeEngineRolestringconst(EngineRoleUserEngineRole="user"EngineRoleSystem......
  • 阿里云天池——零基础入门数据挖掘 - 二手车交易价格预测
    赛题数据见官网:零基础入门数据挖掘-二手车交易价格预测_学习赛_天池大赛-阿里云天池的赛制(aliyun.com)因为本人第一次接触神经网络的深度学习,在此就将教学代码逐框解析1.1导入用于数据处理、模型训练、数据加载以及可视化的Python库%matplotlibinlinefromsklearn.m......
  • Springboot使用Thumbnailator压缩图片上传到阿里云OSS
    原文链接:https://blog.csdn.net/weixin_39973810/article/details/86545054前提:图片的压缩大致有两种,一种是将图片的尺寸压缩小,另一种是尺寸不变,将压缩质量,一般对于项目我们需要第一种,即用户上传一张分辨率为3840 × 2160的图片,通过上传图片接口后上传到OSS上的图片分辨率会......
  • 阿里云天池笔记
    一fromsklearn.model_selectionimporttrain_test_splitfromsklearn.linear_modelimportLinearRegressionfromsklearn.ensembleimportRandomForestRegressorimportpandasaspdimportzipfileimportreimportnumpyasnpimporttorch准备工作:安装sk......
  • 【阿里云】通过OpenAPI获取Token(C#)
    使用C#实现https://help.aliyun.com/zh/isi/getting-started/use-http-or-https-to-obtain-an-access-tokenpublicstaticclassTokenHelper{publicstaticasyncTask<string>GetAccessTokenAsync(stringaccessKeyId,stringaccessKeySecret){......
  • 实战之oss附件批量下载---springboot 实现压缩阿里云oss附件并下载
    实战之oss附件批量下载,借鉴网上一些案例,但是没有达到预期效果,结合项目需求。实现远程将oss上的文件进行压缩,并提供给前端用户下载,经过测试完美实现该功能。@PostMapping("downLoadZip")publicvoiddownLoadZip(@RequestBodyCourseDetailVodetailVo,......
  • 二手车预测-阿里云天池
    %matplotlibinlinefromsklearn.model_selectionimporttrain_test_splitfromtorch.utils.dataimportTensorDataset,DataLoaderimportpandasaspdimportzipfileimportreimportnumpyasnpimporttorchfromtorchimportnnfrommatplotlib_inlineimpor......
  • Centos的yum源更换为国内的阿里云源
    1、备份mv/etc/yum.repos.d/CentOS-Base.repo/etc/yum.repos.d/CentOS-Base.repo.backup2、下载新的CentOS-Base.repo到/etc/yum.repos.d/ CentOS5wget-O/etc/yum.repos.d/CentOS-Base.repohttp://mirrors.aliyun.com/repo/Centos-5.repo或者curl-o/etc/yum.repo......
  • STM32+ESP8266-连接阿里云-创建云产品流转实现STM32与Android app通讯(1)
    前言本文章的内容为STM32通过ESP8266利用AT指令连接阿里云平台,并创建设备和创建云产品流转主题,来为实现Androidapp与STM32的发送接收数据做准备。Androidapp的实现由于篇幅不宜过长,将放到下一篇文章中。演示视频实现一个简单的app来控制stm32开关灯、蜂鸣器、门(舵机),显示温......
  • 如何从自建开源 Prometheus 迁移到阿里云托管 Prometheus 服务
    作者:颍川引言Prometheus[1]已成为可观测指标领域的事实标准。由于各方面因素,当前还有部分用户的部分场景仍使用“自建开源Prometheus+自建开源Thanos+自建Grafana”来实现基础设施和业务应用的指标监控和告警。阿里云可观测监控Prometheus版[2]全面对接开源Promethe......