Created
January 31, 2023 03:19
-
-
Save mattgillard/a0537584223208775d99240a46b0dc8c to your computer and use it in GitHub Desktop.
Python ODBC code to test AWS RDS Proxy IAM authentication with SQL Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
import pyodbc | |
import boto3 | |
# IMPORTANT: Install Microsoft ODBC drivers first for your platform - see: https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/install-microsoft-odbc-driver-sql-server-macos?view=sql-server-ver16 | |
# Just an install is enough for pyodbc to see them. | |
# Also, on M1 mac need to use 4.0.34 release of pyodbc | |
# pip3.11 install pyodbc==4.0.34 | |
# v4.0.35 is broken | |
server = "mssql.proxy-cffntbampvu0.ap-southeast-2.rds.amazonaws.com" | |
port = 1433 | |
username = "admin" | |
client = boto3.client('rds',region_name="ap-southeast-2") | |
iam_rds_token = client.generate_db_auth_token(server,port,username) | |
print(iam_rds_token) | |
# https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Linux | |
iam_rds_token_encoded = iam_rds_token.encode('utf-16-le') | |
token_struct = struct.pack(f'<I{len(iam_rds_token_encoded)}s', len(iam_rds_token_encoded), iam_rds_token_encoded) | |
SQL_COPT_SS_ACCESS_TOKEN = 1256 # This connection option is defined by microsoft in msodbcsql.h | |
connection_string=f"DRIVER={{ODBC Driver 18 for SQL Server}};SERVER={server};ENCRYPT=yes;" | |
cnxn = pyodbc.connect(connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct}) | |
cursor = cnxn.cursor() | |
cursor.execute("SELECT @@version;") | |
row = cursor.fetchone() | |
while row: | |
print(row[0]) | |
row = cursor.fetchone() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment