Creating a Linux Userlist with Python - python

I am writing a script in Python that will look at all of the groups AND all of the users on a linux system, and output me a file.
I have a situation where if an account is in a certain group, I want to set the user ID myself (in this example, it is because the account/s is a Non User Account)
Code below:
#/usr/bin/python
import grp,pwd,os
from os.path import expanduser
destdir = expanduser("~")
destfile = '/newfile.txt'
appname = 'app name'
groupid = ''
userid = ''
#delete old feed file and create file
if os.path.exists(destdir + destfile):
os.remove(destdir + destfile)
print "file deleted...creating new file"
output = open(destdir + destfile, 'w+')
output.write('ACCOUNTID|USERLINKID|APPLICATIONROLE|APPLICATION' + '\n')
else:
print "no file to delete...creating file"
output = open(destdir + destfile, 'w+')
output.write('ACCOUNTID|USERLINKID|APPLICATIONROLE|APPLICATION' + '\n')
#get user/group data for all users non primary groups
#documentation: https://docs.python.org/2/library/grp.html
groups = grp.getgrall()
for group in groups:
groupid = group[2]
print groupid #checking to see if group ids print correctly. Yes it does
for user in group[3]:
if groupid == '33': #Issue is here!
userid = 'qwerty'
print userid #testing var
output.write(user + '|' + userid + '|' + group[0] + '|' + appname + '\n')
The issue is here:
if groupid == '33': #Issue is here!
userid = 'qwerty'
print userid #testing var
The variable "userid" is never set to it's value and never prints anything while testing.
The group "33" does have users in it and exists. I cannot figure out why this doesn't work :(
I have another piece of code that does this for users (as I am looking at both Primary and Secondary groups, and once I figure out this part, I can fix the rest)

Your validate of groupid is against a string, it is an integer
if groupid == 31: # then do something

Related

Duplicated data in excel using Openpyxl

I have created a python script that will append data in excel. However, data that are being transferred in excel is having multiple duplication. Can someone help me fix my script?
tree = ET.parse('users.xml')
root = tree.getroot()
#create excel
wb = Workbook()
ws = wb.active
ws.title = ("Active Users")
df=pd.DataFrame(columns=["Login", "User Name", "Role", "Status"])
for user in root.findall('user'):
login = user.find('login').text
for m in tls.getUserByLogin(login):
user_status = int(m.get("isActive"))
if user_status == 1:
lastname = m.get("lastName")
firstname = m.get("firstName")
userLogin = m.get("login")
activeStatus = ("Active User")
role = m.get("globalRole")
tproject = m.get("tprojectRoles")
print("Login: " + userLogin + " " + lastname + " " + firstname + " Role: " + str(role['name']) + " " + str(activeStatus))
df.loc[len(df.index)] =[userLogin, lastname, str(role['name']), str(activeStatus)]
for row in dataframe_to_rows(df, index = False):
ws.append(row)
else:
inactive = (str(m.get("firstName")) + " " + str(m.get("lastName")) +": User is not Active")
print(inactive)
wb.save(filename = 'userData.xlsx')
The output in excel is this:
Login = A1 , User Name = B1, Role = C1, Status = D1
Login User Name Role Status
admin Administrator Admin Active
Login User Name Role Status
admin Administrator Admin Active
user1 Pedro leader Active
Login User Name Role Status
admin Administrator Admin Active
user1 Pedro leader Active
user2 Juan leader Active
Also, for my else loop for inactive users, is it possible to append them in the same excel file to another sheet? Thank you all
Hi to #Redox and #taipei thank you for your quick responses and answers,
I have resolve my duplication issues in a different format :)
def getUserDetail():
tree = ET.parse('users.xml')
root = tree.getroot()
#create excel
workbook = Workbook()
ws = workbook.active
ws.title = ("Active Users")
ws.append(['Login', 'User Name', 'Role', 'Status'])
#logins = []
for user in root.findall('user'):
login = user.find('login').text
# logins.append(login)
# for index in range(10):
# login = logins[index]
for m in tls.getUserByLogin(login):
user_status = int(m.get("isActive"))
if user_status == 1:
lastname = m.get("lastName")
firstname = m.get("firstName")
userLogin = m.get("login")
activeStatus = ("Active User")
role = m.get("globalRole")
tproject = m.get("tprojectRoles")
print("Login: " + userLogin + " " + lastname + " " + firstname + " Role: " + str(role['name']) + " " + str(activeStatus))
data = [[userLogin, lastname + firstname, str(role['name']), str(activeStatus)]]
for row in data:
ws.append(row)
else:
inactive = (str(m.get("firstName")) + " " + str(m.get("lastName")) +": User is not Active")
print(inactive)
### MOVED code here - note it should be outside ALL for loops ####
workbook.save(filename = 'userData.xlsx')
getUserDetail()
The ws.append() and ws.save should be outside of the ALL for loops, including the first one. Updated code here.
tree = ET.parse('users.xml')
root = tree.getroot()
#create excel
wb = Workbook()
ws = wb.active
ws.title = ("Active Users")
df=pd.DataFrame(columns=["Login", "User Name", "Role", "Status"])
for user in root.findall('user'):
login = user.find('login').text
for m in tls.getUserByLogin(login):
user_status = int(m.get("isActive"))
if user_status == 1:
lastname = m.get("lastName")
firstname = m.get("firstName")
userLogin = m.get("login")
activeStatus = ("Active User")
role = m.get("globalRole")
tproject = m.get("tprojectRoles")
print("Login: " + userLogin + " " + lastname + " " + firstname + " Role: " + str(role['name']) + " " + str(activeStatus))
df.loc[len(df.index)] =[userLogin, lastname, str(role['name']), str(activeStatus)]
else:
inactive = (str(m.get("firstName")) + " " + str(m.get("lastName")) +": User is not Active")
print(inactive)
### MOVED code here - note it should be outside ALL for loops ####
for row in dataframe_to_rows(df, index = False):
ws.append(row)
wb.save(filename = 'userData.xlsx')
Are you sure that users.xml only contains a unique user?
If you're not sure, I think it's better to check existing user logic.
to achieve that you can use a dictionary or array to temporary store your user in a loop and check if the current user was exists
. . .
user_tmp = []
for user in root.findall('user'):
login = user.find('login').text
# Check if login is in the list
if login not in user_tmp:
user_tmp.append(login)
else:
# if login is in the list, continue the loop
continue
. . .
since you are using the Pandas data frame, you can generate multiple sheets when saving the data frame with toExcel
# Example, you generate an active user in df_active and inactive user in # create a excel writer object
with pd.ExcelWriter("path to file\filename.xlsx") as writer:
# use to_excel function and specify the sheet_name and index
# to store the dataframe in specified sheet
df_active.to_excel(writer, sheet_name="Active", index=False)
df_inactive.to_excel(writer, sheet_name="Inactive", index=False)
I hope you can get hints to solve your issues from my suggestions.

Read Outlook Shared Calendars via Python

Using Python, how do you read Outlook's Shared Calendar events, and hopefully, also using a time filter?
Here is a relevant post, but to answer this fully:
import win32com.client # for outlook
import datetime
"""This code reads shared calendars."""
# set variables
days = 3
begin = datetime.date.today()
end = begin + datetime.timedelta(days=days)
events = [] # to write results from calendar loop
# begin importing calendar
Outlook = win32com.client.Dispatch("Outlook.Application")
ns = Outlook.GetNamespace("MAPI")
# turn this into a list to read more calendars
recipient = ns.CreateRecipient("username") # cmd whoami to find this
resolved = recipient.Resolve() # checks for username in address book
# olFolderCalendar = 9
# appointments = ns.GetDefaultFolder(9).Items # for personal calendar
appointments = ns.GetSharedDefaultFolder(recipient, 9).Items
# filtering criteria
# https://learn.microsoft.com/en-us/office/vba/api/outlook.items.includerecurrences
appointments.Sort("[Start]") # suspect problem
appointments.IncludeRecurrences = "True"
restriction = "[Start] >= '" + begin.strftime("%m/%d/%Y") \
+ "' AND [End] <= '" + end.strftime("%m/%d/%Y") + "'"
# list of appointments
restrictedItems = appointments.Restrict(restriction)
# loop through all calendar events, and add elements to list
count = 0
for app in restrictedItems:
count += 1 # no len(range(restrictedItems)) allowed
# display values
print()
print("item: " + str(count))
print("start: \t\t" + str(app.Start))
print("subject: \t" + app.Subject)
print("end: \t\t" + str(app.End))
print("recurring: \t" + str(app.IsRecurring))
print("status: \t" + str(app.MeetingStatus))
# collect values
app_instance = [app.Subject,
app.Start,
app.End,
app.BusyStatus]
events.append(app_instance)

Dynamically build dictionary from columns specified at runtime

I have been told I need to use a mapping table instead of a hardcoded dictionary I made. There has to be a better method than the code below to get a 3 column table into a dictionary?
Mapping table
AgentGrp, Property, TimeZone #Headers
HollyWoodAgent Sunset PST
UnionSquareAgent UnionSquare PST
Turns into the following dictionary:
{'HollyWoodAgent': ['Sunset', 'PST'], 'UnionSquareAgent': ['UnionSquare', 'PST']}
Code:
import pandas as pd
import pyodbc
import datetime
import sys
import csv
VipAgent = "{"
finalSql = "SELECT agentgrp, property, timezone FROM sandbox_dev.agentgrp_map;"
colcnt = 0
try:
conn = pyodbc.connect("DSN=Dev")
cursor = conn.cursor()
cursor.execute(finalSql)
for row in cursor.fetchall():
VipAgent += "'" + row.prop + "VipAgent':['" + row.prop + "','" + row.tz + "'],"
colcnt = colcnt + 1
if(colcnt==3):
VipAgent = VipAgent + "\n"
colcnt = 0
except my.Error as e:
print(e)
VipAgent = VipAgent[:-1] + "}"
Dict = eval(VipAgent)
print(Dict)
I do get the values as expected. There has to be a better python way out there.
We'll take it as given that you read the "mapping table" from a file into a Python list similar to this one
item_map = ['AgentGrp', 'Property', 'TimeZone']
Once you've executed your SELECT query
cursor.execute(finalSql)
then you can build your dict like so:
result_dict = {}
while (True):
row = cursor.fetchone()
if (row):
result_dict[row.__getattribute__(item_map[0])] = \
[row.__getattribute__(x) for x in item_map[1:]]
else:
break
print(result_dict)
# {'HollyWoodAgent': ['Sunset', 'PST'], 'UnionSquareAgent': ['UnionSquare', 'PST']}
The trick is to use row.__getattribute__, e.g., row.__getattribute__('column_name') instead of hard-coding row.column_name.

I keep getting list out of range trying to convert mysqldatabase into html

I dont get why it keeps giving me the list out of range error for sys.argv[1]. From my understanding I am passing data to user_database. Help please
import sys, MySQLdb
def PrintFields(database, table):
host = 'localhost'
user = 'root'
password = 'boysnblue1'
conn = MySQLdb.Connection(db=parking_report, host=localhost, user=root, passwd=boysnblue1)
mysql = conn.cursor()
sql = """ SHOW COLUMNS FROM %s """ % table
mysql.execute("select id, date, time, status, from report_table ")
fields=mysql.fetchall()
print '<table border="0"><tr><th>order</th><th>name</th><th>type</th><th>description</th></tr>'
print '<tbody>'
counter = 0
for field in fields:
counter = counter + 1
id = field[0]
date = field[1]
time = field[2]
status = field[3]
print '<tr><td>' + str(counter) + '</td><td>' + id + '</td><td>' + date + '</td><td>' + time + '</td><td>' + status + ' </td></tr>'
print '</tbody>'
print '</table>'
mysql.close()
conn.close()
users_database = sys.argv[1]
users_table = sys.argv[2]
print "Wikified HTML for " + users_database + "." + users_table
print "========================"
PrintFields(users_database, users_table)
sys.argv is a list containing the name of the program's file and all of the arguments it was passed on the command line.
If you run python script2.py, the contents of sys.argv will be ['script2.py'].
If you run python script2.py database_name table_name, the contents of sys.argv will be ['script2.py', 'database_name', 'table_name'], which is what your program is currently configured to expect:
users_database = sys.argv[1]
users_table = sys.argv[2]
Since you are calling it the first way, sys.argv[1] does not exist, and you get your error that the index (1) is out of range (it only goes to 0).

Python - update database

How would I update an entry that is already in a database using sqlite3?
I've tried:
db_curs.execute("INSERT INTO `database` (cID) VALUES ('Updated')")
But this, of course, creates a new entry. I can obtain the (line(?)) number (of the entry) and what is the command to update the database rather than create a new entry?
EDIT:
Put a bit better, when I convert the SQL entry to a python list I get the following,
(1, u'GGS-04', u'John', u'Smith', 9, u'0')
I need to be able to add a digit to the last item. Here is what I have.
info = (1, u'GGS-04', u'John', u'Smith', 9, u'0')
for result in info:
ln = str(result[0])
ggs = str(result[1])
first_name = str(result[2])
last_name = str(result[3])
dob = str(result[4])
spend = str(result[5])
while True:
res = raw_input("Enter points to add: ")
try:
int(res)
break
except:
print "Please enter a number..."
pass
spend = str(int(spend) + int(res))
db_curs.execute("UPDATE `" + db_name + "` (cID, first_name, last_name, date_of_birth, spend) VALUES ('" + srce + "', '" + first_name + "', '" + last_name + "', '" + dob + "' WHERE '" + spend + "')")
db_connection.commit()
Could someone please explain the correct syntax for this command? It would be awesome if I could just update the "Spend" column than having to update them all from prefixed variables.
Thank you :)
This shall work:
db_curs.execute("UPDATE database SET spend =`" + spend + "` WHERE cID="+ cID)
See also SQL Update Syntax
Btw, "database" isn't a useful name for a database's table. What about "users" or "spendtime" or sth more descriptive?

Categories

Resources