How can I get around Name too long for LOGINREC in pymssql without changing the username - python-2.7

I am attempting to use pymssql to connect to a client's database, but have thus far been unable to succeed. I believe that the root of the problem is this entry in the stack trace of my TDSDUMP:
dblib.c:761:dbsetlname(0x1ac3e10, <username>#<servername>.database.windows.net, 2)
dblib.c:7929:dbperror((nil), 20042, 0)
dblib.c:7981:20042: "Name too long for LOGINREC field"
One problem is that <servername>.database.windows.net already exceeds the string limit (which seems to be 30 according to this: How to use PHP's dblib PDO driver with long usernames? / SQLSTATE[HY000] Name too long for LOGINREC field (severity 2)).
I have also attempted to exclude the #<servername>.database.windows.net portion in the username entry only to receive the following error:
msgno 40532: "Cannot open server "1433D" requested by the login. The login failed."
According to https://github.com/pymssql/pymssql/issues/330 the #<servername> portion is requested by the server.
So at this point, I attempted to do the following:
user = username + "#{}".format(server)
user = user[:30]
And I received the following information (which was a slight improvement but still not ideal, given that I could still not establish the connection):
"Cannot open server "<server_name minus the last 6 characters>" requested by the login. The login failed."
If possible, I would prefer passing some parameter to pymssql's connect method that would override this character limit or do something to append the server to the username on the backend after calling dbsetlname on just <username> without the #<servername> portion. Does anyone have any recommendations (again the preference is to not ask the client to change our username, but we may have to resort to that or trying to use pyodbc if there's no other option).
These are a few of the connection methods I have tried:
conn = pymssql.connect(
host=host,
database=database,
user=username,
password=password,
port=int(port) # this is 1433
)
conn = pymssql.connect(
host=host,
database=database,
user=username + '#{}'.format(servername),
password=password,
port=int(port) # this is 1433
)
conn = pymssql.connect(
server=<servername>.database.windows.net,
database=database,
user=username,
password=password,
port=int(port) # this is 1433
)
Thanks in advance for any help/advice that you may be able to offer!

You can probably use an alternate connecting string method.
If you're using SQL Server Auth, try this:
conn = pymssql.connect(
server="<servername>.database.windows.net",
port=1433,
user="username",
password="password",
database="dbname"
)
If you're using Windows Auth:
conn = pymssql.connect(
server="<servername>.database.windows.net",
port=1433,
user="DOMAIN\USERNAME",
password="password",
database="dbname"
)
Have you tried either of these connect methods?

Related

Oracle Connection with SQLAPI++

I'm trying to connect my c++ code with oracle using SQLAPI++ but it gives me the error
TNS:could not resolve the connect identifier specified
My code is like so:
con.Connect( "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=192.168.1.XXX) (PORT=1521))(CONNECT_DATA = (SERVICE_NAME = SERVICE_NAME )))", "UsrName", "Password", SA_Oracle_Client );
if I only use the same code but the username and password are equal to nothing like this:
con.Connect( "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=192.168.1.XXX) (PORT=1521))(CONNECT_DATA = (SERVICE_NAME = SERVICE_NAME )))", "", "", SA_Oracle_Client );
the compiler gives me an ORA-01017: Invalid username / password; connection refused\n error.
You may give instant client syntax a try:
[//]host[:port][/service name]
This I've used with SQLAPI++ successfully.
The string you've used is expected to occur in tnsnames.ora and you refer to this entry via a so called tnsname. If you can't change the tnsnames.ora stored in Oracle installation you're using then you can instruct the Oracle API to pick the file up form another location by defining the environmanet varable TNS_ADMIN. Set this to a directory were your own tnsnames.ora file exists.

Connecting to google cloud SQL Error using Flask-SQLAlchemy

I'm totally beginner for use flask and Google Cloud SQL. I want to make Login and Registration in my app using Flask-Login and Flask-SQLAlchemy.
But I can't connect to google cloud SQL using Flask-SQLAlchemy, this is my code.
SQLALCHEMY_DATABASE_URI = (
'mysql+pymysql://{db_user}:{db_password}#/{db_name}'
'?unix_socket=/cloudsql/{connection_name}').format(
user=db_user, password=db_password,
database=db_name, connection_name=connection_name)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
I just got this error :
(2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)")
But, when I try to make a connection using SQLAlchemy with this code, the connection is succeeded :
query_string = dict({"unix_socket": "/cloudsql/{}".format(connection_name)})
driver_name = 'mysql+pymysql'
db = sqlalchemy.create_engine(
sqlalchemy.engine.url.URL(
drivername=driver_name,
username=db_user,
password=db_password,
database=db_name,
query=query_string),
pool_size=5,
max_overflow=2,
pool_timeout=30,
pool_recycle=1800)
But when I tried to change the code like this :
app.config['SQLALCHEMY_DATABASE_URI'] = db
then, I got this error: 'Engine' object has no attribute 'drivername'.
Any suggestion for this problem? any advice, might be very helpful for me, Thank you.
This line right here actually assigns the "engine" object to your URI config:
app.config['SQLALCHEMY_DATABASE_URI'] = db
You can use the url object to create a URI instead:
uri = sqlalchemy.engine.url.URL(
drivername=driver_name,
username=db_user,
password=db_password,
database=db_name,
query=query_string)
app.config['SQLALCHEMY_DATABASE_URI'] = uri.render_as_string(hide_password=false)
You can compare the URI to the one you created and see where they differ. It's likely there is a typo, or that some value is escaped incorrectly.

send SMTP email for office365 with python using tls/ssl

i'm trying to create a python script that sends emails with some messages.
my setup is based on a smtp.office365.com. i created some script to do the job.
#!/usr/bin/python
print ("HI! let's start")
import smtplib
import getpass
port=587
smtp_server="smtp.office365.com"
sender_email='mymail#something.com'
receiver_email='mymail#something.com'
print ("defining server")
server = smtplib.SMTP(smtp_server,port)
password=getpass.getpass("enter password")
message='''
Hi,
THIS IS A TEST MESSAGE.
'''
print ("logging in")
server.login(sender_email,password)
print ("sending mail now")
server_sendmail(sender_email,receiver_email,message)
print ("all must be done by now")
But due to some reasons, it gets stuck after printing "defining server". and never reaches to asking for password. apparently the smtplib.SMTP command hangs. can you tell why this happens and how to get rid of it? my setup is as following :
Server: smtp.office365.com
/sjmail.com
security : STARTTLS
Port : 587
Vishesh Arya!
SMTP AUTH extension not supported by Office 365 account. Search for Microsoft Graph to do this.

Downloading a file with LDAP authentication

I'm trying to find a way to download a CSV from a network URI (not web) that requires LDAP authentication. I have a service account made for this, but I'm not able to find a working solution:
conn = ldap.open("10.41.10.10:389") #I've tried different URIs
conn.simple_bind_s('svc_acct#company.com', 'password')
call = open(r'\\fserv03\reports\gps_List.csv')
Is there a better way to do this?
Updated: Got Python-LDAP to work for my 64 bit install after downloading Python-LDAP to work, I downloaded python_ldap-2.4.28-cp27-cp27m-win_amd64 and running the pip install on it.
I was able to get this to work with the following (using Python-LDAP library):
try:
l = ldap.initialize('ldap://LDAP SERVER HERE')
l.protocol_version = ldap.VERSION2
username = "cn=USER, o=example.com"
password = 'PASSWORD HERE'
l.simple_bind(username, password)
except ldap.LDAPError, e:
print e

django generator function not working with real server

I have some code written in django/python. The principal is that the HTTP Response is a generator function. It spits the output of a subprocess on the browser window line by line. This works really well when I am using the django test server. When I use the real server it fails / basically it just beachballs when you press submit on the page before.
#condition(etag_func=None)
def pushviablah(request):
if 'hostname' in request.POST and request.POST['hostname']:
hostname = request.POST['hostname']
command = "blah.pl --host " + host + " --noturn"
return HttpResponse( stream_response_generator( hostname, command ), mimetype='text/html')
def stream_response_generator( hostname, command ):
proc = subprocess.Popen(command.split(), 0, None, subprocess.PIPE, subprocess.PIPE, subprocess.PIPE )
yield "<pre>"
var = 1
while (var == 1):
for line in proc.stdout.readline():
yield line
Anyone have any suggestions on how to get this working with on the real server? Or even how to debug why it is not working?
I discovered that the generator function is actually running but it has to complete before the httpresponse throws up a page onscreen. I don't want to have to wait for it to complete before the user sees output. I would like the user to see output as the subprocess progresses.
I'm wondering if this issue could be related to something in apache2 rather than django.
#evolution did you use gunicorn to deploy your app. If yes then you have created a service. I am having a similar kind of issue but with libreoffice. As much as I have researched I have found that PATH is overriding the command path present on your subprocess. I did not have a solution till now. If you bind your app with gunicorn in terminal then your code will also work.