Exemplo n.º 1
0
def page_channel(feature_code):

    try:
        # connect to the manager
        try:
            manager.connect(CONNECT_IP)
            manager.login(LOGIN_UN, LOGIN_PW)

            # get a status report
            response = manager.status()
            #print(response)
            # Logic to do the dialing
            response = manager.command(
                'channel originate Local/*{0}@app-miscapps extension {1}@ext-paging'
                .format(feature_code, PAGING_GROUP))
            #print(response.data)

            manager.logoff()
        except asterisk.manager.ManagerSocketException as e:
            print("Error connecting to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerAuthException as e:
            print("Error logging in to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerException as e:
            print("Error: %s") % e.strerror
            sys.exit(1)

    finally:
        # remember to clean up
        manager.close()
Exemplo n.º 2
0
def call():
    app.logger.debug('Start call')
    inline = request.form['inline']
    exten = request.form['exten']

    channel = 'SIP/%s' % inline
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        app.logger.debug(
            'Try to connect to asterisk_address=%s and asterisk_port=%s' %
            (config.ASTERISK_ADDRESS, config.ASTERISK_PORT))
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        app.logger.debug(
            'Try to login to asterisk_login=%s and asterisk_password=%s' %
            (config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD))
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        app.logger.debug('Try to call channel=%s and exten=%s' %
                         (channel, exten))
        response = manager.originate(channel,
                                     exten,
                                     caller_id='call_from_CRM <CRM>',
                                     async=True).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 3
0
def make_call(call):
    manager = asterisk.manager.Manager()
    manager.lock = threading.Condition()
    try:
        try:
            call.start = datetime.datetime.now()

            # connect to the manager
            manager.connect(settings.AST_HOST)
            manager.login(settings.AST_USER, settings.AST_PASS)

            # register some callbacks
            manager.register_event('Shutdown', handle_shutdown)  # shutdown
            manager.register_event('*', lambda event, manager: handle_event(
                event, manager, call))  # catch all

            # get a status report
            response = manager.originate(call.channel, call.extension,
                                         call.context, settings.AST_PRIO,
                                         settings.AST_TIMEOUT_ORIGINATE * 1000,
                                         call.caller_id)
            call.response = response.get_header('Response')
            with manager.lock:
                manager.lock.wait(settings.AST_TIMEOUT_HANGUP)

        except asterisk.manager.ManagerSocketException, (errno, reason):
            msg = "Error connecting to the manager: %s" % reason
            call.disposition = msg
            raise
        except asterisk.manager.ManagerAuthException, reason:
            msg = "Error logging in to the manager: %s" % reason
            call.disposition = msg
            raise
Exemplo n.º 4
0
def page_channel(feature_code):

    try:
        # connect to the manager
        try:
            manager.connect(CONNECT_IP)
            manager.login(LOGIN_UN, LOGIN_PW)

            # get a status report
            response = manager.status()
            # print(response)
            # Logic to do the dialing
            response = manager.command(
                "channel originate Local/*{0}@app-miscapps extension {1}@ext-paging".format(feature_code, PAGING_GROUP)
            )
            # print(response.data)

            manager.logoff()
        except asterisk.manager.ManagerSocketException as e:
            print("Error connecting to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerAuthException as e:
            print("Error logging in to the manager") % e.strerror
            sys.exit(1)
        except asterisk.manager.ManagerException as e:
            print("Error: %s") % e.strerror
            sys.exit(1)

    finally:
        # remember to clean up
        manager.close()
Exemplo n.º 5
0
def make_call(call):
  manager = asterisk.manager.Manager()
  manager.lock = threading.Condition()
  try:  
    try:
	call.start = datetime.datetime.now()

        # connect to the manager
        manager.connect(settings.AST_HOST)
        manager.login(settings.AST_USER, settings.AST_PASS)

        # register some callbacks
        manager.register_event('Shutdown', handle_shutdown) # shutdown
        manager.register_event('*', lambda event, manager: handle_event(event,manager,call)) # catch all

        # get a status report
        response = manager.originate(call.channel, call.extension, call.context, settings.AST_PRIO, settings.AST_TIMEOUT_ORIGINATE * 1000, call.caller_id)
        call.response = response.get_header('Response')
        with manager.lock:
            manager.lock.wait(settings.AST_TIMEOUT_HANGUP)

    except asterisk.manager.ManagerSocketException, (errno, reason):
       msg = "Error connecting to the manager: %s" % reason
       call.disposition = msg
       raise
    except asterisk.manager.ManagerAuthException, reason:
       msg = "Error logging in to the manager: %s" % reason
       call.disposition = msg
       raise
Exemplo n.º 6
0
 def connect_to_asterisk_manager(self):
     manager = asterisk.manager.Manager()
     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     s.connect(("8.8.8.8", 80))
     local_ip = s.getsockname()[0]
     s.close()
     manager.connect(local_ip)
     manager.login('Asterisk13', 'AsteriskManager58')
     return manager
Exemplo n.º 7
0
def connect_calls(command, server):
    manager = asterisk.manager.Manager()
    try:
        manager.connect(server, port)
        manager.login(login, password)
        response = manager.command(command)
        return response.data
    except:
        return -1
Exemplo n.º 8
0
def show_channels():
    app.logger.debug('Start show_channels')
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.command('core show channels verbose').data
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 9
0
def show_channels():
    app.logger.debug('Start show_channels')
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.command('core show channels verbose').data
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 10
0
def connect(command, server):
    manager = asterisk.manager.Manager()
    try:
        manager.connect(server, port)
        manager.login(login, password)
        response = manager.command(command)
        return response.data
    except ManagerAuthException:
        return ['error 1', 101]
    except ManagerSocketException:
        return ['error 2', 102]
    except:
        return ['error 3', 103]
Exemplo n.º 11
0
def queue_status():
    app.logger.debug('Start queue_status')
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.send_action({
            'Action': 'QueueStatus',
        }).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 12
0
def queue_status():
    app.logger.debug('Start queue_status')
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.send_action({
            'Action': 'QueueStatus',
        }).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 13
0
def db_get():
    app.logger.debug('Start db_get')
    family = request.args['family']
    key = request.args['key']
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.command('database get %s %s' % (family, key)).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 14
0
def db_get():
    app.logger.debug('Start db_get')
    family = request.args['family']
    key = request.args['key']
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.command('database get %s %s' %
                                   (family, key)).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 15
0
def _get_manager(plpy, hostname):
    import asterisk.manager

    plan = plpy.prepare("SELECT * FROM asterisk.managers WHERE host = $1", [ "text" ])
    r = plpy.execute(plan, [hostname], 1)
    r = r[0]

    manager = asterisk.manager.Manager()
    manager.connect(r['host'])
    manager.login(r['login'], r['passwd'])

    manager.event_registry = []

    return manager
Exemplo n.º 16
0
def _connect_to_ami() -> asterisk.manager.Manager:
    """
    Connecting to asterisk(AMI)
    """
    while True:
        manager = asterisk.manager.Manager()
        try:
            manager.connect(settings.AS_MANAGER_IP)
            manager.login(settings.AS_MANAGER_LOGIN,
                          settings.AS_MANAGER_PASSWORD)
        except asterisk.manager.ManagerException as e:
            logger.error("connect to ami Error: %s" % e)

        if manager.connected():
            return manager
Exemplo n.º 17
0
def _connect_to_ami() -> asterisk.manager.Manager:
    """
    Connecting to asterisk(AMI)
    """
    while True:
        manager = asterisk.manager.Manager()
        try:
            manager.connect(settings.AS_MANAGER_IP)
            manager.login(settings.AS_MANAGER_LOGIN,
                          settings.AS_MANAGER_PASSWORD)
        except asterisk.manager.ManagerException as e:
            logger.error("connect to ami Error: %s" % e)

        if manager.connected():
            return manager
Exemplo n.º 18
0
def _get_manager(plpy, hostname):
    import asterisk.manager

    plan = plpy.prepare("SELECT * FROM asterisk.managers WHERE host = $1",
                        ["text"])
    r = plpy.execute(plan, [hostname], 1)
    r = r[0]

    manager = asterisk.manager.Manager()
    manager.connect(r['host'])
    manager.login(r['login'], r['passwd'])

    manager.event_registry = []

    return manager
Exemplo n.º 19
0
def setup(hass, config):
    """Your controller/hub specific code."""

    # Needs to be done here because hass needs to load the file to know that the library needs installing
    import asterisk.manager
    manager = asterisk.manager.Manager()

    host = config[DOMAIN].get(CONF_HOST, DEFAULT_HOST)
    port = config[DOMAIN].get(CONF_PORT, DEFAULT_PORT)
    username = config[DOMAIN].get(CONF_USERNAME, DEFAULT_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD, DEFAULT_PASSWORD)

    try:
        manager.connect(host, port)
        login_status = manager.login(username=username,
                                     secret=password).get_header("Response")
    except asterisk.manager.ManagerException as e:
        _LOGGER.error("Error connecting to Asterisk: %s", e.args[1])
        return False

    if "Success" not in login_status:
        _LOGGER.error("Could not authenticate: %s", login_status)

    hass.data[DATA_ASTERISK] = manager
    hass.data[DATA_MONITOR] = config[DOMAIN].get(CONF_MONITOR, [])

    load_platform(hass, 'sensor', DOMAIN)

    return True
Exemplo n.º 20
0
def queue_remove():
    app.logger.debug('Start queue_remove')
    queue = request.form['queue']
    interface = request.form['interface']
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.send_action({
            'Action': 'QueueRemove',
            'Queue': queue,
            'Interface': interface,
        }).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 21
0
def call():
    app.logger.debug('Start call')
    inline = request.form['inline']
    exten = request.form['exten']

    channel = 'SIP/%s' % inline
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        app.logger.debug('Try to connect to asterisk_address=%s and asterisk_port=%s' % (config.ASTERISK_ADDRESS, config.ASTERISK_PORT))
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        app.logger.debug('Try to login to asterisk_login=%s and asterisk_password=%s' % (config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD))
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        app.logger.debug('Try to call channel=%s and exten=%s' % (channel, exten))
        response = manager.originate(channel, exten, caller_id='call_from_CRM <CRM>', async=True).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 22
0
def queue_remove():
    app.logger.debug('Start queue_remove')
    queue = request.form['queue']
    interface = request.form['interface']
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        response = manager.send_action({
            'Action': 'QueueRemove',
            'Queue': queue,
            'Interface': interface,
        }).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 23
0
    def ami_connection_loop(self):
        while True:
            if self.stopped.is_set():
                return
            try:
                # Create PBX connection
                manager = asterisk.manager.Manager()
                logger.info(u'Connecting to {}:{} with {}:{}.'.format(
                    self.asterisk_host, self.ami_port,
                    self.ami_user,
                    self.ami_password[0] + '******' + self.ami_password[-1:]))
                #
                manager.connect(str(self.asterisk_host),
                                port=int(self.ami_port))
                manager.login(self.ami_user, self.ami_password)
                logger.info(u'Connected to AMI.')
                # Register for events
                manager.register_event('VarSet', self.on_asterisk_event)
                manager.register_event('Hangup', self.on_asterisk_event)
                manager.register_event('Cdr', self.on_asterisk_event)
                manager.register_event('Newchannel', self.on_asterisk_event)
                manager.register_event('Newstate', self.on_asterisk_event)
                manager.register_event('NewConnectedLine', self.on_asterisk_event)
                manager.register_event('OriginateResponse', self.on_asterisk_event)
                if os.getenv('DISABLE_EVENT_AGENT_CALLED') != '1':
                    manager.register_event('AgentCalled',
                                           self.on_asterisk_event)
                manager.register_event('UserEvent', self.on_asterisk_event)
                self.ami_manager = manager
                self.ami_disconnected.clear()
                self.ami_connected.set()
                self.ami_disconnected.wait()
                logger.info('AMI disconnected.')

            except asterisk.manager.ManagerSocketException as e:
                logger.error("Error connecting AMI %s:%s: %s",
                             self.asterisk_host, self.ami_port, e)
            except asterisk.manager.ManagerAuthException as e:
                logger.error("Error logging in to the manager: %s" % e)
            except asterisk.manager.ManagerException as e:
                logger.error("Error: %s" % e)
            except Exception as e:
                logger.exception('AMI error:')

            logger.info(u'Reconnecting AMI.')
            gevent.sleep(float(os.environ.get('AMI_RECONNECT_TIMEOUT', '1')))
Exemplo n.º 24
0
def before_each_dialer_request(*args, **kwargs):
    status, response, error_msg = 'success', '', ''

    try:
        if not manager.connected():
            manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)

            manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
            response = manager.send_action({
                'Action': 'Events',
                'Events': 'on',
                'EventMask': 'cdr',
            }).response
            manager.register_event('*', event_callback)
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 25
0
    def ami_connection_loop(self):
        while True:
            if self.stopped.is_set():
                return
            self.ami_manager = None
            try:
                # Create PBX connection
                manager = manager = asterisk.manager.Manager()
                logging.debug('Connecting to {}:{} with {}:{}'.format(
                    self.settings.get('AsteriskHost'),
                    self.settings.get('AmiPort'),
                    self.settings.get('AsteriskLogin'),
                    self.settings.get('AsteriskPassword'),
                ))
                manager.connect(
                    str(self.settings.get('AsteriskHost')),
                    port = int(self.settings.get('AmiPort'))
                )
                manager.login(
                    self.settings.get('AsteriskLogin'),
                    self.settings.get('AsteriskPassword')
                )
                logging.info('Managed connected.')
                manager.register_event('PeerStatus', self.handle_asterisk_event)
                manager.register_event('UserEvent', self.handle_asterisk_event)
                manager.register_event('VarSet', self.handle_asterisk_event)
                manager.register_event('Newchannel', self.handle_asterisk_event)
                manager.register_event('NewConnectedLine', self.handle_asterisk_event)
                manager.register_event('Newstate', self.handle_asterisk_event)
                manager.register_event('Hangup', self.handle_asterisk_event)
                self.ami_manager = manager
                self.ami_disconnected.clear()
                self.ami_connected.set()
                self.ami_disconnected.wait()

            except asterisk.manager.ManagerSocketException as e:
                logging.error("Error connecting to the manager: %s" % e)
            except asterisk.manager.ManagerAuthException as e:
                logging.error("Error logging in to the manager: %s" % e)
            except asterisk.manager.ManagerException as e:
                logging.error("Error: %s" % e)

            logging.info('Reconnecting AMI.')
            gevent.sleep(self.settings.get('AmiReconnectTimeout'))
Exemplo n.º 26
0
def spy():
    app.logger.debug('Start spy')
    inline = request.form['inline']
    exten = request.form['exten']
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        manager.send_action({
            'Action': 'Originate',
            'Channel': 'SIP/%s' % inline,
            'CallerID': 'Listening...',
            'Application': 'ChanSpy',
            'Data': 'SIP/%s,q' % exten
        }).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 27
0
def spy():
    app.logger.debug('Start spy')
    inline = request.form['inline']
    exten = request.form['exten']
    manager = asterisk.manager.Manager()
    status, error_msg, response = 'success', '', ''
    try:
        manager.connect(config.ASTERISK_ADDRESS, config.ASTERISK_PORT)
        manager.login(config.ASTERISK_LOGIN, config.ASTERISK_PASSWORD)
        manager.send_action({
            'Action': 'Originate',
            'Channel': 'SIP/%s' % inline,
            'CallerID': 'Listening...',
            'Application': 'ChanSpy',
            'Data': 'SIP/%s,q' % exten
        }).response
    except asterisk.manager.ManagerSocketException, (errno, reason):
        status = 'failure'
        error_msg = 'Error connecting to the manager: %s' % reason
Exemplo n.º 28
0
def plugin(srv, item):

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
                      item.service, item.target)

    host = item.config['host']
    port = item.config['port']
    username = item.config['username']
    password = item.config['password']
    extension = item.config['extension']
    context = item.config['context']

    gateway = item.addrs[0]
    number = item.addrs[1]
    title = item.title
    message = item.message

    try:
        manager = asterisk.manager.Manager()
        manager.connect(host, port)
        response = manager.login(username, password)
        srv.logging.debug("Authentication {}".format(response))
        channel = gateway + number
        channel_vars = {'text': message}
        # originate the call
        response = manager.originate(channel,
                                     extension,
                                     context=context,
                                     priority='1',
                                     caller_id=extension,
                                     variables=channel_vars)
        srv.logging.info("Call {}".format(response))
        manager.logoff()
    except asterisk.manager.ManagerSocketException as e:
        srv.logging.error("Error connecting to the manager: {}".format(e))
        return False
    except asterisk.manager.ManagerAuthException as e:
        srv.logging.error("Error logging in to the manager: {}".format(e))
        return False
    except asterisk.manager.ManagerException as e:
        srv.logging.error("Error: {}".format(e))
        return False

    # Remember to clean up
    finally:
        try:
            manager.close()
        except asterisk.manager.ManagerSocketException:  # pragma: no cover
            pass

    return True
Exemplo n.º 29
0
def plugin(srv, item):

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    host     = item.config['host']
    port = item.config['port']
    username = item.config['username']
    password = item.config['password']
    extension = item.config['extension']
    context  = item.config['context']
 
    gateway  = item.addrs[0]
    number   = item.addrs[1]    
    title    = item.title
    message  = item.message

    try:
        manager = asterisk.manager.Manager()
        manager.connect(host, port)
        response = manager.login(username, password)
        srv.logging.debug("Authentication {}".format(response))
        channel = gateway + number
        channel_vars = {'text': message}
        # originate the call
        response = manager.originate(channel, extension, context=context, priority='1', caller_id=extension, variables=channel_vars)
        srv.logging.info("Call {}".format(response))
        manager.logoff()
    except asterisk.manager.ManagerSocketException as e:
        srv.logging.error("Error connecting to the manage: {}".format(e))
    except asterisk.manager.ManagerAuthException as e:
        srv.logging.error("Error logging in to the manager: {}".format(e))
    except asterisk.manager.ManagerException as e:
        srv.logging.error("Error: {}".format(e))

    finally:
    # remember to clean up
        try:
            manager.close()
        except asterisk.manager.ManagerSocketException:
            pass
    
    return True
Exemplo n.º 30
0
    except:
        srcuniqueid = None

    print event.get_header('Event'), event.headers

    AsteriskEvent(event=event.get_header('Event'),
                  raw=str(event.headers),
                  uniqueid=uniqueid)


manager = asterisk.manager.Manager()

try:
    try:
        manager.connect(config.get('AMI', 'host'))
        manager.login(config.get('AMI', 'username'),
                      config.get('AMI', 'password'))

        manager.register_event('Shutdown', handle_shutdown)
        manager.register_event('Newstate', handle_newstate)
        manager.register_event('Hangup', handle_hangup)
        manager.register_event('Link', handle_link)
        manager.register_event('Unlink', handle_unlink)
        manager.register_event('Dial', handle_dial)
        #manager.register_event('Newstate', handle_newstate)
        #manager.register_event('*', handle_event)

        manager.message_loop()

        manager.logoff()

    except asterisk.manager.ManagerSocketException, (errno, reason):
Exemplo n.º 31
0
#!/usr/bin/python

import asterisk.agi
import asterisk.manager
import sys

agi = asterisk.agi.AGI()
src = agi.env['agi_arg_1']
dst = agi.env['agi_arg_2']

manager = asterisk.manager.Manager()
manager.connect('localhost')
manager.login('switch', 'switch')

manager.originate('Local/%s@callback-dial/n' % src,
                  exten=dst,
                  context='callback-answer',
                  priority='1',
                  async=True,
                  timeout='60000',
                  variables={})
manager.close()
Exemplo n.º 32
0
def send_sms(*args, **kwargs):
    sms_pk = kwargs.get('sms_pk')

    try:
        print('sms_pk: ', sms_pk)
        sms = SMS.objects.get(pk=sms_pk, is_send=False, )
    except SMS.DoesNotExist:
        return False

    manager = asterisk.manager.Manager()

    try:
        # connect to the manager
        try:
            manager.connect(proj.settings.ASTERISK_HOST)
            manager.login(*proj.settings.ASTERISK_AUTH)

            # get a status report
            response = manager.status()
            print('response: ', response)

            response = manager.command('core show channels concise')
            print('response.data: ', response.data)

            response = manager.command('dongle show version')
            print('response.data: ', response.data)

            response = manager.command('dongle show devices')
            print('response.data: ', response.data)

            response = manager.command('dongle ussd Vodafone1 *161#')
            print('response.data: ', response.data)

            response = manager.command('dongle show device settings')
            print('response.data: ', response.data)

            response = manager.command('dongle show device state')
            print('response.data: ', response.data)

            response = manager.command('dongle show device statistics')
            print('response.data: ', response.data)

            manager.logoff()

        except asterisk.manager.ManagerSocketException as e:
            print "Error connecting to the manager: %s" % e
        except asterisk.manager.ManagerAuthException as e:
            print "Error logging in to the manager: %s" % e
        except asterisk.manager.ManagerException as e:
            print "Error: %s" % e

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print e

    sms.task_id = None
    sms.is_send = True
    sms.send_at = timezone.now()
    sms.save(skip_super_save=True, )

    print('increase_send_sms(): ', increase_send_sms())

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
Exemplo n.º 33
0
def send_template_sms(*args, **kwargs):

    phone = kwargs.pop(
        'sms_to_phone_char',
        False,
    )
    if not phone:
        return False

    phone = phone.replace(' ', '').strip('+') \
        .replace('(', '').replace(')', '').replace('-', '') \
        .lstrip('380').lstrip('38').lstrip('80').lstrip('0')

    try:
        int_phone = int(phone[2:])
        int_code = int(phone[:2])
    except ValueError:
        return False

    template_name = kwargs.pop(
        'sms_template_name',
        False,
    )
    try:
        template = Template.objects.get(name=template_name, )
    except Template.DoesNotExist:
        return False

    template_dict = {}

    for key, value in kwargs.items():

        if key.startswith('sms_'):

            template_dict.update({key.lstrip('sms_'): value})

    message = template.template.format(**template_dict)

    sms_inst = SMS(
        template=template,
        direction=2,
        task_id=None,
        sim_id=255016140761290,
        is_send=True,
        message=message,
        to_phone_char=phone,
        to_code=int_code,
        to_phone=int_phone,
        send_at=timezone.now(),
    )

    manager = asterisk.manager.Manager()

    # connect to the manager
    try:
        manager.connect(settings.ASTERISK_HOST)
        manager.login(*settings.ASTERISK_AUTH)

        # get a status report
        response = manager.status()
        print('response: ', response)

        number = '+380{code}{phone}'\
            .format(
                code=sms_inst.to_code,
                phone=sms_inst.to_phone,
            )

        sms_to_pdu = SmsSubmit(
            number=number,
            text=sms_inst.message,
        )

        sms_to_pdu.request_status = False
        sms_to_pdu.validity = timedelta(days=2)
        sms_list = sms_to_pdu.to_pdu()

        # last_loop = len(sms_list) - 1
        for i, pdu_sms in enumerate(sms_list):
            time.sleep(0.5)
            response = manager.command(
                'dongle pdu {device} {pdu}'.format(
                    device='Vodafone1',
                    pdu=pdu_sms.pdu,
                ), )
            print('print: response.data: ', response.data)
            logger.info('logger: response.data: %s' % response.data)
            # [Vodafone1] SMS queued for send with id 0x7f98c8004420\n--END COMMAND--\r\n
            sended_sms = increase_send_sms()
            print('print: sended SMS: ', sended_sms)
            logger.info('logger: sended SMS: %s' % sended_sms)
            # if i != last_loop:
            #     time.sleep(1.5)
            time.sleep(0.5)

        manager.logoff()

    except asterisk.manager.ManagerSocketException as e:
        print("Error connecting to the manager: %s" % e, )
    except asterisk.manager.ManagerAuthException as e:
        print("Error logging in to the manager: %s" % e, )
    except asterisk.manager.ManagerException as e:
        print("Error: %s" % e, )

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print(
                'sms_ussd/tasks.py: e: ',
                e,
            )

    sms_inst.save(skip_super_save=True, )

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
	# popen = subprocess.Popen("/usr/bin/liquidsoap '%s'" % get_liquidsoap_script(phone, socketPath), shell=True, stderr=FNULL)
	#
	liquidsoapfile = config.socketPath + 'liquidsoap.liq'
	try:
		with open(liquidsoapfile, "w") as text_file:
			text_file.write(get_liquidsoap_script(phone, socketPath, currentMusicNumber))
	except Exception as e:
		logger.error("Cannot rewrite liquidsoap.liq script file, error: %s" % str(e))
	cmd = "/usr/bin/liquidsoap %s" % (liquidsoapfile)
	liquidsoap_process = subprocess.Popen(cmd.split(), stderr=FNULL)
	#atexit.register(cleanup) TODO doesn work yet
	logger.debug('New call to queue, phone: %s, callid: %s, channel: %s' % (phone, callId, channel))
	time.sleep(1) # let liquidsoap open socket
	socket_connect()
	manager.connect('127.0.0.1') 
	manager.login('admin', 'admin')
	manager.register_event('DTMF', on_dtmf)
	manager.register_event('QueueEntry', on_queueentry)
	get_queue_status_periodic()
	
except asterisk.manager.ManagerSocketException as err:
	errno, reason = err
	logger.error("Error connecting to the manager: %s" % reason)
	sys.exit(1)
except asterisk.manager.ManagerAuthException as reason:
	logger.error("Error login in to the manager: %s" % reason)
	sys.exit(1)
except asterisk.manager.ManagerException as reason:
	logger.error("Error: %s" % reason)
	sys.exit(1)
Exemplo n.º 35
0
def send_template_sms(*args, **kwargs):

    to_phone_char = kwargs.pop('sms_to_phone_char', False, )
    print('sms_to_phone_char: ', to_phone_char)
    if not to_phone_char:
        return False

    template_name = kwargs.pop('sms_template_name', False, )
    try:
        print('template_name: ', template_name)
        teplate = Template.objects.get(name=template_name, )
    except Template.DoesNotExist:
        return False

    template_dict = {}
    print '203', template_dict
    for key, value in kwargs.iteritems():
        print '205', key, value
        if key.startswith('sms_'):
            print '207', "key.lstrip('sms_')", key.lstrip('sms_')
            print '208', template_dict
            template_dict.update({key.lstrip('sms_'): value})
            print '210', template_dict

    message = teplate.template.format(**template_dict)
    print message

    manager = asterisk.manager.Manager()

    try:
        # connect to the manager
        try:
            manager.connect(proj.settings.ASTERISK_HOST)
            manager.login(*proj.settings.ASTERISK_AUTH)

            # get a status report
            response = manager.status()
            print('response: ', response)

            response = manager.command('core show channels concise')
            print('response.data: ', response.data)

            response = manager.command('dongle show version')
            print('response.data: ', response.data)

            response = manager.command('dongle show devices')
            print('response.data: ', response.data)

            response = manager.command('dongle ussd Vodafone1 *161#')
            print('response.data: ', response.data)

            response = manager.command('dongle show device settings')
            print('response.data: ', response.data)

            response = manager.command('dongle show device state')
            print('response.data: ', response.data)

            response = manager.command('dongle show device statistics')
            print('response.data: ', response.data)

            response = manager.command(u'dongle sms {device} {to_phone_char} {message}'
                                       .format(
                                            device='Vodafone2',
                                            to_phone_char=to_phone_char,
                                            message=message,
                                        ),
            )
            print('response.data: ', response.data)

            manager.logoff()

        except asterisk.manager.ManagerSocketException as e:
            print "Error connecting to the manager: %s" % e
        except asterisk.manager.ManagerAuthException as e:
            print "Error logging in to the manager: %s" % e
        except asterisk.manager.ManagerException as e:
            print "Error: %s" % e

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print e

    sms = SMS(template=teplate,
              direction=2,
              task_id=None,
              is_send=True,
              to_phone_char=to_phone_char,
              message=message,
              send_at=timezone.now(),
              )
    sms.save(skip_super_save=True, )

    print('increase_send_sms(): ', increase_send_sms())

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
Exemplo n.º 36
0
                    #Create collection for Analytics
                    set_concurrentcall_analytic(date_now, switch_id, accountcode, numbercall)

            except sqlite3.Error, e:
                logger.error('Error %s:' % e.args[0])
            finally:
                if con:
                    con.close()
        elif settings.CDR_BACKEND[settings.LOCAL_SWITCH_IP]['cdr_type'] == 'asterisk':
            manager = asterisk.manager.Manager()
            listaccount = {}
            try:
                # connect to the manager
                try:
                    manager.connect(settings.ASTERISK_MANAGER_HOST)
                    manager.login(settings.ASTERISK_MANAGER_USER, settings.ASTERISK_MANAGER_SECRET)

                    # get list of channels
                    response = manager.command('core show channels concise')
                    # response.data = "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!4267877355!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!12346!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!!!3!35!(None)!1352663344.6\n"

                    if response.data:
                        lines = response.data.split('\n')
                        for line in lines:
                            col = line.split('!')
                            if col and len(col) >= 8:
                                if col[8] in listaccount:
Exemplo n.º 37
0
stomp.connect(stomp_username, stomp_password)
stomp.subscribe(stomp_queue)

while True:
    message = stomp.get()

    channel_message = ChannelMessage()

    logging.debug(message.body)

    data = channel_message.load_data_json(message.body)

    if data['type'] == channel_message.TYPE_AGENT_STATUS:
        manager = asterisk.manager.Manager()
        manager.connect(ami_host)
        manager.login(ami_username, ami_password)

        if data['statusId'] == 'available':
            response = queue_add(manager, data)
        elif data['statusId'] == 'offline':
            response = queue_remove(manager, data)
        elif data['statusId'] == 'away':
            response = queue_pause(manager, data)

        print response.headers['Message']

        manager.logoff()

    elif data['type'] == channel_message.TYPE_PING:
	#logging.info('ping at %s from %s', (data['id'], data['agent']))
	#TODO hardcoded value
Exemplo n.º 38
0
"""
Example to get list of active channels
"""
import asterisk.manager
import sys

manager = asterisk.manager.Manager()

try:
    # connect to the manager
    try:
        manager.connect('localhost')
        manager.login('user', 'secret')

        # get a status report
        response = manager.status()
        print(response)
        
        response = manager.command('core show channels concise')
        print(response.data)

        manager.logoff()
    except asterisk.manager.ManagerSocketException as e:
        print "Error connecting to the manager: %s" % e.strerror
        sys.exit(1)
    except asterisk.manager.ManagerAuthException as e:
        print "Error logging in to the manager: %s" % e.strerror
        sys.exit(1)
    except asterisk.manager.ManagerException as e:
        print "Error: %s" % e.strerror
        sys.exit(1)
Exemplo n.º 39
0
def send_sms(*args, **kwargs):
    sms_pk = kwargs.get('sms_pk')

    try:
        sms_inst = SMS.objects.get(
            pk=sms_pk,
            is_send=False,
        )
    except SMS.DoesNotExist:
        return False

    manager = asterisk.manager.Manager()

    # connect to the manager
    try:
        manager.connect(settings.ASTERISK_HOST)
        manager.login(*settings.ASTERISK_AUTH)

        # get a status report
        response = manager.status()
        print('print: response: ', response)
        logger.info('logger: response: %s' % response)
        # Success
        number = '+380{code}{phone}'\
            .format(
                code=sms_inst.to_code,
                phone=sms_inst.to_phone,
            )

        sms_to_pdu = SmsSubmit(
            number=number,
            text=sms_inst.message,
        )

        sms_to_pdu.request_status = True
        sms_to_pdu.validity = timedelta(days=2)
        sms_list = sms_to_pdu.to_pdu()

        # last_loop = len(sms_list) - 1
        for i, pdu_sms in enumerate(sms_list):
            time.sleep(0.5)
            response = manager.command(
                'dongle pdu {device} {pdu}'.format(
                    device='Vodafone1',
                    pdu=pdu_sms.pdu,
                ), )
            print('print: response.data: ', response.data)
            logger.info('logger: response.data: %s' % response.data)
            # [Vodafone1] SMS queued for send with id 0x7f98c8004420\n--END COMMAND--\r\n
            sended_sms = increase_send_sms()
            print('print: sended SMS: ', sended_sms)
            logger.info('logger: sended SMS: %s' % sended_sms)
            # if i != last_loop:
            #     time.sleep(1.5)
            time.sleep(0.5)

        manager.logoff()

    except asterisk.manager.ManagerSocketException as e:
        print("Error connecting to the manager: %s" % e, )
    except asterisk.manager.ManagerAuthException as e:
        print("Error logging in to the manager: %s" % e, )
    except asterisk.manager.ManagerException as e:
        print("Error: %s" % e, )

    finally:
        # remember to clean up
        try:
            manager.close()
        except Exception as e:
            print('print: sms_ussd/task.py: e: ', e)
            logger.info('logger: sms_ussd/task.py: e: %s' % e)

    sms_inst.task_id = None
    sms_inst.is_send = True
    sms_inst.send_at = timezone.now()
    sms_inst.save(skip_super_save=True, )

    return True, timezone.now(), '__name__: {0}'.format(str(__name__))
Exemplo n.º 40
0
"""
Example to get list of active channels
"""
import asterisk.manager
import sys

manager = asterisk.manager.Manager()

try:
    # connect to the manager
    try:
        manager.connect('localhost')
        manager.login('user', 'secret')

        # get a status report
        response = manager.status()
        print response

        response = manager.command('core show channels concise')
        print response.data

        manager.logoff()
    except asterisk.manager.ManagerSocketException, (errno, reason):
        print "Error connecting to the manager: %s" % reason
        sys.exit(1)
    except asterisk.manager.ManagerAuthException, reason:
        print "Error logging in to the manager: %s" % reason
        sys.exit(1)
    except asterisk.manager.ManagerException, reason:
        print "Error: %s" % reason
        sys.exit(1)
Exemplo n.º 41
0
def handle_event(event, manager):
    try:
	srcuniqueid=event.get_header('Uniqueid')
    except:
	srcuniqueid=None

    print event.get_header('Event'), event.headers
    
    AsteriskEvent(event=event.get_header('Event'), raw=str(event.headers), uniqueid=uniqueid)

manager = asterisk.manager.Manager()

try:
    try:
	manager.connect(config.get('AMI', 'host')) 
        manager.login(config.get('AMI', 'username'), config.get('AMI', 'password'))

        manager.register_event('Shutdown', handle_shutdown)
        manager.register_event('Newstate', handle_newstate)
        manager.register_event('Hangup', handle_hangup)
        manager.register_event('Link', handle_link)
        manager.register_event('Unlink', handle_unlink)
        manager.register_event('Dial', handle_dial)
        #manager.register_event('Newstate', handle_newstate)
        #manager.register_event('*', handle_event)

	manager.message_loop()

        manager.logoff()

    except asterisk.manager.ManagerSocketException, (errno, reason):
Exemplo n.º 42
0
                                                    accountcode, numbercall)

                except sqlite3.Error, e:
                    logger.error('Error %s:' % e.args[0])
                finally:
                    if con:
                        con.close()
        elif settings.CDR_BACKEND[
                settings.LOCAL_SWITCH_IP]['cdr_type'] == 'asterisk':
            manager = asterisk.manager.Manager()
            listaccount = {}
            try:
                # connect to the manager
                try:
                    manager.connect(settings.ASTERISK_MANAGER_HOST)
                    manager.login(settings.ASTERISK_MANAGER_USER,
                                  settings.ASTERISK_MANAGER_SECRET)

                    # get list of channels
                    response = manager.command('core show channels concise')
                    # response.data = "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!4267877355!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!12346!!3!35!(None)!1352663344.6\n"
                    # response.data += "SIP/areski-00000006!a2billing-echotest!34902800102*!2!Ring!Echo!!34650784355!!!3!35!(None)!1352663344.6\n"

                    if response.data:
                        lines = response.data.split('\n')
                        for line in lines:
                            col = line.split('!')
                            if col and len(col) >= 8:
                                if col[8] in listaccount:
Exemplo n.º 43
0
dev = Device(mode='b')
dev.baudrate = 9600
while True:
    string = dev.read(KEY_LENGTH).strip()
    old_string = '' # Not yet used to compare string and old_string

    if string != "":
        if string in USER_DATA:
            print "Hex:", binascii.b2a_hex(string)
            dev.write('U')

            # Play ringtone/theme song
            manager = asterisk.manager.Manager()
            manager.connect('192.168.1.200')
            manager.login('steve', 'amp111')

            # manager.originate('', '')
            data = {"Action": "Originate",
                    "Channel": "SIP/180",
                    "Application": "Playback",
                    "Data": USER_DATA[string]['song']
                    }

            manager.send_action(data)
            response = manager.status()
            #print response
            manager.logoff()
            old_string = string

            time.sleep(4)
Exemplo n.º 44
0
        to_speaker = str(mc.get("to_speaker"))
        print to_speaker
    # Если никакого звонка нет
    else:
        # Если есть что удалить, то удаляем
        if len(to_speaker) > 0:
            to_speaker = ""
            mc.delete("to_speaker")


try:
    # Первоначальная инициализация
    to_speaker = ""
    manager = asterisk.manager.Manager()
    manager.connect('127.0.0.1', port=5038)
    manager.login('asterisk', '*******')

    # Если скрипт запущен в тестовом режиме из консоли с передачей параметра test
    if len(sys.argv) > 1 and str(sys.argv[1]) == "test":
        # Слушаем все события
        # manager.register_event('*', handle_event)
        # Слушаем события в Asterisk, передаём в обработку 'Newstate', 'Hangup', 'Bridge' при входящих звонках
        manager.register_event('Newstate', handle_event)
        manager.register_event('Hangup', handle_event)
        manager.register_event('BridgeEnter', handle_event)

    # Если запуск боевой (не тестовый)
    else:
        # Слушаем события в Asterisk, передаём в обработку 'Newstate', 'Hangup', 'Bridge' при входящих звонках
        manager.register_event('Newstate', handle_event)
        manager.register_event('Hangup', handle_event)
Exemplo n.º 45
0
print '=' * 80

stomp = Client(stomp_host)
stomp.connect(stomp_username, stomp_password)

stomp.agent_channel = 'jms.queue.msg.'

connection = connectionForURI(sql_dsn)
sqlhub.processConnection = connection

manager = asterisk.manager.Manager()

#try:
#try:
manager.connect(ami_host)
manager.login(ami_username, ami_password)
manager.destination = stomp

asteriskProtocolVersion = None
if manager.version == '1.0':
    asteriskProtocolVersion = Protocol.ASTERISK_1_0
elif manager.version == '1.1':
    asteriskProtocolVersion = Protocol.ASTERISK_1_1
else:
    sys.exit()

command_handler = CommandHandlerFactory(
    asteriskProtocolVersion).create_command_handler()

manager.register_event('Shutdown', command_handler.handle_Shutdown)
manager.register_event('Hangup', command_handler.handle_Hangup)
Exemplo n.º 46
0
def handle_shutdown(event, manager):
    print("Recieved shutdown event")
    manager.close()


    # we could analize the event and reconnect here
def handle_event(event, manager):
    print("Recieved event: %s" % event.name)


manager = asterisk.manager.Manager()
try:
    # connect to the manager
    try:
        manager.connect('190.117.113.7')
        manager.login('richar', '@admjds.progressive')
        # register some callbacks
        manager.register_event('Shutdown', handle_shutdown)  # shutdown
        manager.register_event('*', handle_event)  # catch all
        # get a status report
        response = manager.status()
        manager.logoff()
    except asterisk.manager.ManagerSocketException as e:
        print("Error connecting to the manager: %s" % e.strerror)
        sys.exit(1)
    except asterisk.manager.ManagerAuthException as e:
        print("Error logging in to the manager: %s" % e.strerror)
        sys.exit(1)
    except asterisk.manager.ManagerException as e:
        print("Error: %s" % e.strerror)
        sys.exit(1)