如何使用"aws ec2"删除给定端口的所有规则?
aws ec2 revoke-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 **--ALL-IP**
根据文档, 此命令适用于--cidr
或--source-group
。 所以如果你有多个IP地址,那么我会说唯一的选择是多次对单个IP地址运行相同的命令(这将采用1.1.1.1/32
的形式)。
或
您可以在文件中列出所有 cidr 格式 (1.1.1.1/32) 的 ipadress(每个 IP 地址都在新行上),然后在每次迭代中运行 for
循环,运行 above 命令。
for i in `cat ip_address_cidr.txt`; do aws ec2 revoke-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 $i; done
我没有测试上面的命令语法,但这应该这样做,以便您可以在单个单行命令中撤销规则。
这就是您要查找的: 如何关闭 AWS 安全组中所有打开的 SSH 端口
下面是特定安全组 ID 的解决方案:
#!/bin/bash
sg = {security group}
# get the cidrs for the ingress rule
rules=$(aws ec2 describe-security-groups --group-ids $sg --output text --query 'SecurityGroups[*].IpPermissions')
# rules will contain something like:
# 22 tcp 22
# IPRANGES 108.42.177.53/32
# IPRANGES 10.0.0.0/16
# 80 tcp 80
# IPRANGES 0.0.0.0/0
# luckily, aws returns all ipranges per port grouped together
# flag for if we are reading ipranges
reading=0
# loop returned lines
while read -r line; do
# split the line up
rulebits=($line)
# check if if we are reading ssh port ipranges
if [ $reading -eq 0 ] ; then
# we are not reading ipranges
# check if '22 tcp 22'
if [ ${rulebits[0]} == "22" ] && [ ${rulebits[1]} == "tcp" ] && [ ${rulebits[2]} == "22" ] ; then
# found it
reading=1
fi
else
# we are reading ipranges
# check if first word is 'IPRANGES'
if [ ${rulebits[0]} == "IPRANGES" ] ; then
# found a cidr for open ssh port
cidr=${rulebits[1]}
echo -n found port 22 open cidr $cidr closing...
# close it
result=$(aws ec2 revoke-security-group-ingress --group-id $sg --protocol tcp --port 22 --cidr $cidr --output text)
if [ "$result" == "true" ] ; then
echo " OK"
else
echo " ERROR"
fi
else
# new port
reading=0
fi
fi
done
2 中的revoke-security-group-ingress
让我们指定多个 IP CIDR。请参阅下面用PHP编写的解决方案,我正在尝试在多个区域和多个程序中清理该解决方案。
要在单个命令中指定多个规则,请使用 --ip-permissions 选项 https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-security-group-ingress.html
$cleanports = [22,5984];
$sgids = [["sgid"=>"sg1","region"=>"us-east-1"],["sgid"=>"sg1","region"=>"us-east-1"]];
foreach($sgids as $sgidDetail){
$iprules = json_decode(shell_exec("/usr/bin/aws ec2 describe-security-groups --group-ids {$sgidDetail['sgid']} --region {$sgidDetail['region']} --query 'SecurityGroups[*].IpPermissions'"), true)[0];
foreach ($iprules as $key => $ips) {
if(!empty($ips['FromPort']) && !empty($ips['ToPort']) && in_array($ips['FromPort'], $cleanports) && in_array($ips['ToPort'], $cleanports)){
echo "nn";
echo shell_exec("/usr/bin/aws ec2 revoke-security-group-ingress --group-id {$sgidDetail['sgid']} --region {$sgidDetail['region']} --ip-permissions '".json_encode($ips)."'");
}
}
}