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

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

Версия от 07:26, 5 августа 2010; Stark (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

       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 );
       }
       SSHSession session = null;
       int timeout = gateSetup.getInt( "timeout", 0 );
       try
       {
           session = new SSHSession( host, port, login, pswd );
           session.setTimeout( timeout );
           session.setRegexp( "\\[.+?@.+?\\] >.*\\[.+?@.+?\\] >" );            
           session.connect();
           processSession(  session );
       }
       catch( Exception e )
       {
           throw new RuntimeException( e );
       }
       finally
       {
           if ( session != null )
           {
               session.disconnect();
           }
       }	

}


public static String generateRule( String addresses, GateType gateType, RuleType ruleType, int cid ) { String rule; Map<String, String> replacements = new HashMap<String, String>(); replacements.put( "\\{CID\\}", String.valueOf( cid ) );

String ruleText = GateCommandUtil.getRule( gateType, ruleType ); rule = GateCommandUtil.generateRule( ruleText, addresses, replacements, ruleType ); return rule; } 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; }

Личные инструменты