Sql-server – Python code in T-SQL environment gives “access a socket in a way forbidden by its access permissions” Error

pythonsql serversql-server-2017t-sql

Help on the following please.

I have this code Python Code

  import requests
  r = requests.get("https://www.google.com")
  r.status_code
  print(r.status_code)
  print("Python Rawks!!!!!!")

which runs fine in command line mode and returns the 200 status code.

The same code in T-SQL query window fails with OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

execute sp_execute_external_script@language = N'Python',@script = N'
          import requests
          r = requests.get("https://www.google.com")
          r.status_code
          print(r.status_code)
          print("Python Rawks!!!!!!")
'

Error in execution. Check the output for more information.
Traceback (most recent call last):
File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\requests\packages\urllib3\connection.py", line 141, in _new_conn (self.host, self.port), self.timeout, **extra_kw)
File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\requests\packages\urllib3\util\connection.py", line 83, in create_connection raise err
File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\requests\packages\urllib3\util\connection.py", line 73, in create_connection sock.connect(sa)

OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
During handling of the above exception, another exception occurred:

Best Answer

Open the Windows Firewall and look for a rule called "Block network access for R local user accounts in SQL Server instance MSSQLSERVER" (assuming you have a default instance). This Firewall rule blocks network access from SQL Server external scripts. You can disable the rule if you want to allow network access.