Home System Tutorial LINUX How to configure security groups for cloud hosts in batches in Python?

How to configure security groups for cloud hosts in batches in Python?

Jul 02, 2024 am 03:16 AM
linux linux tutorial Red Hat linux system linux command linux certification red hat linux linux video

How to configure security groups for cloud hosts in batches in Python?

The biggest change for operation and maintenance personnel in recent years may be the emergence of public cloud. I believe that many small partners may run their business on public cloud. Because of the company's business relationship, I personally came into contact with public cloud very early. I started using Amazon Cloud around 2012, and later gradually came into contact with domestic Alibaba, Tencent Cloud, etc. As the company's business developed domestically, we have also used many domestic public cloud vendors in the past few years, so in cloud operation and maintenance I have also accumulated some experience in moving from traditional physical machines to public cloud operation and maintenance. I personally think the biggest question is whether you can think in terms of public cloud to achieve a safe, stable, scalable and economical business architecture.

Cloud operation and maintenance is different from traditional operation and maintenance. For example, anyone who understands public cloud knows the concept of security group. The function of security group is very similar to that of firewall. So do I need to set up iptables or security group on my machine? Do I also need to set up iptables after setting up a security group? What's the difference between them? I believe many people are a little confused about these. Based on my personal experience (because I have never configured iptables for a cloud host since I came into contact with Amazon), my suggestion is that if you can use security groups, you should not use iptables to manage the machine, because They have essential differences:

First, security groups intercept on the host, and iptables intercept on the system level. That is to say, if someone wants to attack you, if you use the security group method, the attack package will not reach your machine at all.

Second, configuring iptables is a complex project. If you are not careful, the consequences will be devastating. I guess those who have 2 years of operation and maintenance experience should have the experience of shutting themselves out of the host. If you use security groups This aspect is controllable, and even if something goes wrong, you can basically recover quickly.

Third, iptables writes a large number of repeated rules on each server, and these rules cannot be managed hierarchically. Security groups manage the security configuration of the machine by layer. You only need to adjust the parts you need to change. Manage machines in batches.

ok, that’s where the concept is introduced. Next we have to get into the practical stuff, because configuring hundreds of machines with different security groups is a big project. If you do it on the console, I think you will go crazy, so this Speaking of how to manage and operate these security groups in batches, the API provided by the public cloud is used here. Because the public cloud j basically has its own API interface, so calling their API to achieve some automated operations I think it is necessary for every user to You must learn how to build your own business operation and maintenance using the public cloud. Today I will share how to add and remove security groups in batches for a large number of machines. The script itself is encapsulated on the basis of qcloudcli. The script is as follows:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import subprocess

import json

import sys

import argparse

def R(s):

return “%s[31;2m%s%s[0m”%(chr(27), s, chr(27))

def get_present_sgid(vmid):

descmd = ‘/usr/bin/qcloudcli dfw  DescribeSecurityGroups –instanceId ‘ + vmid.strip()

p = subprocess.Popen(descmd, shell=True, stdout=subprocess.PIPE)

output = p.communicate()[0]

res = json.loads(output)

sgid = []

for d in res[‘data’]:

sid = d[‘sgId’]

sgid.append(str(sid))

return sgid

def make_json(vmid,sgid):

pdata = {}

pdata[“instanceId”] = vmid

pdata[“sgIds”] = sgid

pjson = json.dumps(pdata)

return pjson

def add_sgid(vmfile,newsid):

fi = open(vmfile)

for v in fi:

v = v.strip()

res = get_present_sgid(v)

print res

res.append(newsid)

pjson = make_json(v,res)

modcmd = ‘qcloudcli dfw ModifySecurityGroupsOfInstance –instanceSet ‘ + “‘[” + pjson+ “]'”

p = subprocess.Popen(modcmd, shell=True, stdout=subprocess.PIPE)

output = p.communicate()[0]

print output

def remove_sgid(vmfile,newsid):

fi = open(vmfile)

for v in fi:

v = v.strip()

res = get_present_sgid(v)

res.remove(newsid)

pjson = make_json(v,res)

modcmd = ‘qcloudcli dfw ModifySecurityGroupsOfInstance –instanceSet ‘ + “‘[” + pjson+ “]'”

p = subprocess.Popen(modcmd, shell=True, stdout=subprocess.PIPE)

output = p.communicate()[0]

#print output

if __name__ == “__main__”:

parser=argparse.ArgumentParser(description=’change sgid’, usage=’%(prog)s [options]’)

parser.add_argument(‘-f’,’–file’, nargs=’?’, dest=’filehost’, help=’vmidfile’)

parser.add_argument(‘-g’,’–sgid’, nargs=’?’, dest=’sgid’, help=’sgid’)

parser.add_argument(‘-m’,’–method’, nargs=’?’, dest=’method’, help=’Methods only support to add or remove’)

if len(sys.argv)==1:

parser.print_help()

else:

args=parser.parse_args()

if args.filehost is not None and args.sgid is not None and args.method is not None:

if args.method == ‘add’:

add_sgid(args.filehost, args.sgid)

elif args.method == ‘remove’:

remove_sgid(args.filehost, args.sgid)

else:

print R(‘Methods only support to add or remove’)

else:

print R(‘Error format, please see the usage:’)

parser.print_help()
Copy after login

This script supports adding and deleting a certain security group in batches. -f is followed by a file to write a list of instance IDs. -g is followed by the security group ID to be added and deleted. -m is followed by add and remove operations. It means adding or deleting. The overall idea of ​​the script is to first find out the security group list of the instance, and then add or remove the new security group ID in the list. This is the introduction of the script. Friends are welcome to leave messages for communication.

The above is the detailed content of How to configure security groups for cloud hosts in batches in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

vscode terminal usage tutorial vscode terminal usage tutorial Apr 15, 2025 pm 10:09 PM

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

See all articles