Пример 1. реализации шлюза Cisco на BeanShell c управлением ssh

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

(Различия между версиями)
Перейти к: навигация, поиск
(не то шлюз, записла вместо этого..вернул обратно)
Строка 1: Строка 1:
-
Подключение абонентов по схеме "vlan-на-клиента", при этом используется оборудование D-Link - на уровне доступа свитчи
+
import java.util.*;
-
DES-1228G, в ядре - DGS-3610-26G.  
+
import java.util.regex.*;
-
Это шлюз ядра(DGS-3610-26G).  
+
import bitel.billing.common.module.ipn.*;
-
 
+
import bitel.billing.server.ipn.bean.*;
-
конфигурация шлюза
+
import bitel.billing.server.util.*;
-
 
+
import bitel.billing.server.util.ssh.*;
-
<source lang="bash">
+
import bitel.billing.common.*;
-
user_rule.editor.class=bitel.billing.module.services.ipn.editor.vlan.CiscoVlanContactRuleEditor
+
import java.util.regex.Pattern;
-
gate_manager.class=bitel.billing.server.ipn.vlan.CiscoVlanGateWorker
+
-
use.script=1
+
-
</source>
+
-
 
+
-
Команды шлюза
+
-
 
+
-
<source lang="bash">
+
-
[DEFAULT]
+
-
 
+
-
[REMOVE]
+
-
no vlan {VID}
+
-
[/REMOVE]
+
-
 
+
-
[OPEN]
+
-
 
+
-
vlan {VID}
+
-
exit
+
-
vlan 100
+
-
subvlan {VID}
+
-
exit
+
-
vlan {VID}
+
-
subvlan-address-range {addr1} {addr2}
+
-
exit
+
-
 
+
-
ip access-list extended 101
+
-
<LOOP>
+
-
no deny ip host {A} any
+
-
no deny ip any host {A}
+
-
</LOOP>
+
-
exit
+
-
[/OPEN]
+
-
 
+
-
[CLOSE]
+
-
interface gigabitethernet 0/22
+
-
no ip access-group 101 in
+
-
exit
+
-
ip access-list extended 101
+
-
no permit ip any any
+
-
<LOOP>
+
-
deny ip host {A} any
+
-
deny ip any host {A}
+
-
</LOOP>
+
-
permit ip any any
+
-
exit
+
-
interface gigabitethernet 0/22
+
-
ip access-group 101 in
+
-
exit
+
-
[/CLOSE]
+
-
[/DEFAULT]
+
-
 
+
-
</source>
+
-
 
+
-
скрпит шлюза
+
-
<source lang="java">
+
-
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.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.*;
 
-
import bitel.billing.server.util.DefaultServerSetup;
 
-
import bitel.billing.server.util.Utils;
 
-
import bitel.billing.server.util.telnet.OperationTimedoutException;
 
-
import bitel.billing.server.util.telnet.TelnetSession;
 
-
import ru.bitel.bgbilling.common.DefaultSetup;
 
-
import bitel.billing.common.IPUtils;
 
-
import bitel.billing.server.util.Utils;
 
-
import bitel.billing.server.util.telnet.OperationTimedoutException;
 
-
import bitel.billing.server.util.telnet.TelnetSession;
 
-
import ru.bitel.bgbilling.modules.ipn.common.bean.*;
 
-
import bitel.billing.server.util.telnet.ansi.TelnetAnsiSession;
 
   
   
-
//includeBGBS( "bgbs://ru.bitel.bgbilling.kernel.script.common.bean.ScriptLibrary/manad" );
 
   
   
protected void doSync()
protected void doSync()
{
{
-
log.info( "start of cisco........................................................");
+
host = gate.getHost();
-
+
port = gate.getPort();
-
host = gate.getHost();
+
gid = gate.getId();
-
port = gate.getPort();
+
   
   
 +
gateSetup = new DefaultServerSetup( gate.getConfig(), "\r\n" );       
   
   
-
DefaultServerSetup gateSetup = new DefaultServerSetup( gate.getConfig(), "\r\n" );      
+
login = gateSetup.getStringValue( "login");  
 +
pswd = gate.getKeyword();
   
   
-
pswd = gate.getKeyword();
+
acl = gateSetup.getStringValue( "acl_name");  
-
login = gateSetup.getStringValue( "login");
+
result = new StringBuffer();  
-
      timeout = gateSetup.getIntValue( "timeout", 0 );
+
   
   
-
result = new StringBuffer();
 
-
 
   
   
-
if( log.isDebugEnabled() )
+
if( log.isDebugEnabled() )  
-
{
+
{  
-
    log.debug( gate.getId() + " gate: " + host + ":" + port  + " login: " + login + " passwd: " + pswd );
+
log.debug( gate.getId() + " gate: " + host + ":" + port  + " login: " + login + " pswd: " +       pswd );  
-
}
+
}
   
   
   
   
-
log.debug("before connect");
 
-
session = new TelnetAnsiSession( host, port);
 
-
      session.setTimeout( timeout );
 
-
session.setLoginPromptSequence( ":" );
 
-
result.append( session.connect() );
 
-
log.debug("after connect");
 
   
   
-
result.append( session.doCommand( login ) );
+
    session = null;
-
log.debug("after login");
+
-
session.setLoginPromptSequence( "#" );
+
-
result.append( session.doCommand( pswd ) );
+
-
log.debug("after pswd");
+
   
   
-
result.append( session.doCommand( "terminal length 0" ) );
+
    try
-
result.append( session.doCommand( "terminal width 0" ) );
+
    {
-
 
+
session = new SSHSession( host, port, login, pswd );
-
log.debug("after terminal");
+
session.connect();
-
 
+
-
result.append( session.doCommand( "configure terminal" ) );
+
   
   
-
log.debug( "execute commands" );
+
result.append(session.command( "terminal length 0" ) );
-
doCommands( session, result, gateSetup );
+
   
   
-
result.append( session.doCommand( "exit" ) );
 
-
result.append( session.doCommand( "write memory" ) );
 
-
session.doCommandAsync( "exit" );
 
-
 
   
   
-
log.info("!!!!!!!!!!!start of log!!!!!!!!!!!!!!!!!!!!!");
+
result = new StringBuffer();
-
log.info( result );
+
result.append( session.command( "configure terminal" ) );
-
log.info("!!!!!!!!!!!!!!! end of log !!!!!!!!!!!!!!!!!");
+
result.append( session.command( "ip access-list standard " + acl ) );
   
   
-
log.debug( "ok" );
+
buffer = getBuffer( session, result, acl );
-
+
doCommands( session, result, buffer );
   
   
-
log.info( "end of cisco........................................................");
+
      result.append( session.command( "end" ) ); 
-
+
      result.append( session.command( "exit", false ) );
-
}
+
   
   
-
protected void add()
 
-
{
 
   
   
 +
      if (log.isDebugEnabled())
 +
      {
 +
        log.debug( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
 +
        log.debug( result.toString() );
 +
        log.debug( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
 +
      }
 +
 +
        // пауза пока считает команду exit
 +
        Thread.sleep( 100 );
 +
    }
 +
    catch ( Exception e )
 +
    {
 +
    throw new RuntimeException ( e );
 +
    }
 +
    finally
 +
    {
 +
        if( session != null )
 +
        {
 +
            session.disconnect();
 +
        }
 +
    }
}
}
   
   
 +
void doCommands( session, result, buffer )
 +
{   
 +
for( status : statusList )
 +
{
 +
log.info( "status.status=" + status.status );
 +
isPermitted = isUserPermited ( status, buffer);
   
   
-
private void doCommands( session, result, gateSetup) throws IOException, OperationTimedoutException
 
-
{
 
-
acl = gateSetup.getStringValue( "acl");
 
-
 
-
vlanResult = getVlanResult( session );
 
-
    log.info( "!!!!!!!!!!!!!!!!!!!!!!!!!!vlanResult!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
 
-
log.info( vlanResult );
 
-
log.info( "!!!!!!!!!!!!!!!!!!!!!!!!!!vlanResult!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
 
-
 
-
aclResult = getAclResult( session, acl );
 
-
 
-
log.info( "!!!!!!!!!!!!!!!!!!!!!!!!!!aclResult!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
 
-
log.info( aclResult );
 
-
log.info( "!!!!!!!!!!!!!!!!!!!!!!!!!! end aclResult!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
 
-
 
-
for( UserStatus status : statusList )
 
-
{
 
-
VlanManager manager = new VlanManager(status.mid, con);
 
-
gateId  = gate.getId();
 
-
//log.info("gateId=" + gateId);
 
-
vid = manager.getVlan( gateId, status.contractId );
 
-
//log.info("vid=" + vid);
 
-
log.debug( "status=" + status.status);
 
   
   
-
 
+
//  если правило есть, а юзер заблокирован - удаляем правило
-
String addr1 = null;
+
-
String addr2 = null;
+
-
+
-
  date = new GregorianCalendar();
+
-
 
+
-
AddressRangeManager man = new AddressRangeManager( con, mid );
+
-
  addressList = man.getContractAddressRange( status.contractId , date, -1 );
+
-
  if ( addressList.size() > 0 )
+
-
  {
+
-
        AddressRange range =  addressList.get(0);
+
-
addr1 = IPUtils.convertIpToString( range.getAddr1() );
+
-
addr2 = IPUtils.convertIpToString( range.getAddr2() );
+
-
}
+
-
else
+
-
{
+
-
log.info( "empty adress on cid = " + status.contractId );
+
-
continue;
+
-
}
+
-
 
+
   
   
-
rules = null;
+
if ( isPermitted && status.status > 0 )
-
if (status.status == IPNContractStatus.STATUS_OPEN && (!vlanExists(vid, vlanResult) ||  isUserDenied( addr1, addr2, aclResult) ) )
+
-
{
+
-
rules = getOpenRules( status, vid, gateSetup, addr1, addr2, acl );
+
-
}
+
-
else if (status.status == IPNContractStatus.STATUS_REMOVED && ( vlanExists(vid, vlanResult) || isUserDenied( addr1, addr2,aclResult)  ) )
+
{
{
-
rules = getRemoveRules( status, vid, gateSetup, addr1, addr2, acl );
+
rules = getCloseRules( status );
}
}
-
//if closed and etc
+
else if ( !isPermitted && status.status == 0 )
-
else if ( status.status != IPNContractStatus.STATUS_OPEN && status.status != IPNContractStatus.STATUS_REMOVED &&  !isUserDenied( addr1, addr2, aclResult) )
+
// правила нет, а юзер открыт - добавляем правило
-
{
+
{
-
rules = getCloseRules( status, vid, gateSetup, addr1, addr2, acl );
+
rules = getOpenRules( status );
}
}
-
+
else
-
if (vid > 0 && rules != null )
+
{
{
-
for ( String rule : rules )
+
continue;
-
{
+
}           
-
//log.debug  ("command=" + rule );
+
for ( rule : rules )
-
result.append(  session.doCommand( rule ) );
+
{
-
}
+
result.append(  session.command( rule ) );
}
}
 +
}
 +
}
   
   
-
}
 
   
   
-
}
+
private List getOpenRules( status )
 +
{
   
   
-
getOpenRules( status, vid, gateSetup, addr1, addr2, acl )
+
log.info( "getting open rules" );
-
{
+
return getRules( status, "\\[OPEN\\]((.|\n)*)\\[/OPEN\\]" );
-
  log.debug( "geting open rules...");  
+
-
return getRules( status, "\\[OPEN\\](.*)\\[/OPEN\\]", vid, gateSetup, addr1, addr2, acl );
+
}
}
   
   
-
getCloseRules( status, vid, gateSetup, addr1, addr2, acl )
+
private List  getCloseRules( status )
{
{
-
  log.debug( "geting close rules...");
+
log.info( "getting close rules" );
-
return getRules( status, "\\[CLOSE\\](.*)\\[/CLOSE\\]", vid, gateSetup, addr1, addr2, acl );
+
return getRules( status, "\\[CLOSE\\]((.|\n)*)\\[/CLOSE\\]");
}
}
   
   
-
getRemoveRules( UserStatus status, vid, gateSetup, addr1, addr2, acl )
 
-
{   
 
-
  log.debug( "geting remove rules..."); 
 
-
return getRules( status, "\\[REMOVE\\](.*)\\[/REMOVE\\]", vid, gateSetup, addr1, addr2, acl );
 
-
}
 
   
   
-
getRules( status, template, vid, gateSetup, addr1, addr2, acl )
+
 +
 +
private List  getRules( status, String template )
{
{
// пользовательское правило, без типа - то все оставляем как есть
// пользовательское правило, без типа - то все оставляем как есть
-
CiscoRule  ciscoRule = new CiscoRule ( status.rule.getRuleText() );
+
rule = status.rule.getRuleText();
-
rule = ciscoRule.getAddresses();
+
-
 
+
-
//log.info("rule=" + rule);
+
   
   
//типизированное правило
//типизированное правило
Строка 259: Строка 134:
   
   
{
{
-
    rule = generateRule( rule, status.gateType, status.ruleType, vid, status.contractId, gateSetup, addr1, addr2, acl );
+
ruleText = ManadUtils.getRule( status.gateType, status.ruleType );
-
}
+
Map replacements = new HashMap ();
-
   
+
rule = ManadUtils.generateRule( ruleText, status.rule.getRuleText(), replacements, status.ruleType );
-
//log.info("rule=" + rule);
+
}
-
+
-
+
   
   
-
pattern = Pattern.compile( template, Pattern.DOTALL );
+
Pattern pattern = Pattern.compile( template );
-
m = pattern.matcher( rule );
+
Matcher m = pattern.matcher( rule );
if (m.find())
if (m.find())
{
{
-
    rule = m.group( 1 );
+
rule = m.group( 1 );
}
}
 +
 +
log.info("rule=" + rule);
   
   
rule.replaceAll( "\r", "" );
rule.replaceAll( "\r", "" );
-
 
-
 
parts  = rule.split( "\n" );
parts  = rule.split( "\n" );
   
   
result = new ArrayList();
result = new ArrayList();
-
for ( String part : parts )
+
for ( part : parts )
{
{
if ( !Utils.isEmptyString( part ))
if ( !Utils.isEmptyString( part ))
Строка 286: Строка 159:
}
}
}
}
 +
   
   
return result;
return result;
-
}
+
}
   
   
-
generateRule( addresses, gateType, ruleType, int vid, int cid, gateSetup, addr1, addr2, acl )
+
private getBuffer( session, result, acl )
-
{
+
-
supervlan = gateSetup.getIntValue( "supervlan", 0 );
+
-
+
-
Map replacements = new HashMap();
+
-
+
-
        if ( addr1 != null && addr2 != null )
+
-
{
+
-
replacements.put( "\\{addr1\\}", addr1 );
+
-
replacements.put( "\\{addr2\\}", addr2 );
+
-
replacements.put( "\\{SUPERVLAN\\}", String.valueOf( supervlan) );
+
-
replacements.put( "\\{ACL\\}", acl );
+
-
}
+
-
 
+
-
    ruleText = ManadUtils.getRule( gateType, ruleType );
+
-
    if ( vid > 0)
+
-
    {
+
-
        replacements.put( "\\{VID\\}", String.valueOf( vid ) );
+
-
    }
+
-
    return ManadUtils.generateRule( ruleText, addresses, replacements, ruleType );
+
-
}
+
-
 
+
-
private isUserDenied ( addr1, addr2, buffer)
+
{
{
-
//эскейпируем точки в адресе
+
buffer = session.command( "do sh ip access-list " + acl );  
-
String address1 = addr1.replace( ".", "\\." );
+
result.append( buffer );
-
String address2 = addr2.replace( ".", "\\." );
+
return buffer;
-
 
+
-
return isUserDeniedForAddress( address1, buffer ) &&  isUserDeniedForAddress( address2, buffer );
+
}
}
-
 
+
-
private isUserDeniedForAddress ( address, buffer)
+
private isUserPermited ( status, buffer)
{
{
-
//эскейпируем точки в адресе
+
addreses = status.rule.getRuleText().split( "\\s*,\\s*" );
-
//String address = addr1.replace( ".", "\\." );
+
//
-
//log.debug( "aaddr1=" + address );
+
for ( i = 0; i < addreses.length; i++)
-
String template = ".*deny ip host\\s+" + address + "\\s+any.*$";
+
{
-
//log.debug( "template=" + template );
+
address = IPUtils.convertLongIpToString( Utils.parseLongString( addreses[i], 0 ) );
-
Pattern pattern = Pattern.compile( template, Pattern.DOTALL );
+
log.info( "ip=" + address);
-
Matcher m = pattern.matcher( buffer );
+
-
boolean found = m.find();
+
address = address.replace( ".", "\\." );
-
if ( found )  
+
-
{
+
Pattern pattern = Pattern.compile( ".*permit\\s" + address + "(\\s.*)?$", Pattern.DOTALL );
-
log.debug( "user2 denied" );
+
        Matcher m = pattern.matcher( buffer );
-
return true;
+
//если хотя бы один адрес отстуствует, то считаем что клиент закрыт       
-
}
+
if ( !m.find() )
-
 
+
{
-
+
log.info( "is not permitted" );
-
+
return false;
-
pattern = Pattern.compile( ".*deny ip any host\\s" + address + "\\s.*$", Pattern.DOTALL );
+
}  
-
m = pattern.matcher( buffer );
+
-
found = m.find();
+
}
-
log.debug( found ? "user denied" :"user not denied" );
+
log.info( "is permitted" );
-
+
return true;
-
+
-
return found;
+
-
 
+
-
}
+
-
 
+
-
 
+
-
private vlanExists ( vlan, buffer)
+
-
{
+
-
Pattern pattern = Pattern.compile( ".*" + vlan + "\\s+ON\\s+.*", Pattern.DOTALL );
+
-
Matcher m = pattern.matcher( buffer );
+
-
found = m.find();
+
-
log.debug( found ? "vlan found" : "vlan not found" );
+
-
+
-
 
+
-
return found;
+
-
}
+
-
 
+
-
private getVlanResult( session )
+
-
{
+
-
return session.doCommand( "show supervlan");  
+
-
}
+
-
 
+
-
private getAclResult( session, acl )
+
-
{
+
-
return session.doCommand( "show access-lists " + acl );  
+
}
}
-
 
-
</source>
 

Версия 06:22, 16 апреля 2010

import java.util.*; import java.util.regex.*; import bitel.billing.common.module.ipn.*; import bitel.billing.server.ipn.bean.*; import bitel.billing.server.util.*; import bitel.billing.server.util.ssh.*; import bitel.billing.common.*; import java.util.regex.Pattern; import java.util.regex.Matcher;


protected void doSync() { host = gate.getHost(); port = gate.getPort(); gid = gate.getId();

gateSetup = new DefaultServerSetup( gate.getConfig(), "\r\n" );

login = gateSetup.getStringValue( "login"); pswd = gate.getKeyword();

acl = gateSetup.getStringValue( "acl_name"); result = new StringBuffer();


if( log.isDebugEnabled() ) { log.debug( gate.getId() + " gate: " + host + ":" + port + " login: " + login + " pswd: " + pswd ); }


   session = null;

   try
   {

session = new SSHSession( host, port, login, pswd ); session.connect();

result.append(session.command( "terminal length 0" ) );


result = new StringBuffer(); result.append( session.command( "configure terminal" ) ); result.append( session.command( "ip access-list standard " + acl ) );

buffer = getBuffer( session, result, acl ); doCommands( session, result, buffer );

      result.append( session.command( "end" ) );  
      result.append( session.command( "exit", false ) );


      if (log.isDebugEnabled())
      {
       	log.debug( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
       	log.debug( result.toString() );
       	log.debug( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
      }

       // пауза пока считает команду exit
       Thread.sleep( 100 );
   }
   catch ( Exception e )
   {
   	throw new RuntimeException ( e );
   }
   finally
   {
       if( session != null )
       {
           session.disconnect();
       }
   }

}

void doCommands( session, result, buffer ) { for( status : statusList ) { log.info( "status.status=" + status.status ); isPermitted = isUserPermited ( status, buffer);


// если правило есть, а юзер заблокирован - удаляем правило

if ( isPermitted && status.status > 0 ) { rules = getCloseRules( status ); } else if ( !isPermitted && status.status == 0 ) // правила нет, а юзер открыт - добавляем правило { rules = getOpenRules( status ); } else { continue; } for ( rule : rules ) { result.append( session.command( rule ) ); } } }


private List getOpenRules( status ) {

log.info( "getting open rules" ); return getRules( status, "\\[OPEN\\]((.|\n)*)\\[/OPEN\\]" ); }

private List getCloseRules( status ) { log.info( "getting close rules" ); return getRules( status, "\\[CLOSE\\]((.|\n)*)\\[/CLOSE\\]"); }



private List getRules( status, String template ) { // пользовательское правило, без типа - то все оставляем как есть rule = status.rule.getRuleText();


//типизированное правило if( status.ruleType != null )

{ ruleText = ManadUtils.getRule( status.gateType, status.ruleType ); Map replacements = new HashMap (); rule = ManadUtils.generateRule( ruleText, status.rule.getRuleText(), replacements, status.ruleType ); }

Pattern pattern = Pattern.compile( template ); Matcher m = pattern.matcher( rule ); if (m.find()) { rule = m.group( 1 ); }

log.info("rule=" + rule);

rule.replaceAll( "\r", "" ); parts = rule.split( "\n" );

result = new ArrayList(); for ( part : parts ) { if ( !Utils.isEmptyString( part )) { result.add( part ); } }


return result; }

private getBuffer( session, result, acl ) { buffer = session.command( "do sh ip access-list " + acl ); result.append( buffer ); return buffer; }

private isUserPermited ( status, buffer) { addreses = status.rule.getRuleText().split( "\\s*,\\s*" ); // for ( i = 0; i < addreses.length; i++) { address = IPUtils.convertLongIpToString( Utils.parseLongString( addreses[i], 0 ) ); log.info( "ip=" + address);

address = address.replace( ".", "\\." );

Pattern pattern = Pattern.compile( ".*permit\\s" + address + "(\\s.*)?$", Pattern.DOTALL );

       Matcher m = pattern.matcher( buffer );

//если хотя бы один адрес отстуствует, то считаем что клиент закрыт if ( !m.find() ) { log.info( "is not permitted" ); return false; }

} log.info( "is permitted" ); return true; }

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