Реализация стандартного шлюза Mikrotik на BeanShell c управлением по telnet (версия 5.1 )

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

Перейти к: навигация, поиск
import ru.bitel.bgbilling.common.DefaultSetup;
import ru.bitel.common.Preferences;
import bitel.billing.server.util.telnet.TelnetSession;
 
    protected void doSync()
	{
 
        String host = gate.getHost();
        int port = gate.getPort();
 
        Preferences gateSetup = new DefaultSetup( gate.getConfig(), "\r\n" );        
 
        String login = gateSetup.get( "login", "root" );
 
        String pswd = gate.getKeyword();
 
        if( log.isDebugEnabled() )
        {
            log.debug( " gate: " + host + ":" + port + " login: " + login + " pswd: " + pswd );
        }
 
        TelnetSession session = null; 			
 
        try
        {
        	int timeout = gateSetup.getInt( "timeout", 10000 );
        	int socketTimeout = gateSetup.getInt( "socket.timeout", 10000 );
        	session = new TelnetSession( host, port );
        	session.setTimeout( timeout );
        	session.setSocketTimeTimeout( socketTimeout );
			session.setEndString( ": " );
			session.connect();
 
 
 
			doCommand( session, login );
			session.setRegexp( "\\[.+?@.+?\\] >.*\\[.+?@.+?\\] >" );			
			doCommand( session, pswd );			
 
			processSession( session );			
        }
        catch ( Exception e )
        {
        	throw new RuntimeException ( e );
        }
        finally
        {
            if( session != null )
            {
                session.disconnect();
            }
        }	
 
	}		
 
protected void processSession( AbstractTerminalSession session )
		throws Exception
	{
		String buffer = doCommand(session,  "ip firewall address-list print without-paging" );
 
		for( UserStatus status : statusList )
		{
			Integer cid = status.contractId;
 
			// правило для этого договора есть на шлюзе
			if ( ruleExists(cid,  buffer ) )
			{
				//	если правило есть а юзер заблокирован - удаляем правило
				if ( status.status > 0 )
		        {
					//удаляем 
					if ( status.status == IPNContractStatus.STATUS_REMOVED )
					{
						String[]  rules  = getDeleteRules( status );
						for ( String rule : rules )
						{
							doCommand( session, rule );	
						}					
					}			
					//закрываем
					else
					{
						String[] rules = getCloseRules( status );
						for ( String rule : rules )
						{
							doCommand( session, rule );	
						}
					}
 
		        }						
 
			}
 
			else if ( status.status == IPNContractStatus.STATUS_OPEN )
			{
				String[]  rules  = getOpenRules( status );
				for ( String rule : rules )
				{
					doCommand( session, rule );	
				}
 
			}
 
 
 
		}
		session.doCommandAsync( "quit" );
	}
 
	protected String doCommand( AbstractTerminalSession session, String rule )
		throws Exception
	{ 		
		return session.doCommand( rule  );
	}
 
	private boolean ruleExists( Integer cid, String buffer ) throws Exception
	{					
		return buffer.indexOf( "!!" + cid + "!!" ) >= 0;		
	}
 
 
	private String[]  getOpenRules( UserStatus status )
	{
 
		return getRules( status, "\\[OPEN\\](.*)\\[/OPEN\\]" );
	}
 
	private String[]  getCloseRules( UserStatus status )
	{
 
 
		return getRules( status, "\\[CLOSE\\](.*)\\[/CLOSE\\]" );
	}
 
	private String[]  getDeleteRules( UserStatus status )
	{
 
 
		return getRules( status, "\\[DELETE\\](.*)\\[/DELETE\\]" );
	}	
 
 
	private String[]  getRules(  UserStatus status, String template )
	{
		// пользовательское правило, без типа - то все оставляем как есть
		String rule = status.rule.getRuleText();
 
 
 
		//типизированное правило
		if( status.ruleType != null )
 
		{	
			String ruleText = GateCommandUtil.getRule( gateType, status.ruleType );
 
			Map<String, String> replacements = new HashMap<String, String>();
 
			replacements.put( "\\{CID\\}", String.valueOf( status.contractId ) );
 
			rule = GateCommandUtil.generateRule( ruleText, status.rule.getRuleText(), replacements, status.ruleType );
		}
 
 
		Pattern pattern = Pattern.compile( template, Pattern.DOTALL );
		Matcher m = pattern.matcher( rule );
		if (m.find())
		{
			rule = m.group( 1 );
		}		
 
		rule.replaceAll( "\r", "" );
 
 
		String parts [] = rule.trim().split( "\n" );
 
 
		return parts;
	}
Личные инструменты