0

I would like to access a SQL server from windows 10 using python and pyodbc, not with the account i currently am logged in windows but with a different windows account

runan different user cannot work because the user that have access to the DB has not access to python directory nad i can include him in the users of my PC

Is it possible?

  • Runas? Execute as login = 'python_account'? – sepupic Nov 26 '19 at 14:34
  • Does this answer your question? [Error 28000: Login failed for user DOMAIN\\user with pyodbc](https://stackoverflow.com/questions/37692780/error-28000-login-failed-for-user-domain-user-with-pyodbc) – Gord Thompson Nov 26 '19 at 15:15
  • 1
    The windows user that can access the DB is not user in the PC running Python so when i runas the other windows user i got a error that the user don't have access to the directory of Python. Also i cannot add the other windows user to PC users. Tricky situation... Do you know any other way to connect with Python the way i want? Thank you in advance – michael katsilieris Nov 27 '19 at 10:38
  • Your other option is to use FreeTDS ODBC instead of Microsoft's ODBC driver. – Gord Thompson Nov 27 '19 at 15:14
  • 1
    Thank you for your response! Unfortunately the DB server does not support this way to connect! the only way is to request access with the windows account i have logged in my pc – michael katsilieris Jan 09 '20 at 12:58
  • Did you ever find a solution to this, @michaelkatsilieris? – Tim Griffith Mar 31 '22 at 14:32

1 Answers1

0

So, I ended up solving this not using pyodbc but using pymssql instead. I'm not sure if that help OP though. Just figured I'd share.

import dotenv, os, pymssql, win32security, win32con
from modules.utility import write_to_json
dotenv.load_dotenv()

def impersonate_user(username, password, domain):
    """Impersonate the security context of another user."""
    handler = win32security.LogonUser(
        username, domain, password,
        win32con.LOGON32_LOGON_INTERACTIVE,
        win32con.LOGON32_PROVIDER_DEFAULT)
    win32security.ImpersonateLoggedOnUser(handler)
    write_to_json(get_records_from_database(), 'JSON_FILE_NAME')
    handler.Close()

def terminate_impersonation():
    """Terminate the impersonation of another user."""
    win32security.RevertToSelf()

def connect_pymssql():
    con = pymssql.connect(
        server=os.getenv('DB_SERVER'),
        database=os.getenv('DB_NAME'),
        port=os.getenv('DB_PORT')
    )
    cur = con.cursor()
    return con, cur

def get_records_from_database():
    con, cur = connect_pymssql()
    cur.execute(f"select * from [TABLE];")
    result = cur.fetchall()
    con.close()
    return [list(x) for x in result] if result else None
Tim Griffith
  • 170
  • 1
  • 11