I'm trying to update user credentials for PostgreSQL db user using Python. I've tried referring to the following thread but that doesn't seem to solve my issue unfortunately:
How to change password of a newly created user using variable in postgresql 9.5 SP
Here's my code:
con = p.connect(database="mydB", user="abc", password="testing", host="127.0.0.1", port="5432")
cur = con.cursor()
uid = "adi"
pwd = "test6"
statement = statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)
cur.execute( statement)
cur.execute('''COMMIT''')
I get the following error:
ProgrammingError: syntax error at or near "'adi'"
Please help or refer me to a thread with a better solution. Thanks in advance, everyone!
error image
I was able to solve this successfully.
import psycopg2 as p
con = p.connect(database="mydB", user="adi", password="xxxx", host="127.0.0.1", port="5432")
cur = con.cursor()
uid = "adi"
pwd = "test"
statement = '''ALTER USER {} WITH PASSWORD %s '''.format(uid)
cur.execute(statement, [pwd])
cur.execute('''COMMIT''')
Try to give the username and password in the actual statement and try executing.
First try removing the extra quotation before ALTER USER and execute.
If doesn't work try this:
statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE 'ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)
cur.execute(statement)
Related
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! :)
I have an LDAP Query which is running perfectly fine in my terminal
ldapsearch -h ldap.mygreatcompany.com -D user#mygreatcompany.COM -w "$ldappassword" -b "DC=abc,DC=mygreatcompany,DC=com" -s sub "(mail=user1#mygreatcompany.COM)" sAMAccountName
I want to run this command in python3, I followed other answers from StackOverflow and wrote something like this,
import ldap
l = ldap.initialize('ldap://ldap.mygreatcompany.com')
binddn = "user#mygreatcompany.COM"
pw = #ldappassword
basedn = "DC=abc,DC=mygreatcompany,DC=com"
searchAttribute = ["sAMAccountName"]
searchFilter = "(&(mail=user1#mygreatcompany.COM')(objectClass=*))"
searchScope = ldap.SCOPE_SUBTREE
l.simple_bind_s(binddn, pw)
ldap_result_id = l.search_s(basedn, searchScope, searchFilter, searchAttribute)
#Get result
l.unbind_s()
But Here I am not getting the result from ldap_result_id. Can anybody help what is the correct way to do this query?
Thanks
It turns out that I was not using connection.set_option(ldap.OPT_REFERRALS, 0) in the code and there is some issue in LDAP which automatically chases the referrals internally with anonymous access which fails.
Here is the working code:
def get_user_id(email):
# Seach fiter for user mail
searchFilter = "mail={}".format(email)
try:
# binding to ldap server
connection = ldap.initialize('ldap://yourcompanyhost')
connection.set_option(ldap.OPT_REFERRALS, 0)
connection.protocol_version = ldap.VERSION3
connection.simple_bind_s(binddn, pwd)
# get result
ldap_result_id = connection.search_s(basedn, searchScope, searchFilter, searchAttribute)
# extract the id
saMAccount = ldap_result_id[0][1]["sAMAccountName"][0].decode('utf-8')
except ldap.INVALID_CREDENTIALS:
print("Your username or password is incorrect.")
except ldap.LDAPError as e:
print(e)
except:
print("Data doesn't exist for this user")
connection.unbind_s()
print(get_user_id("user1#mygreatcompany.COM"))
ulogin=str(self.t1.get())
med=str(self.mymed.get("1.0",END))
print(med)
conn = connect("med.db")
c = conn.cursor()
c.execute("UPDATE user_details SET reminder ="+ med +"WHERE username =" + ulogin)
conn.commit
conn.close()
im trying to get this to update a text wall however it breaks continuously
line 284 on GitHub
link: https://github.com/Polar001/medicine-reminder/commit/0f6e74a1103937a24c67af3e8f07a2bcf0975f0a
if possible be as basic as possible im not good at coding at all
Your SQL statement is incorrectly constructed, use placeholder as below:
c.execute("UPDATE user_details SET reminder = ? WHERE username = ?", (med, ulogin))
First and foremost, I must admit I am new to Python and SQL. Now, I will get the problem. I am trying to update a table where column_ID is equivalent to a variable. In the Python class I have a function with the following statement:
stName = self.txtName.text()
stUsername = self.txtUsername.text()
stPassword = self.txtPassword.text()
stMobile = self.txtMobile.text()
myID = self.txtID.text()
sql_update_query = """UPDATE signup SET name = %s, username = %s, password = %s, mobile = %s WHERE id = myID"""
input = (stName, stUsername, stPassword, stMobile)
curs.execute(sql_update_query, input)
conn.commit()
When I click the Update button to run this function, the system prompts 'Python has stopped working'.
Can someone assist me to fix the SQL statement?
myID needs to be passed as an argument to the sql statement.
sql_update_query = """UPDATE signup SET name = %s, username = %s, password = %s, mobile = %s WHERE id = %s"""
And
input = (stName, stUsername, stPassword, stMobile, myID)
I am running this code
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from %(tablename)s where userid = %(userid)s"
result = db.run_query_vals(sql, payload)
res = result.fetchall()
return res
but get an error
SQLError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''statuser' where userid = '14'' at line 1
The arguments being passed are :
sql = "select * from %(tablename)s where userid = %(userid)s"
payload = {'tablename' : 'statuser', 'userid' : 14}
As far as I understand, the query being passed to MySQL is along the lines of
select * from 'statuser' where userid = '14'
which is where I get the error; the tablename isnt supposed to be enclosed in quotes. How do I have the name included without the quotes/make them backquotes?
(I don't want to hard-code the table name - this is a variable and is initialised according to different parameters during class creation). Any help here?
You can use the .format() from string in python:
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from {tablename} where userid = {userid}"
sql = sql.format(**payload)
# result = db.run_query_vals(sql, payload) # Method to run query
res = result.fetchall()
return res
I encountered the same problem in pymysql and have figured out a solution:
rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.
don't know whether it will help in your case, just sharing a possible way
similiar question: How to remove extra quotes in pymysql
Here's my code:
from pymysql.connections import Connection, converters
class MyConnect(Connection):
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str):
return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()