Seems like these Python ctypes posts are really turning into a nice little series. Today I’m following up on my previous posts (covering IcmpSendEcho and InternetConnectedState) with a little bit about using Windows functions to access websites.
Normally you could go about using one of a thousand methods built into Python for this, but there’s good reason to use the built-in Windows functions as you’ll see in a minute.
When using Python (or any other scripting language I’d hazard a guess) to access a given URL, you’re bypassing the way that Windows handles the any proxy server and credentials associated with it. If you’re sitting on a system with direct internet access this isn’t much of an issue. However if you’re end goal is to run this code, or have this code execute, on an enterprise workstation, chances are you’ll need to consider proxies and authentication.
By using Windows functions to perform the access for you, you bypass these issues by tapping into Microsoft’s Security Support Provider Interface (SSPI). The Windows function that we’re interested here is WinInet.
Using Secure WinInet
Win32 Internet APIs, also known as WinInet, is another way of building secure distributed applications without having to deal with SSPI directly.
So by using functions within WinInet we can use SSPI to piggyback on whatever authentication tokens are present and in use on the system without needing to worry about it. Even a simple script to take advantage of this ends up in a few hundred lines (although I’m sure a good coder could write it in half that). Below is some example code to help those searching for a blogpost discussing the topic more than anything else.
hInternet = wininet.InternetOpenA(
hConnect = wininet.InternetConnectA(
I can’t really give a full example in this blogpost, so I’ve written up a simple URL downloader with the ability to either save or display the results to screen. It support HTTP and HTTPS (no FTP support as yet).
Again I’ve also converted this into a .exe using PyInstaller for those looking for something a bit more portable.
- Python sourcecode –> HERE
- simpleurl.exe –> HERE
Feel free to leave any comments if you have ideas, uses, or generally want to laugh at by bad coding 😉
- Microsoft’s SSPI
- WinInet Reference – MSDN