Getting mac address from pc and compare it fails - python

I am using python 2.7 with sqlite3
I've created an empty table to and a function that checks if the table is empty it gets the mac address of the current pc and stores it at the table, it works every time the program work, then if the table is not empty it calls another function that gets the current mac and compares it to the one stored in the table , then closes the program if its not the same ,,
Here is the code :
def active():
from uuid import getnode as get_mac
mac = get_mac()
name = 666
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM mac")
count = c.fetchall()[0]
conn.close()
if count == 0:
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("INSERT INTO mac (name, macAddress) VALUES (?, ?)", (name, mac, ))
conn.commit()
conn.close()
else:
checking()
def checking():
from uuid import getnode as get_mac
mac = get_mac()
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("SELECT macAddress FROM mac WHERE name = 666")
table_mac = c.fetchall()[0]
if mac == table_mac:
critical_title1 = 'أهلاً بك '
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "تم تأكيد صلاحية النسخة للإستخدام "
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.information(mainWindow, critical_title, critical_msg)
else:
critical_title1 = 'خطأ'
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "لا يمكنك إستخدام البرنامج من دون شراء نسختك الخاصة"
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.critical(mainWindow, critical_title, critical_msg)
sys.exit()
everything goes fine and the program already catches the mac address then add it to the table, but then, in all cases, it shows the error that closes the program after it .. ignoring the if-else statement that should stop the error from being showed
i think the problem is here :
if mac == table_mac:
critical_title1 = 'أهلاً بك '
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "تم تأكيد صلاحية النسخة للإستخدام "
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.information(mainWindow, critical_title, critical_msg)
else:
critical_title1 = 'خطأ'
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "لا يمكنك إستخدام البرنامج من دون شراء نسختك الخاصة"
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.critical(mainWindow, critical_title, critical_msg)
sys.exit()
Note
the main problem that there is no traceback error
it just shows the last else statement despite the condition if mac == table_mac: is met

The problem was that I tried to call the 2nd function from inside the first one I just changed
else:
checking()
to pass and then add autorun command for both functions and it works great
active()
checking()

Related

How can i run all my code in one function

My python code doesnt work. I get an output for only success mysql connection.
I want to print group id, hostname and other variables. The only output i get is
('Connected to MySQL Server version ', u'5.7.36-0ubuntu0.18.04.1')
("You're connected to database: ")
I cannot print group id or anything else. Im a newbie in python :(
import os
import mysql.connector
import json
execfile("/home/manager/test/mysqlconnector.py")
active_ip = ""
hostname = ""
group_id = 0
def my_funciton():
query = "select value_oid from snmp_trap where name_oid = '1.3.6.1.4.1.14823.2.3.3.1.200.1.17.0'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
mac = cursor.fetchone()
mac_string = mac.values()
mac_str = json.dumps(mac_string)
mac_ = mac_str.replace(':','')
mac_ = mac_.replace('"','')
mac_ = mac_.replace(']','')
mac_ = mac_.replace('[','')
return mac_
active_mac = my_function()
query = "select epp_active_ip, epp_hostname, epp_group_id from epp_inventory where epp_active_mac = + 'active_mac.upper()'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
rows = cursor.fetchall()
#active_ip = ""
#hostname = ""
#group_id = 0
for row in rows:
active_ip = row["epp_active_ip"]
hostname = row["epp_hostname"]
group_id = row["epp_group_id"]
print(group_id)
query = "select wmic_id from group_wmic where group_id = " + str(group_id)
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
wmic_ids = cursor.fetchall()
for row in wmic_ids:
query = "select command_line from wmic_commands where id = " + row["wmic_id"]
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
command_line = cursor.fetchone()
os.system(command_line)
os.system("ls -al")
#os.system(command)
my_funciton()
Apart from naming and indentation issues, which you should really fix, because it will make your code a nightmare to maintain - the issue is quite simple:
Consider:
def some_function():
print('this prints')
return
print('this does not')
Your code has the exact same problem. In your function my_funciton, you have the following line:
return mac_
Nothing after that will ever execute. You need to put the return statement in the position of the function's code where you expect it to actually return. You cannot put it just anywhere and expect the function to execute the rest of the code.

Query function suddenly returning `None` instead of the item it should be retruning

I did some minor refactoring to some working code. All I did was add 2 functions to clean up how input and it's assignment was handled. I did not change anything about the query_pswd_by_name function but now it doesn't return the password, it returns None. Everything else works perfectly. Any ideas what is going on? Here is the code:
import secrets
import string
import sqlite3
import pyperclip
import optparse
#CREATE PASSWORD OF GIVEN LENGTH
def get_pass(length):
return "".join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) for x in range(length))
def get_pass_length():
length = int(input("Enter the length of password: "))
password= get_pass(length)
print(password)
pyperclip.copy(password)
print('Password copied to clipboard')
def create_and_store_pwsd():
password = get_pass_length()
name = str(input("Enter name for password: "))
#CREATE DATABASE CONNECTION
conn = sqlite3.connect("managerDB.db")
#CREATE CURSOR OBJECT
c = conn.cursor()
#CREATE TABLE IN DISK FILE BASED DATABASE
c.execute("""CREATE TABLE IF NOT EXISTS password_table (
name TEXT,
pswd TEXT
)""")
#c.execute("DELETE FROM password_table")
c.execute("INSERT INTO password_table (name, pswd) VALUES (?, ?)", (name, password))
#COMMIT CHANGES
conn.commit()
conn.close()
def query_pswd_by_name(name):
conn = sqlite3.connect('managerDB.db')
c = conn.cursor()
query_password = "SELECT pswd FROM password_table WHERE name = ?"
c.execute(query_password,(name,))
result = c.fetchall()
for row in result:
pyperclip.copy(str(row[0]))
print("Password copied to clipboard")
print(str(row[0]))
conn.commit()
conn.close()
def input_name_and_query():
name = input('Name of password you wish to query: ')
query_pswd_by_name(name)
create_and_store_pwsd()
input_name_and_query()```
I mean, at face value, it returns None because you never return anything from the function. You are copying it to the clip board.
A bit more detail would be good. What functions were refactored? What is the output to the console of all your print statements?
As an aside, I'd recommend wrapping the module functionality (last two calls) in an if __name__ == "__main__" block

Why pymysql not insert record into table?

I am pretty new in python developing. I have a long python script what "clone" a database and add additional stored functions and procedures. Clone means copy only the schema of DB.These steps work fine.
My question is about pymysql insert exection:
I have to copy some table contents into the new DB. I don't get any sql error. If I debug or print the created INSERT INTO command is correct (I've tested it in an sql editor/handler). The insert execution is correct becuse the result contain the exact row number...but all rows are missing from destination table in dest.DB...
(Ofcourse DB_* variables have been definied!)
import pymysql
liveDbConn = pymysql.connect(DB_HOST, DB_USER, DB_PWD, LIVE_DB_NAME)
testDbConn = pymysql.connect(DB_HOST, DB_USER, DB_PWD, TEST_DB_NAME)
tablesForCopy = ['role', 'permission']
for table in tablesForCopy:
with liveDbConn.cursor() as liveCursor:
# Get name of columns
liveCursor.execute("DESCRIBE `%s`;" % (table))
columns = '';
for column in liveCursor.fetchall():
columns += '`' + column[0] + '`,'
columns = columns.strip(',')
# Get and convert values
values = ''
liveCursor.execute("SELECT * FROM `%s`;" % (table))
for result in liveCursor.fetchall():
data = []
for item in result:
if type(item)==type(None):
data.append('NULL')
elif type(item)==type('str'):
data.append("'"+item+"'")
elif type(item)==type(datetime.datetime.now()):
data.append("'"+str(item)+"'")
else: # for numeric values
data.append(str(item))
v = '(' + ', '.join(data) + ')'
values += v + ', '
values = values.strip(', ')
print("### table: %s" % (table))
testDbCursor = testDbConn.cursor()
testDbCursor.execute("INSERT INTO `" + TEST_DB_NAME + "`.`" + table + "` (" + columns + ") VALUES " + values + ";")
print("Result: {}".format(testDbCursor._result.message))
liveDbConn.close()
testDbConn.close()
Result is:
### table: role
Result: b"'Records: 16 Duplicates: 0 Warnings: 0"
### table: permission
Result: b'(Records: 222 Duplicates: 0 Warnings: 0'
What am I doing wrong? Thanks!
You have 2 main issues here:
You don't use conn.commit() (which would be either be liveDbConn.commit() or testDbConn.commit() here). Changes to the database will not be reflected without committing those changes. Note that all changes need committing but SELECT, for example, does not.
Your query is open to SQL Injection. This is a serious problem.
Table names cannot be parameterized, so there's not much we can do about that, but you'll want to parameterize your values. I've made multiple corrections to the code in relation to type checking as well as parameterization.
for table in tablesForCopy:
with liveDbConn.cursor() as liveCursor:
liveCursor.execute("SELECT * FROM `%s`;" % (table))
name_of_columns = [item[0] for item in liveCursor.description]
insert_list = []
for result in liveCursor.fetchall():
data = []
for item in result:
if item is None: # test identity against the None singleton
data.append('NULL')
elif isinstance(item, str): # Use isinstance to check type
data.append(item)
elif isinstance(item, datetime.datetime):
data.append(item.strftime('%Y-%m-%d %H:%M:%S'))
else: # for numeric values
data.append(str(item))
insert_list.append(data)
testDbCursor = testDbConn.cursor()
placeholders = ', '.join(['`%s`' for item in insert_list[0]])
testDbCursor.executemany("INSERT INTO `{}.{}` ({}) VALUES ({})".format(
TEST_DB_NAME,
table,
name_of_columns,
placeholders),
insert_list)
testDbConn.commit()
From this github thread, I notice that executemany does not work as expected in psycopg2; it instead sends each entry as a single query. You'll need to use execute_batch:
from psycopg2.extras import execute_batch
execute_batch(testDbCursor,
"INSERT INTO `{}.{}` ({}) VALUES ({})".format(TEST_DB_NAME,
table,
name_of_columns,
placeholders),
insert_list)
testDbConn.commit()
How to insert data into table using python pymsql
Find my solution below
import pymysql
import datetime
# Create a connection object
dbServerName = "127.0.0.1"
port = 8889
dbUser = "root"
dbPassword = ""
dbName = "blog_flask"
# charSet = "utf8mb4"
conn = pymysql.connect(host=dbServerName, user=dbUser, password=dbPassword,db=dbName, port= port)
try:
# Create a cursor object
cursor = conn.cursor()
# Insert rows into the MySQL Table
now = datetime.datetime.utcnow()
my_datetime = now.strftime('%Y-%m-%d %H:%M:%S')
cursor.execute('INSERT INTO posts (post_id, post_title, post_content, \
filename,post_time) VALUES (%s,%s,%s,%s,%s)',(5,'title2','description2','filename2',my_datetime))
conn.commit()
except Exception as e:
print("Exeception occured:{}".format(e))
finally:
conn.close()

python to write data into table error

write python program to create a mysql table and insert data into this table,the program is as follows:
def pre_data_db_manage(type,data):
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="********", db="facebook_info",charset="utf8")
cur = conn.cursor()
if type == "pre_davi_group_members_data":
is_exist_table_sql = "SHOW TABLES LIKE 'fb_pre_davi_group_members_posts'"
if cur.execute(is_exist_table_sql) == 0:
create_table_sql = '''CREATE TABLE fb_pre_davi_group_members_posts (id bigint not null primary key auto_increment,userID bigint,userName varchar(128),userURL varchar(256),
postTime varchar(128),postText text,postTextLength int,likesCount int,sharesCount int,commentsCount int,postTextPolarity varchar(64),postTextSubjectivity varchar(64))'''
cur.execute(create_table_sql)
r = re.compile(r'^[a-zA-Z0-9]')
for item in data:
if "'" in item["PostText"]:
item["PostText"] = item["PostText"].replace("'"," ")
if "\\" in item["PostText"]:
item["PostText"] = item["PostText"].replace("\\","\\\\")
for i in item["PostText"]:
result = r.match(i)
if result == None:
print("in re")
item['PostText'] = item['PostText'].replace(i, ' ')
if "nan" in item["SharesCount"]:
item["SharesCount"] = 0
if "nan" in item["LikesCount"]:
item["LikesCount"] = 0
if "nan" in item["CommentsCount"]:
item["CommentsCount"] = 0
if "nan" in item["PostTextLength"]:
item["PostTextLength"] = 0
item["PostTextLength"] = int(item["PostTextLength"])
item["LikesCount"] = int(item["LikesCount"])
item["SharesCount"] = int(item["SharesCount"])
item["CommentsCount"] = int(item["CommentsCount"])
if type == "pre_davi_group_members_data":
insert_sql = '''INSERT INTO fb_pre_davi_group_members_posts (userID,userName,userURL,
postTime,postText,postTextLength,likesCount,sharesCount,commentsCount,postTextPolarity,postTextSubjectivity) VALUES
({0},"{1}",'{2}','{3}','{4}',{5},{6},{7},{8},{9},{10})'''.format(item["UserID"],item["UserName"],item["UserURL"],item["PostTime"],item["PostText"],item["PostTextLength"],item["LikesCount"],item["SharesCount"],item["CommentsCount"],item["PostTextPolarity"],item["PostTextSubjectivity"])
print(insert_sql)
try:
cur.execute(insert_sql)
except Exception as e:
print("insert error")
continue
cur.close()
conn.commit()
conn.close()
and write call statement as follows:
type = "pre_davi_group_members_data"
pre_data_db_manage(type, df_list)
however,when execute this program, found that no data have been inserted into table:fb_pre_davi_group_members_posts,
in the mysql order line, write:
select count(*) from fb_pre_davi_group_members_posts;
the result is 0
could you please tell me the reason and how to solve it

python sqlite3 logic (for console server and command)

I am trying to return some commands to my partner in sqlite3 db in python.
As my partner needs me to write a function to return command, I need some idea from the logic to write the function.
First I write the thing that maybe useless.
def readrouter():
function = "SELECT command FROM switch WHERE type = ? or function = ? ORDER BY key ASC"
conn = sqlite3.connect('server.db')
cur = conn.cursor()
print(read)
conn.commit()
I have learned that now I am trying to connect to server but it can't return my variable function and print it out.
Should I make parameter for the function and how should I write it?
thanks for help and now i fix it with:
def readswitch(function,read):
conn = sqlite3.connect('server.db')
cur = conn.cursor()
function = "SELECT command FROM switch WHERE type = ? or function = ? ORDER BY key ASC"
cur.execute(function)
read = cur.fetchone()
for row in read:
print(read)
conn.commit()
is there any mistake and def readswitch(function,read): shows that the function and read [Parameter 'function' value is not used]
where is my mistake?
# Paul Rooney
for the meaning of the function
function = "SELECT command FROM switch WHERE type = ? or function = ? ORDER BY key ASC"
is to select some kinds of commands by different function
for example:
My partner want to select a vlan command
then i will search the function which is "create vlan"
and the usage of type is to provide some command which is global use (enable, conf t)
For the command , i will print out:
('enable',)
('configure terminal',)
('vlan (number)',)
('name (vlan name)',)
now , should i make two variables to fill in the "?"
like:
function = "SELECT command FROM switch WHERE type = " +x+" or function = " +y+ " ORDER BY key ASC"
In the Parameterized queries http://zetcode.com/db/sqlitepythontutorial/
I do not know what is the meaning of uId = 1 and i change it to x=1
what will be happen?
now i correct it like:
def readswitch(function,read):
x=1
#
conn = sqlite3.connect('server.db')
cur = conn.cursor()
function = "SELECT command FROM switch WHERE function =:function  ORDER BY key ASC",{"function":x}
con.commit()
cur.execute(function)
read = cur.fetchone()
for row in read:
print read.row[0], row[1]

Categories