Git Product home page Git Product logo

pyst2's Introduction

"There's that line from Newton about standing on the shoulders of giants. We're all standing on Dennis' shoulders."

-- Brian Kernighan

wakatime

pyst2's People

Contributors

almogcohen avatar ar13pit avatar areski avatar c1cc10 avatar daleevans avatar dext0r avatar eill avatar evilscientress avatar gerrrr avatar inpos avatar jfernandz avatar ludovic-gasc avatar poing avatar randalldegges-okta-2 avatar rdegges avatar revent avatar sp1tf1r3 avatar spike77453 avatar tuxpowered avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyst2's Issues

Blocked in manager.close()

I run a repetitive program performing following steps:

  1. open a new manager connection
  2. send a command
  3. close manager connection
  4. wait few minutes and repeat from step 1

After several hours my program seems blocked. I've used manhole to get stack traces and it appears we are blocked in manager.close():

######### ProcessID=10487, ThreadID=139735744718656 #########
File: "/usr/local/src/ateis/ateis.py", line 145, in <module>
  run(monitoring)
File: "/usr/lib/python2.7/site-packages/sigtools/modifiers.py", line 156, in __call__
  return self.func(*args, **kwargs)
File: "/usr/lib/python2.7/site-packages/clize/runner.py", line 349, in run
  ret = cli(*args)
File: "/usr/lib/python2.7/site-packages/clize/runner.py", line 216, in __call__
  return func(*posargs, **kwargs)
File: "/usr/local/src/ateis/ateis.py", line 130, in monitoring
  manager.close()
File: "/usr/lib/python2.7/site-packages/asterisk/manager.py", line 483, in close
  self.logoff()
File: "/usr/lib/python2.7/site-packages/asterisk/manager.py", line 524, in logoff
  response = self.send_action(cdict)
File: "/usr/lib/python2.7/site-packages/asterisk/manager.py", line 272, in send_action
  response = self._response_queue.get()
File: "/usr/lib64/python2.7/Queue.py", line 168, in get
  self.not_empty.wait()
File: "/usr/lib64/python2.7/threading.py", line 339, in wait
  waiter.acquire()
#############################################

Catch Hangup Events

So this project is great and it all makes sense but is there any way I could get an example of how to catch hangup events? I don't quite understand how that would work. When the caller hangs up I need to do a few things before returning to the Dial Plan.

Can't reconnect to AMI

Hi, I'm trying to reconnect on a shutdown event. But when Asterisk is back and it does reconnect, it fails with a RuntimeError: threads can only be started once.

Here is my shutdown event:

def handle_shutdown(event, manager, hass, entry):
    _LOGGER.error("Asterisk shutting down.")

    manager.close()

    host = entry.data[CONF_HOST]
    port = entry.data[CONF_PORT]
    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]

    while True:
        sleep(30)
        try:
            manager.connect(host, port)
            manager.login(username, password)
            _LOGGER.info("Succesfully reconnected.")
            break
        except asterisk.manager.ManagerException as exception:
            _LOGGER.error("Error reconnecting to Asterisk: %s", exception.args[1])

Would be great to get this to work for a Asterisk integration for Home Assistant.

asteriks authenticate problem

I run this code

"""
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('muhammet', '123456')

        # 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)

finally:
    # remember to clean up
    manager.close()


Add this line

[muhammet]
secret = 123456
deny = 0.0.0.0/0.0.0.0
permit = 192.168.0.0/255.255.255.0
read = all
write = all
writetimeout = 5000

in /etc/manager.conf file but I take this error :


Traceback (most recent call last):
  File "asteriksornek.py", line 27, in <module>
    print ("Error logging in to the manager: %s" % e.strerror)
AttributeError: 'ManagerAuthException' object has no attribute 'strerror'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "asteriksornek.py", line 35, in <module>
    manager.close()
  File "/home/mert/.local/lib/python3.8/site-packages/asterisk/manager.py", line 500, in close
    self.logoff()
  File "/home/mert/.local/lib/python3.8/site-packages/asterisk/manager.py", line 541, in logoff
    response = self.send_action(cdict)
  File "/home/mert/.local/lib/python3.8/site-packages/asterisk/manager.py", line 283, in send_action
    self._sock.write(command.encode('utf8','ignore'))
  File "/usr/lib/python3.8/socket.py", line 684, in write
    self._checkClosed()
ValueError: I/O operation on closed file.

six doesn't listed in requirements

...and hence installing only pyst2 doesn't install six automatically.

I'm not sure if I should make a PR fixing this issue or you can fix it by yourself.

Please respond if I do. Thanks!

Example of register_event() and listen for events?

Hi,

I can see that the manager has a register_event() but how can I tell the manager to listen for events? For example, a listen() function that would put the manager to sleep but in any event will call the register_event() callback?

Manager.logoff(): socket closed after writing "Action: Logoff" and before calling flush()

In asterisk/manager.py, Manager class,
When sending the "Logoff" action there seems to be a race condition where the socket can get closed after writing "Action: Logoff" in the socket and before calling flush. Then when flush is called a ValueError is raised.

It does not happens all the time, I tested introducing a delay between the writing and the flush, and the greater the delay, the higher the chance of the socket to be closed.
My guess is that the connection is closed from the other side after receiving the "Logoff", and that sometimes it happens before the flush is called.

Error when running show_channels.py

I get the following error when attempting to run the example, show_channels.py.

Python 2.6.6
CentOS 6.5
Asterisk 11.14.2

python show_channels.py

Success
SIP/6606-00000018!lhs-pager-conference!s!4!Up!ConfBridge!1234,pagerbridge,pagerparticipant,!6606!!!3!133!(None)!1446585827.34
--END COMMAND--

Traceback (most recent call last):
File "show_channels.py", line 35, in
manager.close()
File "/usr/lib/python2.6/site-packages/pyst2-0.4.6-py2.6.egg/asterisk/manager.py", line 483, in close
self.logoff()
File "/usr/lib/python2.6/site-packages/pyst2-0.4.6-py2.6.egg/asterisk/manager.py", line 524, in logoff
response = self.send_action(cdict)
File "/usr/lib/python2.6/site-packages/pyst2-0.4.6-py2.6.egg/asterisk/manager.py", line 276, in send_action
raise ManagerSocketException(0, 'Connection Terminated')
asterisk.manager.ManagerSocketException: (0, 'Connection Terminated')
Exception in thread Thread-2 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
File "/usr/lib64/python2.6/threading.py", line 484, in run
File "/usr/lib/python2.6/site-packages/pyst2-0.4.6-py2.6.egg/asterisk/manager.py", line 425, in event_dispatch
File "/usr/lib64/python2.6/Queue.py", line 179, in get
File "/usr/lib64/python2.6/threading.py", line 274, in notify
<type 'exceptions.TypeError'>: 'NoneType' object is not callable

The script appears to 'Logoff' twice. Asterisk closes the TCP connection before the second logoff action is completed, so pyst2 shows the above error.
ami

Commenting out Line 22 of show_channels.py seems to fix the issue. I believe it's caused by Logoff being actioned twice.

bug in agi.py

I worked agi.py, was as follows:
def init(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
self._got_sighup = False
signal.signal(signal.SIGHUP, self._handle_sighup) # handle SIGHUP
self.stderr.write('ARGS: ')
self.stderr.write(str(sys.argv))
self.stderr.write('\n')
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.env = {}
self._get_agi_env()

Error:
Traceback (most recent call last):
File "./test.py", line 16, in
agi = AGI()
File "/usr/local/lib/python2.7/dist-packages/pyst2-0.4.8-py2.7.egg/asterisk/agi.py", line 91, in init
self.stderr.write('ARGS: ')

I did so:
def init(self,stdin=sys.stdin,stdout=sys.stdout,stderr=sys.stderr):
self.stdin=stdin
self.stdout=stdout
self.stderr=stderr
self._got_sighup = False
signal.signal(signal.SIGHUP, self._handle_sighup) # handle SIGHUP
self.stderr.write('ARGS: ')
self.stderr.write(str(sys.argv))
self.stderr.write('\n')
self.env = {}
self._get_agi_env()
It began to work.

Clarify License

In 55cc2a0 the string "UNLICENSE" was added to the licenses.

It is totally unclear to me which license this project is using. Can you clarify this? With an unclear license it is impossible to package this in Debian.

send_action - result

class MyManager(asterisk.manager.Manager):

    def queuestatus(self):
        cdict = {"Action": "QueueStatus"}
        response = self.send_action(cdict)
        return response

in response.data raw output, why not dict?
and how parse this output?
why in response.headers hasn't events?
why events not in events thread?

agi.verbose("string") bug

File "/opt/agi/unknow", line 13, in
agi.verbose("python agi started")
File "/usr/local/lib/python3.4/dist-packages/pyst2-0.4.7-py3.4.egg/asterisk/agi.py", line 606, in verbose
self.execute('VERBOSE', self._quote(message), level)
File "/usr/local/lib/python3.4/dist-packages/pyst2-0.4.7-py3.4.egg/asterisk/agi.py", line 121, in _quote
return ''.join(['"', string.encode('ascii', 'ignore'), '"'])
TypeError: sequence item 1: expected str instance, bytes found

Create new release

Since the latest release (0.5.0) is quite a few commit behind master and there were some minor bugfixes and improvements since then, I was wondering if you could create a new version and release it on pypi?

Cheers!

No data returned for SIPPeers() AMI command

When issuing the following:

    response = manager.sippeers()
    print(response)
    print(response.data)

print(response) will print "Success"

However print(response.data) does not return any of the data.

Telnetting to AMI confirms that SIPPeers is returning information for 39 different peers.

Any pointers?

a question in AMI about can't receive EventList data

EventList: start judgment conditions have problems .
You should not start with "status will follow" end with "statuscomplete"
I think a good judgment is to start with EventList: start, EventList: Complete end

your code in manager.py 336 line
` if 'status will follow' in line:
status = True
wait_for_marker = True
lines.append(line)

                # line not ending in \r\n or without ':' isn't a
                # valid header and starts multiline response
                if not line.endswith('\r\n') or ':' not in line:
                    multiline = True
                # Response: Follows indicates we should wait for end
                # marker --END COMMAND--
                if not (multiline or status) and line.startswith('Response') and \
                        line.split(':', 1)[1].strip() == 'Follows':
                    wait_for_marker = True
                # same when seeing end of multiline response
                if multiline and (line.startswith('--END COMMAND--') or line.strip().endswith('--END COMMAND--')):
                    wait_for_marker = False
                    multiline = False
                # same when seeing end of status response
                if status and 'StatusComplete' in line:
                    wait_for_marker = False
                    status = False
                if not self._connected.isSet():
                    break`

My advice
` if 'EventList: start' in line:
status = True
wait_for_marker = True
lines.append(line)

                # line not ending in \r\n or without ':' isn't a
                # valid header and starts multiline response
                if not line.endswith('\r\n') or ':' not in line:
                    multiline = True
                # Response: Follows indicates we should wait for end
                # marker --END COMMAND--
                if not (multiline or status) and line.startswith('Response') and \
                        line.split(':', 1)[1].strip() == 'Follows':
                    wait_for_marker = True
                # same when seeing end of multiline response
                if multiline and (line.startswith('--END COMMAND--') or line.strip().endswith('--END COMMAND--')):
                    wait_for_marker = False
                    multiline = False
                # same when seeing end of status response
                if status and 'EventList: Complete' in line:
                    wait_for_marker = False
                    status = False
                if not self._connected.isSet():
                    break`

Return multiple variables

I was having trouble getting two variables or running a script, I've tried both ways below:

agi.set_variable ('name', name, 'user', user)
and
agi.set_variable ('name', name, 'user', user)
agi.set_variable ('user', user)

Is it possible or would it have to be implemented?

string.encode bug

Archive: agi.py
Bug Python 3 at Line: 128
return ''.join(['"', string.encode('utf8', 'ignore'), '"'])

Correction:
return ''.join(['"', string.encode('ascii', 'ignore').decode('ascii'), '"'])

command output contains numerous "Output" headers, but only one is saved

Because there are several "Output" headers in the output of the "core show channels concise" command, it appears the response is only keeping the very last one.

I execute the following code after initiating a manager instance successfully:
response = manager.command("core show channels concise")
print(response.get_header("Output"))

The output to the print is as follows:
SIP/callcentric19-00000077!macro-dial-one!s!56!Up!Dial!SIP/10,15,HhtrIb(func-apply-sipheaders^s^1)!100!!!3!146!83324977-96e4-4ea9-98f9-19f23b472c7e!1604003497.139

Running AMI in Telnet shows the following, -> is sent lines, <- is received lines:
->action: command
->command: core show channels concise
->
<-Response: Success
<-Message: Command output follows
<-Output: SIP/10-00000078!from-internal!!1!Up!AppDial!(Outgoing Line)!10!!!3!27!83324977-96e4-4ea9-98f9-19f23b472c7e!1604003508.140
<-Output: SIP/callcentric19-00000077!macro-dial-one!s!56!Up!Dial!SIP/10,15,HhtrIb(func-apply-sipheaders^s^1)!100!!!3!38!83324977-96e4-4ea9-98f9-19f23b472c7e!1604003497.139

Notice there are two Output header lines...

Proposed solution:

  1. if there are multiple headers with the same name, perhaps they could be stored in an array. A new get_header_array() method could return the results in an array. If only one came back, get_header_array() would return an array of 1, but if multiple came back, return the array of all of them. One would use this method when expecting possibly more than one (is this the only case where that happens, when running a command? I am not sure).
    get_header() would likely still return the last one for backward compatibility.

Provide(advise) with Ami example

He first of all thank you for you hard work to keep on track the pyst2 module.
Second could you advise what appropriate method should do the job of reading all events from asterisk ami interface.

For example when I make login according your example:

            manager.connect('asterisk.sip.net')
            manager.login('test', 'test')
            resp = manager.status()

All I need just to read all events from the asterisk ami output and act accordingly.

ModuleNotFoundError: No module named 'SocketServer'

from asterisk import fastagi

Traceback (most recent call last):
File "", line 1, in
File "/home/ubuntu/.local/lib/python3.8/site-packages/asterisk/fastagi.py", line 17, in
import SocketServer
ModuleNotFoundError: No module named 'SocketServer'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.