Docker高级教程之智能添加与修改防火墙规则

2020-06-17 06:44:44易采站长站整理

container_ip=eval(child.value)['Container_ip']if len(container_ip) == 0 and args.container_name != "all":
print 'This container:%s info is not in etcd!'%args.container_name
sys.exit(1)
if '/'+args.container_name not in docker_container_all_name and args.container_name != "all":
print 'local host docker is not container:%s!'%args.container_name
sys.exit(1)
if args.list:
try:
now_firewall_rule=etcd_client.read('%s%s/firewall/nat-%s'%(docker_etcd_key,local_ip,args.container_name)).value
except KeyError:
print 'This container:%s is not firewall rule!'%args.container_name
sys.exit(1)
if len(now_firewall_rule) >0:
now_firewall_rule=eval(now_firewall_rule)
print 'Follow is container:%s firewall rule!'%args.container_name
for i in now_firewall_rule:
print i
else:
print 'This container:%s is not firewall rule!'%args.container_name
sys.exit(1)
if args.portmode=="dynamic":
try:
now_port=etcd_client.read('%s%s/firewall/now_port'%(docker_etcd_key,local_ip)).value
except KeyError:
now_port='40000'
now_port=int(now_port) + 1
key='%s%s/firewall/now_port'%(docker_etcd_key,local_ip)
etcd_client.write(key,now_port)
portmode=args.portmode
elif args.portmode=="manual":
if len(args.sport)>0:
now_port=args.sport
else:
print 'no input source port'
key='%s%s/firewall/now_port'%(docker_etcd_key,local_ip)
etcd_client.write(key,now_port)
#add docker container firewall rule
if args.add:
if args.mode:
if args.source:
if args.source == "all":
source_ip='0.0.0.0/0.0.0.0'
else:
source_ip=args.source
if args.portmode=="dynamic":
sport=now_port
else:
sport=args.sport
if args.dport:
dport=args.dport
else:
print 'please input dest port!This port is container local port!'
sys.exit(1)
try:
now_id=len(eval(etcd_client.read('%s%s/firewall/nat-%s'%(docker_etcd_key,local_ip,args.container_name)).value))
except KeyError:
now_id='0'
except SyntaxError:
now_id='0'
now_id = int(now_id) + 1
if args.mode=="internal":
msg={'Id':now_id,'Mode':args.mode,'Container_name':args.container_name,'Source_ip':source_ip,'Port_mode':portmode,'Source_port':'%s'%sport,'Local_port':dport,'Container_ip':container_ip}
else:
if args.dest:
msg={'Id':now_id,'Mode':args.mode,'Container_name':args.container_name,'Source_ip':source_ip,'Destination_ip':args.dest,'Port_mode':portmode,'Source_port':'%s'%sport,'Local_port':dport,'Container_ip':container_ip}
else:
print 'please input destination ip'
sys.exit(1)
#add rule to iptables
try:
now_firewall_rule=etcd_client.read('%s%s/firewall/nat-%s'%(docker_etcd_key,local_ip,args.container_name)).value
now_firewall_rule=eval(now_firewall_rule)
except KeyError:
now_firewall_rule=[]except SyntaxError:
now_firewall_rule=[]for i in now_firewall_rule:
if msg['Local_port'] == i['Local_port'] and msg['Source_ip'] == i['Source_ip'] and msg['Mode'] == i['Mode'] and msg['Container_name'] == i['Container_name'] and msg['Source_port'] == i['Source_port']: