Reputation: 2296
I'm trying to get the status of an Asterisk Server using a python socket but nothing happens.
Here is my code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.1.105'
PORT = 5038
s.connect((HOST, PORT))
params = """Action: login
Events: off
Username: admin
Secret: mypass
Action: status
Action: Logoff
"""
s.send(params)
data = s.recv(1024)
print data + '\n'
s.close()
I just get a message saying Asterisk Version and nothing more.
I hope somebody could help me with this.
Thanks in advance.
Upvotes: 3
Views: 4985
Reputation: 8604
Handling of even such simple TCP based protocol may become tricky.
Problems in this case:
Try something like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.1.105'
PORT = 5038
s.connect((HOST, PORT))
params = ["Action: login",
"Events: off",
"Username: admin",
"Secret: mypass"]
s.send("\r\n".join(params) + "\r\n")
# receive login response
data = ""
while "\r\n" not in data:
data += s.recv(1024)
s.send("Action: status\r\n\r\n")
# receive action response
data = ""
while "\r\n" not in data:
data += s.recv(1024)
print repr(data)
s.send("Action: Logoff\r\n\r\n")
s.close()
Upvotes: 1
Reputation: 33824
You have malformed your code there. The Asterisk AMI requires \r\n termination between commands.
You need to send each command in a separate packet:
params = """Action: login
Events: off
Username: admin
Secret: mypass"""
s.send(params + '\r\n')
data = s.recv(1024)
print data + '\n'
params = 'Action: status'
s.send(params + '\r\n')
data = s.recv(1024)
print data + '\n'
params = 'Action: Logoff'
s.send(params + '\r\n')
data = s.recv(1024)
print data + '\n'
That should do the trick. Obviously you'll want to also make a function for it or whatever, but that will make it work.
Always separate AMI commands out!
Upvotes: 2