i am trying to get the email address of the current user after oauth.
I have found a solution on the web:
def get_user_info():
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json',
scopes=['openid',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'])
flow.run_local_server()
credentials = flow.credentials
# service = build('calendar', 'v3', credentials=credentials)
# Optionally, view the email address of the authenticated user.
user_info_service = build('oauth2', 'v2', credentials=credentials)
user_info = user_info_service.userinfo().get().execute()
user_email = user_info['email']
return user_email
First it was working on one machine, then i tried it on another:
First the Authentification pop up comes up and is satified:
The authentication flow has completed. You may close this window.
On the second run however i get:
Traceback (most recent call last):
File "/home/jakob/PycharmProjects/pywhatsapp2/main.py", line 313, in <module>
user_email = get_user_info()
File "/home/jakob/PycharmProjects/pywhatsapp2/main.py", line 290, in get_user_info
flow.run_local_server()
File "/home/jakob/.local/lib/python3.10/site-packages/google_auth_oauthlib/flow.py", line 499, in run_local_server
local_server = wsgiref.simple_server.make_server(
File "/usr/lib/python3.10/wsgiref/simple_server.py", line 154, in make_server
server = server_class((host, port), handler_class)
File "/usr/lib/python3.10/socketserver.py", line 452, in __init__
self.server_bind()
File "/usr/lib/python3.10/wsgiref/simple_server.py", line 50, in server_bind
HTTPServer.server_bind(self)
File "/usr/lib/python3.10/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.10/socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use
The error “Address is already in use” is thrown because the server that deals with oauth cannot be started because you already have another server currently running on that address. What it seems it happened is that in your first run you started a server and never stopped it, so when you tried to run it again, the server could not start because the address was already being used. Normally you want to always have a server running instead of always having to start one specifically for oauth in your case.
If the address is being used by another server try changing the port number.
Related
I need to write a python script which checks for incoming e-mail in a shared mailbox hosted on office 365.
I have used python exchangelib 4.7.3:
Code
#!/usr/bin/env python3
import logging
from exchangelib import Credentials, Account, Configuration, DELEGATE
def list_mails():
credentials = Credentials('user#company.com', 'SecretPassword')
config = Configuration(server='outlook.office365.com', credentials=credentials)
account = Account(primary_smtp_address='sharedmailbox#company.com', config=config, autodiscover=False, access_type=DELEGATE)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
print(item.subject, item.sender, item.datetime_received)
def main():
list_mails()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
main()
Issue
Regardless of the different tries, the following error is showing up:
DEBUG:exchangelib.protocol:No retry: no fail-fast policy
DEBUG:exchangelib.protocol:Server outlook.office365.com: Retiring session 87355
DEBUG:exchangelib.protocol:Server outlook.office365.com: Created session 82489
DEBUG:exchangelib.protocol:Server outlook.office365.com: Releasing session 82489
Traceback (most recent call last):
File "/Users/test/Code/./orderalert.py", line 24, in <module>
main()
File "/Users/test/Code/./orderalert.py", line 20, in main
list_mails()
File "/Userstest/Code/./orderalert.py", line 11, in list_mails
account = Account(primary_smtp_address='sharedmailbox#company.com', config=config, autodiscover=False, access_type=DELEGATE)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/account.py", line 204, in __init__
self.version = self.protocol.version.copy()
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/protocol.py", line 483, in version
self.config.version = Version.guess(self, api_version_hint=self._api_version_hint)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/version.py", line 233, in guess
list(ResolveNames(protocol=protocol).call(unresolved_entries=[name]))
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 187, in _elems_to_objs
for elem in elems:
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 245, in _chunked_get_elements
yield from self._get_elements(payload=payload_func(chunk, **kwargs))
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 265, in _get_elements
yield from self._response_generator(payload=payload)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 227, in _response_generator
response = self._get_response_xml(payload=payload)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 343, in _get_response_xml
r = self._get_response(payload=payload, api_version=api_version)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 297, in _get_response
r, session = post_ratelimited(
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/util.py", line 917, in post_ratelimited
protocol.retry_policy.raise_response_errors(r) # Always raises an exception
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/protocol.py", line 688, in raise_response_errors
raise UnauthorizedError(f"Invalid credentials for {response.url}")
exchangelib.errors.UnauthorizedError: Invalid credentials for https://outlook.office365.com/EWS/Exchange.asmx
DEBUG:exchangelib.protocol:Server outlook.office365.com: Closing sessions
Tried solutions (no luck with them)
The user#company.com credentials are valid, I can log myself in the web interface (no MFA or other enforced)
I have tried the auto discovery:
account = Account('sharedmailbox#company.com', credentials=credentials, autodiscover=True, access_type=DELEGATE)
Disable TLS Validation when connecting
As suggested added a "on" subdomain on on.company.com for the emails addresses.
Tested the overall setup for autodiscovery on testconnectivity.microsoft.com
On the Office 365 Azure AD admin web interface, I can see a successful login performed by the script.
I would like to use python kubernetes-client to connect to my AKS cluster api.
To do that I try to use the example give by kubernetes:
config.load_kube_config()
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
It is supposed to load my local kubeconfig and get a pods list but I get the following error:
Traceback (most recent call last): File "test.py", line 4, in
config.load_kube_config() File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/kubernetes/config/kube_config.py",
line 661, in load_kube_config
loader.load_and_set(config) File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/kubernetes/config/kube_config.py",
line 469, in load_and_set
self._load_authentication() File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/kubernetes/config/kube_config.py",
line 203, in _load_authentication
if self._load_auth_provider_token(): File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/kubernetes/config/kube_config.py",
line 221, in _load_auth_provider_token
return self._load_azure_token(provider) File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/kubernetes/config/kube_config.py",
line 233, in _load_azure_token
self._refresh_azure_token(provider['config']) File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/kubernetes/config/kube_config.py",
line 253, in _refresh_azure_token
refresh_token, client_id, '00000002-0000-0000-c000-000000000000') File
"/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/adal/authentication_context.py",
line 236, in acquire_token_with_refresh_token
return self._acquire_token(token_func) File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/adal/authentication_context.py",
line 128, in _acquire_token
return token_func(self) File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/adal/authentication_context.py",
line 234, in token_func
return token_request.get_token_with_refresh_token(refresh_token, client_secret) File
"/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/adal/token_request.py",
line 343, in get_token_with_refresh_token
return self._get_token_with_refresh_token(refresh_token, None, client_secret) File
"/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/adal/token_request.py",
line 340, in _get_token_with_refresh_token
return self._oauth_get_token(oauth_parameters) File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/adal/token_request.py",
line 112, in _oauth_get_token
return client.get_token(oauth_parameters) File "/Users//works/test-kube-api-python/env/lib/python2.7/site-packages/adal/oauth2_client.py",
line 291, in get_token
raise AdalError(return_error_string, error_response) adal.adal_error.AdalError: Get Token request returned http error: 400
and server response:
{"error":"invalid_grant","error_description":"AADSTS65001: The user or
administrator has not consented to use the application with ID
'' named 'Kubernetes AD Client
'. Send an interactive authorization request for this user and
resource.\r\nTrace ID:
\r\nCorrelation ID:
\r\nTimestamp: 2019-10-14
12:32:35Z","error_codes":[65001],"timestamp":"2019-10-14
12:32:35Z","trace_id":"","correlation_id":"","suberror":"consent_required"}
I really don't understand why it doesn't work.
When I use kubectl, all work fine.
I read some docs but I'm not sure to understand the adal error.
Thanks for your help
Login as a tenant admin to https://portal.azure.com
Open the registration for your app in the
Go to Settings then Required Permissions
Press the Grant Permissions button
If you are not a tenant admin, you cannot give admin consent
From https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi/issues/19
This is good post where you can find snippet to authenticate to AKS:
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.containerservice import ContainerServiceClient
from azure.mgmt.containerservice.models import (ManagedClusterAgentPoolProfile,
ManagedCluster)
credential = AzureCliCredential()
subscription_id = "XXXXX"
resource_group= 'MY-RG'
resouce_client=ResourceManagementClient(credential,subscription_id)
container_client=ContainerServiceClient(credential,subscription_id)
resouce_list=resouce_client.resources.list_by_resource_group(resource_group)
Note: You need to install respective Az Python SKD libraries.
Ugh, I have tried as many ways is I have been able to find online thus far, but to no avail. My primary objective is to send email from a django based web application on a private LAN. I don't care how it happens...smtp or win32com and outlook...anything, as long is it works.
Using django default settings and this code in a django shell:
from django.core.mail import send_mail
send_mail('subject','message','myemail#email.com',['myemail#email.com'])
I get this error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27_32\lib\site-packages\django\core\mail\__init__.py", line 50, in send_mail
connection=connection).send()
File "C:\Python27_32\lib\site-packages\django\core\mail\message.py", line 274, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 87, in send_messages
new_conn_created = self.open()
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 48, in open
local_hostname=DNS_NAME.get_fqdn())
File "C:\Python27_32\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27_32\lib\smtplib.py", line 311, in connect
(code, msg) = self.getreply()
File "C:\Python27_32\lib\smtplib.py", line 359, in getreply
+ str(e))
SMTPServerDisconected: Connection unexpectedly closed: [Errno 10057] A request to send or
receive data was disallowed because the socket is not connected and (when sending on a
datagram socket using a sendto call) no address was supplied
After digging into the code, I inserted a print statement in smtplib showing the address as ('localhost', 25). So I don't know why it says no address was supplied. That's when I discovered django-smtp-ssl.py and after installing added the following to my settings:
EMAIL_USE_TLS = True #also tried 1
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = 'myemail#email.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 465
Then executing the same code, I now get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27_32\lib\site-packages\django\core\mail\__init__.py", line 50, in send_mail
connection=connection).send()
File "C:\Python27_32\lib\site-packages\django\core\mail\message.py", line 274, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 87, in send_messages
new_conn_created = self.open()
File "C:\Python27_32\lib\site-packages\django_smtp_ssl.py", line 12, in open
local_hostname=DNS_NAME.getfqdn())
File "C:\Python27_32\lib\smtplib.py", line 777, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python27_32\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27_32\lib\smtplib.py", line 311, in connect
(code, msg) = self.getreply()
File "C:\Python27_32\lib\smtplib.py", line 355, in getreply
line = self.file.readline()
File "C:\Python27_32\lib\smtplib.py", line 186, in readline
chr = self.sslobj.read(1)
File "C:\Python27_32\lib\ssl.py", line 160, in read
return self._sslobj.read(len)
AttributeError: 'NoneType' object has no attribute 'read'
I have additionally tried sending mail via Outlook and win32com in a production environment using Apache. I have received a couple different exceptions trying this, such as: 'Server execution failed and 'Call was rejected by callee'. Although it works in a django shell (of course).
Has anyone seen these any of these errors and found resolution? Thank you for any help!
And it's the workaround, nothing short of shoddy, but it'll get the job done until a better solution presents itself.
First I created a custom command that can be called from manage.py as it is not executed from the Apache server (which further tells me that the system does not recognize Apache as a valid user for automatic email generation, certainly there's a way to tell the system "it's okay").
Following that, I created a task in Windows Task Scheduler to run every 30 min (which will suffice for the objective). Action:
Start a program C:\python27_32\python.exe C:\www\myproject\manage.py send_email
myapp/management/commands/send_email.py
from django.core.management.base import BaseCommand
from myapp.util.gen_email import AutoEmail #custom code to generate email via win32com
from myapp.models import MyModel
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
items = MyModel.objects.filter(status__in=['status_a','status_b'])
if items:
self.send_proc_email()
def send_proc_email(self):
subject = 'There are new items to process'
to = 'someemail#email.com'
message = ''
email = AutoEmail(subject, message, to)
def handle(self, *args, **kwargs):
pass
Far from optimal, I know, but hey if it works...
I am trying to access linkedin API using python code. Here's the code that I am running on my windows machine:
from linkedin import server
import webbrowser
API_KEY = "<API_KEY>"
API_SECRET = "<API_SECRET>"
application = server.quick_api(API_KEY, API_SECRET)
I am executing these statements one-by-one in the console, but when I execute server.quick_api(API_KEY, API_SECRET), I receive the following error:
>>> application = server.quick_api(API_KEY, API_SECRET)
https://www.linkedin.com/uas/oauth2/authorization?scope=r_basicprofile%20rw_nus%20r_network%20r_contactinfo%20w_messages%20rw_groups%20r_emailaddress%20r_fullprofile&state=0b0290ff6e51e14c5409434a6e4bf52f&redirect_uri=http%3A//localhost%3A8000/&response_type=code&client_id=<API_KEY>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2731, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-9-eb867f0fb231>", line 1, in <module>
application = server.quick_api(API_KEY, API_SECRET)
File "C:\Users\sony\AppData\Roaming\Python\Python27\site-packages\linkedin\server.py", line 24, in quick_api
_wait_for_user_to_enter_browser(app)
File "C:\Users\sony\AppData\Roaming\Python\Python27\site-packages\linkedin\server.py", line 38, in _wait_for_user_to_enter_browser
httpd = BaseHTTPServer.HTTPServer(server_address, MyHandler)
File "C:\Python27\lib\SocketServer.py", line 419, in __init__
self.server_bind()
File "C:\Python27\lib\BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python27\lib\SocketServer.py", line 430, in server_bind
self.socket.bind(self.server_address)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
I get a url which I understand I am supposed to get, but what's the cause of this error?
Also, when I paste the url in the browser, it takes me to linkedin page and asks for my credentials which it never accepts (I am sure I am entering the correct credentials). It always shows:
"HTTP Error 404. The requested resource is not found."
I am otherwise able to login to linkedin using the same credentials.
This script:
import imaplib
user = "dave.trindall#gmail.com"
pwd = "***"
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("Inbox") # here you a can choose a mail box like INBOX instead
m.search("NEW")
makes this error for me:
Traceback (most recent call last):
File "c:\Program Files\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 701, in __call__
handler.get(*groups)
File "c:\Users\Dave\git_stuff\Touch Base\Touch Base\main.py", line 30, in get
m = imaplib.IMAP4_SSL("imap.gmail.com")
File "c:\Python26\lib\imaplib.py", line 1138, in __init__
IMAP4.__init__(self, host, port)
File "c:\Python26\lib\imaplib.py", line 163, in __init__
self.open(host, port)
File "c:\Python26\lib\imaplib.py", line 1149, in open
self.sock = socket.create_connection((host, port))
AttributeError: 'module' object has no attribute 'create_connection'
Why?
This fails because App-Engine disallows opening sockets in your application. See the 'Pure Python' section in http://code.google.com/appengine/docs/python/runtime.html, also discussion at http://groups.google.com/group/google-appengine/browse_thread/thread/4a8764d266ec17af
Note that while you can't make raw socket connections from App Engine, you can send mail using the Mail API and you can read a Gmail inbox using the Gmail Inbox Feed.