Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions #86

Closed
doverradio opened this issue Feb 28, 2019 · 13 comments · Fixed by #115
Assignees

Comments

@doverradio
Copy link

Expected Behavior

Trying to run quickstart on python 3.6

Actual Behavior

Got error:

C:\Users\Uber-Admin\Desktop\Google Drive!GIF PROJECT\Python\Python 3.x\Requests

python quickstart.py
Traceback (most recent call last):
File "quickstart.py", line 49, in
main()
File "quickstart.py", line 30, in main
creds = flow.run_local_server()
File "C:\ProgramData\Anaconda3\lib\site-packages\google_auth_oauthlib\flow.py"
, line 407, in run_local_server
host, port, wsgi_app, handler_class=_WSGIRequestHandler)
File "C:\ProgramData\Anaconda3\lib\wsgiref\simple_server.py", line 153, in mak
e_server
server = server_class((host, port), handler_class)
File "C:\ProgramData\Anaconda3\lib\socketserver.py", line 453, in init
self.server_bind()
File "C:\ProgramData\Anaconda3\lib\wsgiref\simple_server.py", line 50, in serv
er_bind
HTTPServer.server_bind(self)
File "C:\ProgramData\Anaconda3\lib\http\server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\ProgramData\Anaconda3\lib\socketserver.py", line 467, in server_bind
self.socket.bind(self.server_address)
OSError: [WinError 10013] An attempt was made to access a socket in a way forbid
den by its access permissions

Steps to Reproduce the Problem

  1. Ran quickstart.py from https://developers.google.com/gmail/api/quickstart/python
  2. Got error:
    C:\Users\Uber-Admin\Desktop\Google Drive!GIF PROJECT\Python\Python 3.x\Requests

python quickstart.py
Traceback (most recent call last):
File "quickstart.py", line 49, in
main()
File "quickstart.py", line 30, in main
creds = flow.run_local_server()
File "C:\ProgramData\Anaconda3\lib\site-packages\google_auth_oauthlib\flow.py"
, line 407, in run_local_server
host, port, wsgi_app, handler_class=_WSGIRequestHandler)
File "C:\ProgramData\Anaconda3\lib\wsgiref\simple_server.py", line 153, in mak
e_server
server = server_class((host, port), handler_class)
File "C:\ProgramData\Anaconda3\lib\socketserver.py", line 453, in init
self.server_bind()
File "C:\ProgramData\Anaconda3\lib\wsgiref\simple_server.py", line 50, in serv
er_bind
HTTPServer.server_bind(self)
File "C:\ProgramData\Anaconda3\lib\http\server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\ProgramData\Anaconda3\lib\socketserver.py", line 467, in server_bind
self.socket.bind(self.server_address)
OSError: [WinError 10013] An attempt was made to access a socket in a way forbid
den by its access permissions

Specifications

  • Python version (python --version) Python 3.6.3 :: Anaconda custom (64-bit)
  • OS (Mac/Linux/Windows)
    My OS is Windows 7 64-bit Pro
@Crowbrammer
Copy link

Crowbrammer commented Mar 7, 2019

I solved this by updating the run_local_server function in the flow.py module of the google_auth_oauthlib package. I changed the port from 8080 to 8090. There should be some conditional logic to see if 8080 is open so that new users of the Google API, like me, don't get frustrated so early on and give up.

I learned a lot about sockets (a socket is literally an IP address and a port number paired together), netstat, and working with the UAC from Python trying to figure this out though.

@doverradio
Copy link
Author

Is this NOT supposed to be run in Python 3? Does it need to be on Python 2.7?

@doverradio
Copy link
Author

doverradio commented Mar 8, 2019

In 'flow.py', I found this piece of code:

def Run(flow, launch_browser=True, http=None,
auth_host_name='localhost', auth_host_port_start=8085):

Screenshot of that code in flow.py:
port 8090

I am assuming you meant to change this port number to 8090, right?

Unfortunately, same result that it gives me the same error:

C:\Users\Uber\Google Drive!GIF PROJECT!NC\Calendar>python quickstart.py
Traceback (most recent call last):
File "quickstart.py", line 52, in
main()
File "quickstart.py", line 30, in main
creds = flow.run_local_server()
File "C:\ProgramData\Anaconda3\lib\site-packages\google_auth_oauthlib\flow.py"
, line 407, in run_local_server
host, port, wsgi_app, handler_class=_WSGIRequestHandler)
File "C:\ProgramData\Anaconda3\lib\wsgiref\simple_server.py", line 153, in mak
e_server
server = server_class((host, port), handler_class)
File "C:\ProgramData\Anaconda3\lib\socketserver.py", line 453, in init
self.server_bind()
File "C:\ProgramData\Anaconda3\lib\wsgiref\simple_server.py", line 50, in serv
er_bind
HTTPServer.server_bind(self)
File "C:\ProgramData\Anaconda3\lib\http\server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\ProgramData\Anaconda3\lib\socketserver.py", line 467, in server_bind
self.socket.bind(self.server_address)
OSError: [WinError 10013] An attempt was made to access a socket in a way forbid
den by its access permissions

@Crowbrammer
Copy link

Crowbrammer commented Mar 9, 2019

I got it to work in Python 3.6.

@doverradio Might have you try something you're not used to. We're going to see if port 8085 is in use or not using a command in your terminal called netstat. If it's not in use, there's probably some UAC or firewall issue going on.

So, your terminal has a command called netstat. NETSTAT displays all TCP and UPD connections (sockets) that are currently active. We'll confirm that port 8085, the one you've used, is not in use.

To see all the sockets (each of which are displayed as "IP-address:port") that are in use, type into your terminal "netstat -a". This will show all the sockets in use. Of all these, to directly see if 8085 is in use, type:

  • 'netstat -na | grep "8085"' in Bash or
  • 'netstat -na | find "8085"' in cmd or
  • 'netstat -na | find """8085"""' in Powershell.

Let us know if 8085 is in there. If it is, change your port to something not in use. If it isn't there, let us know, so we can see how else this error might occur.

@doverradio
Copy link
Author

@Crowbrammer I did netstat -na | find "8085" (I'm on Windows 7 64-Bit) but got no value returned.

I'm doing this from an @gmail.com account. Could part of this complication be due to free @gmail.com and not paid Gsuite account? I do have a paid Gsuite so I could just retry with that account. Can you confirm this can be done all within a @gmail.com account (free one)?

@doverradio
Copy link
Author

doverradio commented Mar 9, 2019

Not sure what is different but I retried everything on a new PC and it worked as expected from using this script below and having to re-run

Script:

from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])

if __name__ == '__main__':
    main()

Error:
ModuleNotFoundError: No module named 'google_auth_oauthlib'

Solution:
pip install google-auth-oauthlib

After doing these things, I ran 'python quickstart.py' and got Chrome window asking me to authorize. So, it appears working. Thank you!

Please let me know the type of account (free @gmail.com or paid) and within that, whether it must be a Service account or non-Service account which may be used (or both, I don't know).

@Crowbrammer
Copy link

@doverradio I used a free Gmail account. I did not use a Service account. I'll get back to you if I learn anything new about this.

@Elijha
Copy link

Elijha commented Apr 16, 2019

I have tried on three win 10 machines after installing the current version of python 3.7.3 to follow this example and get the same error.
As some one new to python and Google sheets can a commentor above advise where the flow.py module is kept?

I'll note netstat -na | find "8085" gives no result in an elevated cmd prompt.
Not AV or Firewalls are active. I stopped all IIS servcies.

@erickoledadevrel erickoledadevrel self-assigned this Apr 16, 2019
@erickoledadevrel
Copy link

Some searching indicates that Windows may require you to run the program as an administrator. Can you try that and see if it alleviates the issue?

Another workaround would be to replace the call to run_local_server with run_console:

https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console

This flow doesn't spin up a local server, and therefore doesn't require you to open any ports.

@Elijha
Copy link

Elijha commented Apr 17, 2019

The script was run via a command prompt launched as Adminstrator at all times.

Looking at the full error I found the flow.py file under the google_auth_olib folder in the local python install (Lib\site-packages folder).

From here I search for "localhost" to find the line with the port in it and change the 8080 to 8088 and reran the script - working!.

This flow doesn't spin up a local server
the error message, the notes in this file and the working solution seem to indicate otherwise.

The server strategy instructs the user to open the authorization URL in
their browser and will attempt to automatically open the URL for them.
It will start a local web server to listen for the authorization
response. Once authorization is complete the authorization server will
redirect the user's browser to the local web server. The web server
will get the authorization code from the response and shutdown. The
code is then exchanged for a token

I'm guessing this will be undone if / when updates are made to the Google Oauth library files though .. would be good to be able to define or set this in the 'example' file?

@erickoledadevrel
Copy link

What I meant was that the run_console method doesn't spin up a local server. Some folks on this thread reported a port conflict, which seemed to be the issue in your case as well. However I was worried there was some other problem, since @doverradio seemed to have checked the ports and they were open.

@mskesselring
Copy link

I got this to work by calling creds=flow.run_local_server(port=8090) instead of creds=flow.run_local_server(). I guess the default port 8080 wasn't available and providing a different one fixed the issue.

erickoledadevrel pushed a commit that referenced this issue Jul 18, 2019
* Update oauthlib, set port to 0 in oauth flow to use ephemeral ports. Fixes #86.

* Update oauthlib version for gmail quickstart, missed in previous commit
@vervolk
Copy link

vervolk commented Apr 20, 2022

net stop hns; net start hns

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants