Python ODBC Connect to SQL Server with Service Account (trusted_connection=no) - python

I connect to my server no problem with SQL Alchemy or Pyodbc so long as I use a trusted connection:
pyodbc.connect("Driver={SQL Server};Server=myServer;Port=1433;Database=myDB;trusted_connection=yes")
sqlalchemy.create_engine('mssql://myServer/myDB?trusted_connection=yes&driver=SQL+Server')
But I need to connect with a service account with basic Windows Authentication. When I try to add the UID/PWD like so:
sqlalchemy.create_engine("mssql+pyodbc://myUserName:myPassWord#myServer?driver=SQL+Server?trusted_connection=no")
pyodbc.connect('DRIVER={SQL Server};SERVER=myServre;DATABASE=myDB;UID=myUserName;PWD=myPassword')
I get the error "Login failed for user 'myUserName'. (18456) (SQLDriverConnect); [28000] "
Bonus try:
sqlalchemy.create_engine("mssql+pyodbc://myUserName:myPassword#myDB?driver=SQL+Server?trusted_connection=no")
Returns '[Microsoft][ODBC Driver Manager] Data source name too long (0) (SQLDriverConnect)'
Using SQL Server 2018.
I've verified that the service account has all the right permissions on the DB I'm trying to connect to. FWIW, I've also tried connecting using my own Windows credentials instead of the service account's (but with trusted_connection=no) and I get the same error messages.

get the error "Login failed for user 'myUserName'. (18456) (SQLDriverConnect); [28000] "
None of the Microsoft ODBC drivers support using Windows Integrated Authentication (NTLM or Kerberos) using provided credentials. This connection string
DRIVER={SQL Server};SERVER=myServre;DATABASE=myDB;UID=myUserName;PWD=myPassword
is for SQL Auth, where you have a login and a database user created in SQL Server.
eg:
use mydb
create login myUserName with password='myPassword'
create user myUserName for login myUserName
grant select to myUserName
To use Windows Auth with this driver you have to run your program as the target user, do Windows-level impersonation, store a credential in the Windows Credential store, or use runas /netonly.

Related

Backup SQL objects using mssql-scripter

I'm making backup sql objects by mssql-scripter and it works like a charm if it comes to my local server (here I don't have to provide any user, just pointing server and db). The problem is I have to backup sql objects from client's database wchich has Azure Active Directory authentication method.
I'm providing server, database and my credentials (mail as user)
mssql-scripter -S server -d database -U user -P password -f destination --file-per-object
But I'm getting error:
Failed to connect to server 'server_name'. ---> System.Data.SqlClient.SqlException: Cannot open server "my_mail_domain" requested by the login. The login failed.
Where im mistaking? I've read info to backup sql object using mssql-scripter, authentication has to be set as 'Windows Authentication'. Is this true or I can backup providing Azure credentials?
This has been documented as an issue already.
This is only supported with a custom connection-string parameter
mssql-scripter
--connection-string "Server=server;Database=database;User Id=user;Password=password;Authentication=Active Directory Password" `
-f destination `
--file-per-object
Assuming you actually meant that you have a on-premises SQL Server, but the domain is Azure AD, then you just need to use Integrated Security ie normal Windows Authentication.
mssql-scripter
--connection-string "Server=server;Database=database;Integrated Security=true" `
-f destination `
--file-per-object
Note that usernames and passwords are not used here, the currently logged in user is used.

Python - SQL ODBC login with active directory authentication using user name & password

Is there a way to login to SQL server from Linux server using "ODBC Driver 17 for SQL Server" by passing active directory UID & PWD (not using Trusted_Connection=Yes option).
I tried with below connection parameters but getting error:
"Driver=ODBC Driver 17 for SQL Server;MultiSubnetFailover=Yes;UID=;PWD=;Server=;Database=;"
Error: Login failed
"Driver=ODBC Driver 17 for SQL Server;MultiSubnetFailover=Yes;UID=;PWD=;Server=;Database=;Authentication=ActiveDirectoryPassword";
Error: SSL Provider: SSL routines: [error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed: self signed certificate]
Is there a way to get achieve this?

Flask Sql-Alchemy, sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: PAM authentication failed for user 'abc'

I am writing a flask application, whick uses flask-sqlalchemy library to communicate with postgres server in AWS RDS.
The application works fine with just username and password. But i created a IAM user and allow him to login to postgres using the token (uses boto3's function 'generate_db_auth_token()'). using token login the get the following error.
'sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: PAM authentication failed for user "abc"'
This is the SQLALCHEMY_DATABASE_URI i am using with token,
"postgresql+psycopg2://"+get_conn()[0]['user']+":"+str(get_conn()[0]['password'])+"#"+get_conn()[0]['host']+":"+str(get_conn()[0]['port'])+"/common?sslmode=verify-ca&sslrootcert=/home/ec2-user/root.pem"
Am i doing anything wrong here.
Use this:
sqlalchemy.engine.url.URL.create(
drivername='postgresql+psycopg2',
username='postgres',
password='password',
host='localhost',
port=5432,
database='common'
)
The issue was with URL construction, use this to construct URL if you are using AWS token for authentication.
sqlalchemy.engine.url.URL('postgresql+psycopg2', username='postgres', password='password', host='localhost', port=5432, database='common')

pyodbc trusted connection not working on IIS

I'm building a Python web app on Flask that use pyodbc to read data from a SQL Server database. Only trusted connection is allowed per the database's policy.
When I tried on my local, it works perfectly well. But when I hosted it on IIS (via WFastCGI) it's not working (Internal Server Error is raised) - failed to connect on below:
pyodbc.connect(blabla,trusted_connection = yes)
Just want to know how the user can get their credential and then continue connection to the SQL.
This call has worked for me in the past (connecting to SQL Server):
conn = pyodbc.connect(''''
TRUSTED_CONNECTION=Yes;
DRIVER={SQL Server};
SERVER={myServer};
DATABASE=myDB;''')

PYODBC can't connect to SQL Express instance

I'm running an instance of SQL Server Express 2017 on my computer. I am attempting to connect to it with the following connection string:
"Driver=ODBC Driver 13 for SQL Server;Server=COMPUTERNAME\\SQLEXPRESS,1433;Database=databasename;Uid=testuser;Pwd=testpassword;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"
I have successfully connected to the server manually using those connections and SQL Server Authentication using SQL Server Management Studio.
Firewall shouldn't be an issue as it's a locally hosted server, but I've opened port 1433 for inbound and outbound connections anyway.
This connection string format has worked in the past with a database hosted on Azure (which I can no longer afford to do).
The error message:
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it.\r\n (10061) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10061)')
Any more suggestions?
I'm going to answer this question in case someone else finds it, even though it's old.
What worked pretty well for me was:
Finding out the port used by the SQL Express instance (which in my case turned out to be good 'ol 1433)
Using Network Library=DBMSSOCN to avoid issues regarding named instances (couldn't make it work that way)
How?
Doing it this way:
pyodbc.connect('driver={SQL Server Native Client 11.0};server='+DBIPAddress+';port='+DBPort+';Network Library=DBMSSOCN;database='+DBName+';uid='+DBUser+';pwd='+DBPass)
Where
DBIPAddress is the IP address of the SQL Server server
DBPort is the port
DBName is the name of the database you're trying to connect to
DBUser is the username you're using
DBPass is the password
I guess you could use {SQL Server} driver also, but I haven't tried. What we're doing is forcing a connection using the IP and port regardless of the existence of a named instance.

Categories

Resources