大网数据广告活动
服务器运维问答

How to delete all ufw rules for a certain port?

· 52CE 我爱测

I am using ansible to configure ufw on my DB servers to only let accept connections from certain servers connection to a specific port (lets say 1234 ). When a server that used to have access is taken out of the pool, it might be…

问题原文

原帖链接 · Benjamin · CC BY-SA 3.0

I am using ansible to configure ufw on my DB servers to only let accept connections from certain servers connection to a specific port (lets say 1234).

When a server that used to have access is taken out of the pool, it might be forgotten to remove the access rule for that server.

My solution: When setting up the rules, I want to delete all rules for port 1234, and then recreate them with the servers from the current pool.

Unfortunately ufw delete requires to precisely specify the rule to be deleted (port,protocol, scr IP,...).

I tried a solution like ufw delete $(ufw status numbered | grep 1234 | <get all the numbers of the rules> ), but it got really ugly, really fast.

Is there a better way to delete all rules for a certain port?

社区高分解答

原帖链接 · Sysfu · CC BY-SA 3.0

There are two problems that need to be solved here:

  1. generate a list of ufw rule numbers which match a desired string.
  2. have the shell expand this list and tack it on the end of a sequence of 'ufw delete [rule number]' commands.

I think I have a solution for problem #1 via this one liner in bash:

ufw status numbered |(grep '80/tcp'|awk -F"[][]" '{print $2}')

The example above matches any firewall rule for the string '80/tcp' and prints just the rule number with the brackets stripped.

I have not solved problem #2 yet because as best I can tell, the 'ufw delete' command does not have a switch that suppresses the '(y|n)' confirmation prompt, thus foiling automation.

You can run the command below however and manually hammer out each rule deletion by hitting the 'y' key to confirm and then up arrow => enter to rinse and repeat

ufw delete $(ufw status numbered |(grep '80/tcp'|awk -F"[][]" '{print $2}'))

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2014-07-24)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。