Unable to change user's password via ldap3 Python3 - python-3.x

Whenever I try to change someone's password via ldap3 library I get the following error:
{'type': 'modifyResponse', 'result': 53, 'message': '0000001F: SvcErr: DSID-031A12D2, problem 5003 (WILL_NOT_PERFORM), data 0\n\x00', 'referrals': None, 'description': 'unwillingToPerform', 'dn': ''}
This error usually occurs because of the two conditions: either user is trying to modify the password through the unencrypted connection or the password is being sent with the incorrect encoding. My SSL connection is fine (at least it seems to be):
print(connection)
>>> ldaps://DC1.DOMAIN.LOCAL:636 - ssl - user: DOMAIN\admin - not lazy - bound - open - <local: 172.16.10.2:49230 - remote: 172.16.10.254:636> - tls not started - listening - SyncStrategy - internal decoder
I tried to encode the string I'm trying send to the LDAP server, but .encode('utf-16le') didn't do the trick. Any other workarounds?
I have a test domain environment with Windows Server 2012 R2 as a domain controller, and the code I'm trying to change the password with is present below.
import ssl
from ldap3 import *
tls_configuration = Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1_2)
s = Server('DC1.domain.local', get_info=ALL, use_ssl=True, tls=tls_configuration)
password = 'mypasswordhere'
c = Connection(s, user="DOMAIN\\admin", password=password)
c.open()
c.bind()
user = "CN=Dummy Dumass,OU=Automatically Generated,OU=Staff,OU=RU,DC=DOMAIN,DC=LOCAL"
c.modify(user, {
'unicodePwd': [(MODIFY_REPLACE, ['New12345'])]
})
print(c.result)
c.unbind()

ldap3 contains a specific method for changing AD password, use the following code instead of c.modify():
c.extend.microsoft.modify_password(user, new_password)

This code is working with Windows 2012 R2 AD:
pip install ldap
#!/usr/bin/python
import ldap3
SERVER='127.0.0.1'
BASEDN="DC=domain,DC=com"
USER="test-ms-ad#domain.com"
CURREENTPWD="current_password"
NEWPWD="new_password"
SEARCHFILTER='(&(|(userPrincipalName='+USER+')(samaccountname='+USER+')(mail='+USER+'))(objectClass=person))'
USER_DN=""
ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL)
conn = ldap3.Connection(ldap_server, USER, CURREENTPWD, auto_bind=True)
conn.start_tls()
print conn
conn.search(search_base = BASEDN,
search_filter = SEARCHFILTER,
search_scope = ldap3.SUBTREE,
attributes = ['cn', 'givenName'],
paged_size = 5)
for entry in conn.response:
if entry.get("dn") and entry.get("attributes"):
if entry.get("attributes").get("cn"):
USER_DN=entry.get("dn")
print USER_DN
print ldap3.extend.microsoft.modifyPassword.ad_modify_password(conn, USER_DN, NEWPWD, CURREENTPWD, controls=None)

The mentioned code is working for me, but changing password is only possible while using ssl. Change the server definition line as below:
ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL, use_ssl=True)

Related

how to send email with python after the google update?

I am using smtplib but after writing the code, been getting a bad credentials error and after changing email password and adding python to app passwords now i get a TimeoutError,
import smtplib
my_email = "ro21manrrereynolds349#gmail.com"
# password = "nqfpmxfgvrpunxku"
password = "6!OmRXMxLs8"
conn = smtplib.SMTP("smtp.gmail.com", port=465)
conn.ehlo()
conn.starttls()
conn.login(user=my_email, password=password)
conn.sendmail(
from_addr=my_email,
to_addrs="horisroman#gmail.com",
msg="Subject:Ola\n\nYou there."
)
conn.quit()
tried changing password, changing email, adding python to the app passwords, used email.mime.multipart but still got the same issues

authentication error trying to send Outlook email from Python

I'm testing out a simple script to send an Outlook email from Python 3 (using Spyder).
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = 'my_username#my_company.com'
password = 'my_password'
mail_from = username
mail_to = username
mail_subject = "Test Subject"
mail_body = "This is a test message"
mimemsg = MIMEMultipart()
mimemsg['From']=mail_from
mimemsg['To']=mail_to
mimemsg['Subject']=mail_subject
mimemsg.attach(MIMEText(mail_body, 'plain'))
try:
connection = smtplib.SMTP(host='smtp.office365.com', port=587)
connection.starttls()
connection.login(username,password)
except Exception as e:
print('Got error here')
print(e)
And the output is:
Got error here
(535, b'Authentication unsuccessful, the user credentials were incorrect. [SOME_VALUE_HERE.hostname.prod.outlook.com]')
I know for sure my own username and email are correct - I verified by checking my username's properties > SMTP value. And anyway it's the username I use to login to Windows.
I'm also using the same password for logging into Windows.
Is it possible my company uses different values for host or port? Or on the backend it sends a different user name to the SMTP server?
The error indicates that SMTP authentication is disabled. Read more about that on the page at https://aka.ms/smtp_auth_disabled. The link explains how to enable SMTP AUTH for the whole organization or only for some mailboxes.
Also take a look at the following settings that would block Legacy Authentication:

Python Web3 connect to Ankr Binance Smart Chain API, through user and password

Maybe this is a dumb question but for web3.js there is the option to use another API service Ankr, instead of Infura. Ankr gives access to BSC network which has lower fees. I cannot seem to figure out how to connect to Ankr through python web3 as it requires authentication with a username and password. It returns false when I run the python code. I am not sure which keys I am suppose to use for web3.py, or possibly the syntax for the call is wrong, when I use the requests library everything works fine so it is not an issue with the address.
# Python Code Unsuccessful
Ankr_bsc_url = 'https............'
web3 = Web3(Web3.HTTPProvider(Ankr_bsc_url, request_kwargs={'headers': {'Username': user, 'Password': password}}))
print(web3.isConnected())
//Node.js Code web3.js Works
const web3Provider = new Web3.providers.WebsocketProvider(url, {
headers: { authorization: `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`}
})
You should save the headers on a Session object, and pass it as a parameter of HTTPProvider
from web3 import Web3
import requests
s = requests.Session()
s.headers.update({'authorization': 'Basic ZZZZ'})
# HTTPProvider:
w3 = Web3(Web3.HTTPProvider('https://apis.ankr.com/XXXX/YYYY/binance/full/main', session=s))
w3.isConnected()
In my case w3.isConnected return True
I found the method below worked well when connecting to the "Basic authentication" method which required a username and password.
Alternatively, using the "Token" method did not require a username and password and that also successfully gives you an Ankr API endpoint.
from web3 import Web3
import requests
import base64
ankr_eth_url = 'INSERT_ANKR_API_ENDPOINT'
s = requests.Session()
# Make sure to use the Project Username and not your log-in username
# myProjectUsername:password
upass = "myProjectUsername:12345678".encode("ascii")
b64 = base64.b64encode(upass).decode("ascii")
s.headers.update({'Authorization': 'Basic ' + b64})
w3 = Web3(Web3.HTTPProvider(ankr_eth_url, session=s))
print(w3.isConnected())

My django smtp g-suite settings don't seem to be working

I am having issues connecting Django to google g-suite account:
The settings are currently as follows:
SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'noreply#mydomain.com'
EMAIL_HOST_PASSWORD = '16CharacterAppPassword'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
Setting I have tried: Note, comma separated the different settings I have tried in all possible combination
EMAIL_HOST = 'smtp.gmail.com', 'smtp-relay.gmail.com', 'mail.mydomain.com'
EMAIL_USE_TLS = True, False
EMAIL_USE_SSL = False, True
EMAIL_PORT = 587, 25, 465
EMAIL_HOST_USER = 'noreply#mydomain.com'
EMAIL_HOST_PASSWORD = '16CharacterAppPassword', 'mynormalpassword'
Other things I have tried:
LessSecure settings: On/Off
App Password: Tried 2 two different ones just incase the first one messed up
Contact G-Suite support: They had a look at the settings and everything is fine from their end
Tried CaptchaLink
Tried verifying last login attempt as 'it was me' so it won't block the IP
Tried the following tutorial: G-Suite Smtp
More details if it might help:
Server: Pythonanywhere
Domain: Google registered domain
Python: 3.8
Django: 3.1.1
django-allauth: 0.42.0
Error msg I get when trying to send an email:
SMTPAuthenticationError: Username and Password not accepted learn more at ...
Followed the link provided and tried all the trouble shoot methods.
EDIT:
After 48hrs it's randomly working and nothing has really changed in terms of what I have tried. I'll leave this open if someone knows what the cause might have been? Only thing I can think of is DNS Propagation but can't confirm since support mentioned that everything was fine their side.
maybe the SITE_ID is wrong try to enter to the shell and get the right SITE_ID by this command:
from django.contrib.sites.models import Site
new_site = Site.objects.create(domain='....', name='....')
print new_site.id

Connect Python to SharePoint List

I am trying to access a SharePoint List with OAuth2 security and am experiencing issues with gaining access.
Error:
Cannot get security assertion for user [user]#[company].com from federation-sts.[company].com/adfs/services/trust/2005/…
An error occurred while retrieving auth cookies from ts.[company].com/_forms/default.aspx?wa=wsignin1.0
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
url = 'https://company.sharepoint.com'
username = 'user123#company.com'
password = 'password'
listname = 'Test List'
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
sp_list = ctx.web.lists.get_by_title(listname)
items = sp_list.get_items()
ctx.load(items)
ctx.execute_query()
else:
print(ctx_auth.get_last_error())
Try #2 with SharePlum:
from shareplum import Site
from shareplum import Office365
authcookie = Office365('https://ts.company.com', username='user', password='pw').GetCookies()
site = Site('https://ts.company.com/sites/SiteName/', authcookie=authcookie)
SharePlum error (I know my credentials are correct)
Exception: ('Error authenticating against Office 365. Error from Office 365:', 'AADSTS50126: Error validating credentials due to invalid username or password.
I tried it with below code on my SPO environment, it works well:
tenant_url= "https://abc.sharepoint.com"
site_url="https://abc.sharepoint.com/sites/A"
listname = 'Test List'
ctx_auth = AuthenticationContext(tenant_url)
if ctx_auth.acquire_token_for_user("x#abc.onmicrosoft.com","xxxx"):
ctx = ClientContext(site_url, ctx_auth)
web = ctx.web
sp_list = ctx.web.lists.get_by_title('kkkk')
items = sp_list.get_items()
ctx.load(items)
ctx.execute_query()
print(items)
else:
print(ctx_auth.get_last_error())
Could you please confirm that the username/password is correct? And You can also have a try another python library for Sp connection:
SharePlum: Python + SharePoint

Resources