How to use Python to open a .sqlite with password - python-3.x

I have a .sqlite file which is protected by a password. When I use viewer like SQLiteStudio to connect it, I need to manually input the password in UI.
When I use c# to connect it, the codes as below work very well:
string db_file_path = "xxx.sqlite";
string conn_conf = $"Data Source={db_file_path};Version=3;password={db_passwd}";
SQLiteConnection conn = new SQLiteConnection(conn_conf);
But for python, the code is like this:
sqlite_file = '/xxx.db'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
"OperationalError: unable to open database file" appear on the connect()
So, how to use the password??? How to open it???

Related

Read SQL from sqlite3 database in Windows using connectorx

I tried to establish a connection to my sqlite3 database which is located on my laptop's hard drive. I used the follwing example code from https://sfu-db.github.io/connector-x/databases/sqlite.html:
import connectorx as cx
db_path = '/home/user/path/test.db' # path to your SQLite database
conn = 'sqlite://' + db_path # connection token
query = 'SELECT * FROM `database.dataset.table`' # query string
cx.read_sql(conn, query) # read data from SQLite
Since I'm using Windows the path to the database contains a colon:
db_path = 'E:/my_db.db'
conn = 'sqlite://E:/my_db.db'
When I try to execute cx.read_sql(conn, 'select * from tablename') I get the following error message:
[2023-01-21T19:01:47Z ERROR r2d2] unable to open database file: E/my_db.db
What's interesing about the error message is that the path to the database which it displays is missing the colon. It is E/my_db.db instead of E:/my_db.db. It looks like a bug. So the question is: How to establish the connection to my database on Windows?
I got the hint to use db_path = urllib.parse.quote(os.path.abspath(database_name)) but it didn't really help me out. Now I get the following error:
RuntimeError: Conversion error from type Text at index: 11, trailing input

Execute customized script when launching instance using openstacksdk

I'm new to Openstack and I'm trying to create a tool so that I can launch any number of instances in an Openstack cloud. This was easily done using the nova-client module of openstacksdk.
Now the problem is that I want to make the instances execute a bash script as they are created by adding it as a userdata file, but it doesn't execute. This is confusing because I don't any error or warning message. Does anyone know what could it be?
Important parts of the code
The most important parts of the Python program are the function which gets the cloud info, the one that creates the instances and the main function, . I'll post them here as #Corey told.
"""
Function that allow us to log at cloud with all the credentials needed.
Username and password are not read from env.
"""
def get_nova_credentials_v2():
d = {}
user = ""
password = ""
print("Logging in...")
user = input("Username: ")
password = getpass.getpass(prompt="Password: ", stream=None)
while (user == "" or password == ""):
print("User or password field is empty")
user = input("Username: ")
password = getpass.getpass(prompt="Password: ", stream=None)
d['version'] = '2.65'
d['username'] = user
d['password'] = password
d['project_id'] = os.environ['OS_PROJECT_ID']
d['auth_url'] = os.environ['OS_AUTH_URL']
d['user_domain_name'] = os.environ['OS_USER_DOMAIN_NAME']
return d
Then we have the create_server function:
"""
This function creates a server using the info we got from JSON file
"""
def create_server(server):
s = {}
print("Creating "+server['compulsory']['name']+"...")
s['name'] = server['compulsory']['name']
s['image'] = server['compulsory']['os']
s['flavor'] = server['compulsory']['flavor']
s['min_count'] = server['compulsory']['copyNumber']
s['max_count'] = server['compulsory']['copyNumber']
s['userdata'] = server['file']
s['key_name'] = server['compulsory']['keyName']
s['availability_zone'] = server['compulsory']['availabilityZone']
s['nics'] = server['compulsory']['network']
print(s['userdata'])
if(exists("instalacion_k8s_docker.sh")):
print("Exists")
s['userdata'] = server['file']
nova.servers.create(**s)
And now the main function:
"""
Main process: First we create a connection to Openstack using our credentials.
Once connected we cal get_serverdata function to get all instance objects we want to be created.
We check that it is not empty and that we are not trying to create more instances than we are allowed.
Lastly we create the instances and the program finishes.
"""
credentials = get_nova_credentials_v2()
nova = client.Client(**credentials)
instances = get_serverdata()
current_instances = len(nova.servers.list())
if not instances:
print("No instance was writen. Check instances.json file.")
exit(3)
num = 0
for i in instances:
create_server(i)
exit(0)
For the rest of the code you can access to this public repo on github.
Thanks a lot!
Problem solved
The problem was the content of the server['file'] as #Corey said. It cannot be the Path to the file where you wrote the data but the content of it or a file type object. In the case of OpenstackSDK it must be base64 encoded but it is not the case in Novaclient.
Thanks a lot to #Corey for all the help! :)

ldap3 add user to group after conn.search

currently, I am writing an AWS Lambda function and the idea is, that someone can send an email to a specific address with a username and AD group and it will trigger the function and add this person to the desired group.
I am using the python module ldap3 and the conn.search part is working, aswell as the addUsersInGroup, but only if I run it separately. If I create a script where I already have the cn or dn name of both user and group and use the addUsersInGroup Function it works, but if I do a conn.search somewhere before it somehow can't establish the connection for the add-to-group part.
from ldap3 import Server, Connection, ALL, NTLM, SUBTREE
from ldap3.extend.microsoft.addMembersToGroups import ad_add_members_to_groups as addUsersInGroups
import email
import os
import json
email = "sample#test.com"
subject = "username,ad-group"
user = subject.split(",")[0]
group = subject.split(",")[1]
emaildomain = email.split("#")[1]
domaingroup = ["test.com"]
adgroups = ["group1","group2"]
server = Server('serverIP', use_ssl=True, get_info=ALL)
conn = Connection(server, OU,
password, auto_bind=True)
def find_user():
user_criteria = "(&(objectClass=user)(sAMAccountName=%s))"%user
if conn.search("OU", user_criteria):
result = str(conn.entries)
user_dn = result.split("-")[0].replace("[DN: ","")
return user_dn
return nouser
def find_group():
group_criteria = "(&(objectClass=group)(sAMAccountName=%s))"%group
if conn.search("OU", group_criteria):
result_group = str(conn.entries)
group_dn = result_group.split("-")[0].replace("[DN: ","")
return group_dn
return nogroup
def add_to_group(user,group):
addUsersInGroups(conn,user,group)
if emaildomain in domaingroup:
user = find_user()
group = find_group()
add_to_group(user,group)
Please note that I had to delete some things off the script for security reasons.
The connection to search for a user or group is working and if I run the add-to-group function it works too, but only running it without any search beforehand.
Somehow I have the feeling that making the conn.search blocks the connection for anything search related and if try to use the same connection for something different e.g. adding a user to group, that request gets blocked.
Here is the error I receive:
Error_Message
Found the solution on this website:
https://github.com/cannatag/ldap3/issues/442
You are getting this error probably due to auto_referrals=True in Connection by default. Try to use:
conn = Connection(server, "cn=xxx,cn=users,dc=wwww,dc=zzzz,dc=com", "my_pass", auto_bind=True, auto_referrals=False) and do not search and another DC.

ValueError: character U+590048 is not in range [U+0000; U+10ffff] - MAC OS

Could someone help me with the below error while connecting to Teradata from my Python environment.
I'm using ODBC driver method and I've tried all the below existing methods to connect but no luck.
Note: if you are using windows, you can directly use these methods, however the problem comes when you are on MAC OS (not for all though)
USING TERADATA Module and SQL Alchemy.
import teradata
import pyodbc
server='111.00.00.00'
username = 'user'
password = 'pwd'
udaExec = teradata.UdaExec(appName="test", version="1.0",
logConsole=True)
ndw_con = udaExec.connect(method = 'odbc',authentication = "LDAP",
system=server, username=username, password=password)
# SQL ALCHEMY from teradata
from sqlalchemy import create_engine
user = 'user'
pwd = 'pwd'
host = '1'11.00.00.00'
td_engine = create_engine('teradata://'+user+':'+pwd+'#'+host+':22/' )
result = td_engine.execute('select top 100 * from temp.sampledata')
# USING PYODBC: the below code gave me a new error saying ('01000', "
[01000]
[unixODBC][Driver Manager]Can't open lib 'Teradata' : file not found
(0) (SQLDriverConnect)")
import pyodbc
td_conn = pyodbc.connect('DRIVER= .
{Teradata};DBCName='+server+';UID='+username+';PWD='+ password,
automcommit=True)
cursor = td_conn.cursor()
Regardless, I was unable to made a connection to teradata, could someone let me know what's going on here and how to fix this issue once for all.
Thanks!
Found the answer using pyodbc module. Replaced Driver = {Teradata} parameter with full path where the driver is located, check below fpr the full connection string. Please note that this can only be used on MAC OS.
td_conn = pyodbc.connect('DRIVER={/Library/Application Support/teradata/client/16.20/lib/tdataodbc_sbu.dylib};DBCName='+server+';UID='+username+';PWD='+ password, automcommit=True, authentication = "LDAP")

How to use dcmtk/dcmprscp in Windows

How can I use dcmprscp to receive from SCU Printer a DICOM file and save it, I'm using dcmtk 3.6 & I've some trouble to use it with the default help, this's what I'm doing in CMD:
dcmprscp.exe --config dcmpstat.cfg --printer PRINT2FILE
each time I receive this messagebut (database\index.da) don't exsist in windows
W: $dcmtk: dcmprscp v3.6.0 2011-01-06 $
W: 2016-02-21 00:08:09
W: started
E: database\index.dat: No such file or directory
F: Unable to access database 'database'
I try to follow some tip, but the same result :
http://www.programmershare.com/2468333/
http://www.programmershare.com/3020601/
and this's my printer's PRINT2FILE config :
[PRINT2FILE]
hostname = localhost
type = LOCALPRINTER
description = PRINT2FILE
port = 20006
aetitle = PRINT2FILE
DisableNewVRs = true
FilmDestination = MAGAZINE\PROCESSOR\BIN_1\BIN_2
SupportsPresentationLUT = true
PresentationLUTinFilmSession = true
PresentationLUTMatchRequired = true
PresentationLUTPreferSCPRendering = false
SupportsImageSize = true
SmoothingType = 0\1\2\3\4\5\6\7\8\9\10\11\12\13\14\15
BorderDensity = BLACK\WHITE\150
EmptyImageDensity = BLACK\WHITE\150
MaxDensity = 320\310\300\290\280\270
MinDensity = 20\25\30\35\40\45\50
Annotation = 2\ANNOTATION
Configuration_1 = PERCEPTION_LUT=OEM001
Configuration_2 = PERCEPTION_LUT=KANAMORI
Configuration_3 = ANNOTATION1=FILE1
Configuration_4 = ANNOTATION1=PATID
Configuration_5 = WINDOW_WIDTH=256\WINDOW_CENTER=128
Supports12Bit = true
SupportsDecimateCrop = false
SupportsTrim = true
DisplayFormat=1,1\2,1\1,2\2,2\3,2\2,3\3,3\4,3\5,3\3,4\4,4\5,4\6,4\3,5\4,5\5,5\6,5\4,6\5,6
FilmSizeID = 8INX10IN\11INX14IN\14INX14IN\14INX17IN
MediumType = PAPER\CLEAR FILM\BLUE FILM
MagnificationType = REPLICATE\BILINEAR\CUBIC
The documentation of the "dcmprscp" tool says:
The dcmprscp utility implements the DICOM Basic Grayscale Print
Management Service Class as SCP. It also supports the optional
Presentation LUT SOP Class. The utility is intended for use within the
DICOMscope viewer.
That means, it is usually not run from the command line (as most of the other DCMTK tools) but started automatically in the background by DICOMscope.
Anyway, I think the error message is clear:
E: database\index.dat: No such file or directory
F: Unable to access database 'database'
Did you check whether there is a subdirectory "database" and whether the "index.dat" file exists in this directory? If you should ask why there is a need for a "database" then please read the next paragraph of the documentation:
The dcmprscp utility accepts print jobs from a remote Print SCU.
It does not create real hardcopies but stores print jobs in the local
DICOMscope database as a set of Stored Print objects (one per page)
and Hardcopy Grayscale images (one per film box N-SET)

Resources