Python2.6 xmpp Jabber Error - python

I am using xmpp with python and I want create a simple client to communicate with a gmail
id.
#!/usr/bin/python
import xmpp
login = 'Your.Login' # #gmail.com
pwd = 'YourPassword'
cnx = xmpp.Client('gmail.com')
cnx.connect( server=('talk.google.com',5223) )
cnx.auth(login,pwd, 'botty')
cnx.send( xmpp.Message( "YourFriend#gmail.com" ,"Hello World form Python" ) )
When I run the last line I get an exception
IOError: Disconnected from server.
Also when I run the other statements I get debug messages in the console.
What could be the issue and how can I resolve it ?

Here is how it did on my PyTalk client.
Don't forget the #gmail.com in the userID.
I think you should try to connect talk.google.com on the 5222 port.
Also try to specify a ressource for the auth.
import xmpp
import sys
userID = 'Your.Login#gmail.com'
password = 'YourPassword'
ressource = 'Script'
jid = xmpp.protocol.JID(userID)
jabber = xmpp.Client(jid.getDomain(), debug=[])
connection = jabber.connect(('talk.google.com',5222))
if not connection:
sys.stderr.write('Could not connect\n')
else:
sys.stderr.write('Connected with %s\n' % connection)
auth = jabber.auth(jid.getNode(), password, ressource)
if not auth:
sys.stderr.write("Could not authenticate\n")
else:
sys.stderr.write('Authenticate using %s\n' % auth)
jabber.sendInitPresence(requestRoster=1)
jabber.send(xmpp.Message( "YourFriend#gmail.com" ,"Hello World form Python" ))
By the way, it looks very close from Philip Answer

Try this code snippet. I didn't handle the error conditions for simplicity's sake.
import xmpp
login = 'Your.Login' # #gmail.com
pwd = 'YourPassword'
jid = xmpp.protocol.JID(login)
cl = xmpp.Client(jid.getDomain(), debug=[])
if cl.connect(('talk.google.com',5223)):
print "Connected"
else:
print "Connectioned failed"
if cl.auth(jid.getNode(), pwd):
cl.sendInitPresence()
cl.send(xmpp.Message( "YourFriend#gmail.com" ,"Hello World form Python" ))
else:
print "Authentication failed"
To switch off the debugging messages, pass debug=[] for the 2nd parameter on the Client class's constructor:
cl = xmpp.Client(jid.getDomain(), debug=[])

i think you must write this. i test it in python 2.7 with xmpppy 0.5.0rc1 and work IT very nice :P :) :
import xmpp
login = 'your mail#gmail.com' # #gmail.com
pwd = 'your pass'
text='Hello worlD!'
tojid='your friend #gmail.com'
jid = xmpp.protocol.JID(login)
cl = xmpp.Client(jid.getDomain(), debug=[])
if cl.connect(('talk.google.com',5223)):
print "Connected"
else:
print "Connectioned failed"
if cl.auth(jid.getNode(), pwd):
cl.sendInitPresence()
cl.send(xmpp.protocol.Message(tojid,text))
else:
print "Authentication failed"

I think you need to call sendInitPresence before sending the first message:
...
cnx.auth(login,pwd, 'botty')
cnx.sendInitPresence()
cnx.send( xmpp.Message( "YourFriend#gmail.com" ,"Hello World form Python" ) )

Related

pysmb listpath method return error "SMB connection not authenticated"

I'm using pysmb to connect a server (192.168.1.54) the code are:
host = '192.168.1.54' # server IP
username = 'Test'
password = 'test'
my_name = "localmac"
remote_name = "servermac"
try:
conn = SMBConnection(username, password, my_name, remote_name, is_direct_tcp=True)
except Exception as e:
print (e)
return
try:
conn.connect(host,445) #
except Exception as e:
print (e)
return
bytedata = 'hello'.encode()
print(conn.echo(bytedata, timeout=10))
print(conn.is_using_smb2)
for i in conn.listPath('misc', ''):
print(i.filename, i.create_time)
the two 'print' codes run smoothly and the listPath function returned the error "SMB connection not authenticated". Why? if not authenticated, why the echo sentence didn't return error?
Any comments or helps are appreciated!
1) If you are sure that the username and password correct, check the version of pysmb.
I had similar problem with pysmb==1.2.6, so if you're using this version too, update to 1.2.8.
The problem was with pysmb's own implementation of MD4 algorithm.
When there is no MD4 in Python's hashlib pysmb uses its own algorithm:
try:
import hashlib
hashlib.new('md4')
def MD4(): return hashlib.new('md4')
except ( ImportError, ValueError ):
from .utils.md4 import MD4
So if it possible update to pysmb==1.2.8 where this problem was fixed.
2) if not authenticated, why the echo sentence didn't return error?
The echo command does not require authentication, it just sends data to the remote server and remote server replies with the same data.

Python LDAP authentication to a Security Group in Active Directory

the authentication to Active directory using python-ldap works well with the code below, now trying to find how can I verify
if a user belongs to a Security Group to be successfully authentificate but cannot figure out how to do that.
I have this code integrated in a flask website.
Here is my code:
import ldap
def authenticate():
conn = ldap.initialize('ldap://ldap.example.com')
conn.protocol_version = 3
conn.set_option(ldap.OPT_REFERRALS, 0)
try:
username = 'user_id'
password = 'motdepasse'
user = "%s#domain" %username
result = conn.simple_bind_s('user', 'password')
except ldap.INVALID_CREDENTIALS:
print "Invalid credentials"
return "Invalid credentials"
except ldap.SERVER_DOWN:
print "Server down"
return "Server down"
except ldap.LDAPError, e:
if type(e.message) == dict and e.message.has_key('desc'):
return "Other LDAP error: " + e.message['desc']
else:
print "Other LDAP error: "
return "Other LDAP error: " + e
finally:
conn.unbind_s()
print "Succesfully"
return "Succesfully authenticated"
authenticate()
Thanks for your help
To restrict the LDAP authentication to a specific AD group I used the "search_s function" which find if the authenticated user is part of a AD group.
conn.search_s("OU={AD Security Group},OU=group,OU=Groups,dc=twpn,dc=root,dc=domain,dc=com", ldap.SCOPE_SUBTREE, "(cn=userid)")

Error Authenticating Spotify - Bad Request

I'm having a hard time trying to authenticate my spotify app on localhost. I have my redirect_uri set as localhost:8888/callback (have also tried it with http://) at my developer account, but I get this error page when terminal prompts me to enter the URL I'm being redirected to.
I am running my server using python -m SimpleHTTPServer 8888, and entering at terminal python script.py username.
This is my Python script:
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print "Usage: %s username" % (sys.argv[0],)
sys.exit()
token = util.prompt_for_user_token(username, scope, client_id='myId', client_secret='mySecret', redirect_uri='localhost:8888/callback')
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print track['name'] + ' - ' + track['artists'][0]['name']
else:
print "Can't get token for", username
This is the log:
token_info = sp_oauth.get_access_token(code)
File "/Library/Python/2.7/site-packages/spotipy/oauth2.py", line 210, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
What could be wrong?
have you tried it without the port number?
So replacing
localhost:8888/callback
with this:
localhost:/callback

pyramid_mailer not sending emails?

New to Pyramid here, and trying to set up pyramid_mailer to send an email to myself:
I have in development.ini:
mail.host = smtp.gmail.com
mail.username = EMAIL#gmail.com
mail.password = PASSWORD
mail.port = 587
mail.ssl = True
[handlers]
keys = console
in my project/__init__.py:
config.include('pyramid_mailer')
in my project/views.py
from pyramid_mailer.mailer import Mailer
from pyramid_mailer import get_mailer
from pyramid_mailer.message import Message
#view_config(renderer="templates/site_view.pt")
def site_view(self):
...
config.registry['mailer'] = Mailer.from_settings(settings)
mailer = request.registry['mailer']
message = Message(subject="It works!",
sender="EMAIL#gmail.cm",
recipients=["EMAIL#gmail.com"],
body="Hey there!")
mailer.send(message)
Am I missing something very fundamental here?
In fact you are missing something fundamental! :-)
.send() is a lazy-send which adds the message to the transaction manager. If you are not using pyramid_tm then the mail will not be sent at the end of the request. The transactional emailing is nice because if an exception is raised in your code after calling send(), the mail will not be sent.
Anyway, the way to make your code send is via .send_immediately().
You might want to check that and use:
mail.tls = True
Can't send emails with pyramid_mailer and gmail
also you can use .send_immediately(message, fail_silently=False)
You'd have something like that:
mail.host = smtp.gmail.com
mail.username = EMAIL#gmail.com
mail.password = PASSWORD
mail.port = 587
mail.tls = True
In your setup:
config.include('pyramid_mailer')
And then
mailer = get_mailer(request)
message = Message(subject="It works!",
sender="EMAIL#gmail.cm",
recipients=["EMAIL#gmail.com"],
body="Hey there!")
mailer.send_immediately(message, fail_silently=False)
If nothing still work, you can enable debugging using
mail.debug = True
It should dump in stdout the smtp session. If something didn't work. You'll know exactly why. If everything is fine.

Error 252 : b"2.1.5 Send some mail, I'll try my best f18sm1267047wiv.14"

Hi I've written a Python script to send a simple message. The script works with my university email address. However, with gmail there seems to be a problem. I've tried using both my email and just login as a login name - same result. The error I get is:
Error 252 : b"2.1.5 Send some mail, I'll try my best f18sm1267047wiv.14"
I'm not sure what I'm doing wrong. I really couldn't find much info. All I get is the above line, nothing else. I'm running the script on a Linux machine and it was written on a linux machine.
#! /usr/bin/python3.1
def sendmail(recepient, msg):
import smtplib
# Parameters
sender = 'login#gmail.com'
password = 'password'
smtpStr = 'smtp.gmail.com'
smtpPort = 587
# /Parameters
smtp_serv = smtplib.SMTP(smtpStr, smtpPort)
smtp_serv.ehlo_or_helo_if_needed()
smtp_serv.starttls()
smtp_serv.ehlo()
recepientExists = smtp_serv.verify(recepient)
if recepientExists[0] == 250:
smtp_serv.login(sender, password)
try:
smtp_serv.sendmail(sender, recepient, msg)
except smtplib.SMTPException:
print(recepientExists[1])
else:
print('Error', recepientExists[0], ':', recepientExists[1])
smtp_serv.quit()
sendmail('receiver#gmail.com', 'hi')
It's pretty straightforward. Nobody supports VRFY because it's such an aid to spam. Pull out that check and it should work OK.

Categories