Шлюз Cisco2, учитывающий периоды действия дипазонов

Материал из BiTel WiKi

Перейти к: навигация, поиск

Скрипт будет анализирует сети( адреса), привязанный к шлюзу и проверяет- есть ли такая сеть(диапазон) среди действующих сетей(диапазонов) договора( с учетом сроков действия) . Если нет , то закрывать доступ к этому адресу, в независимости от статуса шлюза.

конфигурация шлюза

user_rule.editor.class=bitel.billing.module.services.ipn.editor.vlan.CiscoVlanContactRuleEditor
gate_manager.class=bitel.billing.server.ipn.vlan.CiscoVlanGateWorker
use.script=1

Команды:

[DEFAULT]
 
 
[OPEN]
 
<LOOP_NET> 
access-template bgb-in dynamic-in {IP} {MASK_WILD} any 
access-template bgb-out dynamic-out any {IP} {MASK_WILD} 
</LOOP_NET> 
 
<LOOP> 
access-template bgb-in dynamic-in host {A} any
access-template bgb-out dynamic-out any host {A}
</LOOP> 
 
 
[/OPEN]
 
[CLOSE]
<LOOP_NET> 
clear access-template bgb-in dynamic-in {IP} {MASK_WILD} any 
clear access-template bgb-out dynamic-out any {IP} {MASK_WILD} 
</LOOP_NET> 
 
<LOOP> 
clear access-template bgb-in dynamic-in host {A} any
clear access-template bgb-out dynamic-out any host {A}
</LOOP> 
 
[/CLOSE]
 
[/DEFAULT]


Скрипт:

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.StringTokenizer;
 
import bitel.billing.common.module.ipn.IPNContractStatus;
import bitel.billing.server.ipn.GateWorker;
import bitel.billing.server.ipn.UserStatus;
import bitel.billing.server.ipn.bean.VlanManager;
import bitel.billing.server.util.DefaultServerSetup;
import bitel.billing.server.util.Utils;
import bitel.billing.server.util.telnet.TelnetSession;
import ru.bitel.bgbilling.common.DefaultSetup;
import bitel.billing.common.IPUtils;
import bitel.billing.server.ipn.bean.GateType;
import bitel.billing.server.ipn.bean.RuleType;
import bitel.billing.server.ipn.bean.VlanManager;
import bitel.billing.server.util.Utils;
import bitel.billing.server.util.telnet.TelnetSession;
import ru.bitel.bgbilling.modules.ipn.server.bean.command.*;
import ru.bitel.bgbilling.modules.ipn.common.bean.*;
 
 
protected void doSync()
{
 
	log.info( "start of cisco........................................................");
	host = gate.getHost();
	port = gate.getPort();
 
 
	DefaultServerSetup gateSetup = new DefaultServerSetup( gate.getConfig(), "\r\n" );        
 
	String login = gateSetup.getStringValue( "login" );
	String pswd = gate.getKeyword();
    timeout = gateSetup.getIntValue( "timeout", 0 );
 
 
	result = new StringBuffer();
 
 
	if( log.isDebugEnabled() )
	{
		log.debug( gate.getId() + " gate: " + host + ":" + port  + " login: " + login + " pswd: " + 		 pswd );
	}
 
 	log.info( "before connect.." );
 
	session = new TelnetSession( host, port);
    session.setTimeout( timeout );
	session.setEndString( ":" );						
	result.append( session.connect() );
	log.info( "after connect.." );
 
	result.append( session.doCommand( login ) );
	log.info( "after login.." );
 
	session.setLoginPromptSequence( "#" );
	result.append( session.doCommand( pswd ) );
 
	log.info( "after pswd.." );
 
	result.append( session.doCommand( "terminal length 0" ) );
	result.append( session.doCommand( "terminal width 0" ) ); 
 
	//result.append( session.doCommand( "configure terminal" ) );
 
	log.debug( "execute commands" );
	doCommands( session, result);
 
	//result.append( session.doCommand( "exit" ) );
    session.doCommandAsync( "exit" );
 
	log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
	log.info( result );
	log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");		
 
	log.debug( "ok" );
 
 
	log.info( "end of cisco........................................................");
}
 
protected void add()
{
 
}
 
 
private void doCommands( TelnetSession session, StringBuffer result) throws IOException
{		
 
	//String accessList100 = session.doCommand( "show access-list 100" ); 
	//result.append( accessList100 );
	//String accessList101 = session.doCommand( "show access-list 101" ); 
	//result.append( accessList101 );
 
	String accessList100 = session.doCommand( "show access-list bgb-in" ); 
	result.append( accessList100 );
	String accessList101 = session.doCommand( "show access-list bgb-out" ); 
	result.append( accessList101 );
 
	for( UserStatus status : statusList )
	{
 
		log.info(" begin new cid = " +  status.contractId );
		gateId  = gate.getId();
		log.info("gateId=" + gateId);
 
		VlanManager manager = new VlanManager(status.mid, con); 
		vid = manager.getVlan( gateId, status.contractId );
		log.info("vid=" + vid);	
 
		String ruleText = status.rule.getRuleText();
		//во  такой вот хитрый способо распарсить
		List loops = GateCommandUtil.getAddresLoops( ruleText );
 
 
		List goodList = new ArrayList(); 
		List badList = new ArrayList();
 
		classifyIp(  loops, status.contractId, goodList, badList);
 
 
		boolean  checked = check ( session, status, goodList, accessList100, status.status == IPNContractStatus.STATUS_OPEN );
		checked = checked && check ( session, status, goodList, accessList101, status.status == IPNContractStatus.STATUS_OPEN );
		log.info(" after first check" );	
 
 
 
		List rules = new ArrayList();
		if ( !checked )
		{
			if ( status.status == IPNContractStatus.STATUS_OPEN )
			{						
				rules = getOpenRules( status, vid, ruleText, goodList ); 	
			} 				
			//if closed and etc 
			else 
			{
				rules = getCloseRules( status, vid, ruleText, goodList );
			}		
		}
 
		for ( String rule : rules )
		{									
			result.append(  session.doCommand( rule ) );				
		}
 
		checked = check ( session, status, badList, accessList100, false );
		checked = checked && check ( session, status, badList, accessList101, false );
 
		if ( !checked )
		{	
			List badRules = new ArrayList();	
			badRules = 	getCloseRules( status, vid, ruleText, badList );
 
			for ( String rule : badRules )
			{									
				result.append(  session.doCommand( rule ) );				
			}
		}
 
		log.info(" end  cid = " +  status.contractId );
 
	}		
 
}
 
getOpenRules( status, vid, String ruleText, List loops )
{
    return getRules( status, "\\[OPEN\\](.*)\\[/OPEN\\]", vid, ruleText, loops );
}
 
getCloseRules( status, vid, String ruleText, List loops )
{
    return getRules( status, "\\[CLOSE\\](.*)\\[/CLOSE\\]", vid, ruleText, loops );
}
 
 
getRules(  status, template, vid, String ruleText , List loops )
{
	// пользовательское правило, без типа - то все оставляем как есть
	rule = ruleText;
	log.info("rule=" + rule);
 
	//типизированное правило
	if( status.ruleType != null )
 
	{	
	    rule = generateRule( rule, status.gateType, status.ruleType, vid, loops );
	}
 
	log.info("rule=" + rule);
 
 
 
	pattern = Pattern.compile( template, Pattern.DOTALL );
	m = pattern.matcher( rule );
	if (m.find())
	{
	    rule = m.group( 1 );
	}		
 
	rule.replaceAll( "\r", "" );
 
 
	parts  = rule.split( "\n" );
 
	result = new ArrayList();
	for ( String part : parts )
	{
		if ( !Utils.isEmptyString( part ))
		{
			result.add( part );
		}
	}
 
	return result;
}		
 
generateRule( addresses, gateType, ruleType, int vid, List loops )
{		
    ruleText = GateCommandUtil.getRule( gateType, ruleType );
    replacements =  new HashMap ();
    if ( vid > 0)
    {
        replacements.put( "\\{VID\\}", String.valueOf( vid ) );
    }
    return GateCommandUtil.generateRule( ruleText, replacements, ruleType, loops );		
}
 
 
private boolean check ( TelnetSession session, status,  List loops, String accessList, boolean opened )
{
	//String accessList = session.doCommand( "show access-list " + acl ); 
	//result.append( accessList );
 
	boolean result 	= true;
 
	LOOP:
	for ( LoopPattern pattern : loops )
	{
		for ( List list : pattern.getObjects() )
		{
 
			String address = list.get( 0 );
 
			log.info( "ip=" + address); 
			//address = address.replace( ".", "\\." );
			//log.info( "ip after replace");
			//Pattern pattern = Pattern.compile( ".*permit.*?" + address + ".*?$", Pattern.DOTALL );
			//log.info( "after pattern compile" );
        	//Matcher m = pattern.matcher( accessList );
			//log.info( "after matcher" );
			boolean found = accessList.indexOf( address ) > 0; 
			//m.find();
			log.info( "found = "  + found );
 
			if ( opened )
			{
				//если хотя бы один адрес отстуствует, то считаем что клиент закрыт 
				if ( !found )													
				{					
					result = false;
					break LOOP;
				} 			
			}
			else
			{
				//когда ищем мертвые адреса , то еслихотя бы один адрес присуствет, то считаем что клиент открыт
				if ( found )													
				{					
					result = false;
					break LOOP;
				} 			
			}
 
		}	
 
	}
 
	log.info( result ? "checked = true" : "checked = false" );	
	return result;
}
 
/*
удаляем те ip, которые сейчас не действуют	
*/
void classifyIp(  List loops, int cid, List goodList, List badList )
{		
	///обнуляем		
	AddressRangeManager man = new AddressRangeManager( con, mid );
   	addressList = man.getContractAddressRange( cid, new GregorianCalendar(), -1 );
 
	for ( int i = 0; i < loops.size(); i++  )
	{
		LoopPattern pattern = loops.get( i );
 
		LoopPattern goodPatern = new  LoopPattern();
		goodPatern.setLoopPatern( pattern.getLoopPatern() );
		goodPatern.setReplacements( pattern.getReplacements() );		
		goodList.add( goodPatern ) ;
 
		LoopPattern badPatern = new  LoopPattern();
		badPatern.setLoopPatern( pattern.getLoopPatern() );
		badPatern.setReplacements( pattern.getReplacements() );		
		badList.add( badPatern ) ;
 
 
		for ( List list : pattern.getObjects() )
		{	
			String address = list.get( 0 );			
 
			boolean found = false; 
			long laddress = IPUtils.convertStringIPtoLong( address );
			AddressRange foundRange = null;
 
			for ( AddressRange range : addressList )
			{
 
				//адрес
				if ( i == 0 && range.getAddr1()  <= laddress 	&& range.getAddr2() >= laddress )
				{
					found = true;
					break;
				}
 
 
				//сеть
				if ( i == 1 && range.getAddr1() == 		laddress )
				{
					found = true;
					break;
				}
 
 
			}
 
			if ( found )
			{					
				log.info( "is good" );
				goodPatern.getObjects().add( list );
			}
			else
			{
				log.info( "is bad" );
				badPatern.getObjects().add( list );
			}	
 
		}
 
 
	}
 
 
}
Личные инструменты