Issue with calculating password age date in Python - python

I'm rebuilding my PowerShell script with Python.
Sole purpose of that is to easily insert data to Postgre DB tables with Python.
PowerShell script works as it should, but when it comes to Python I encountered a obstacle.
In this loop, I gather all data - most like direct reports from specific AD account. As you may see, I already gather account name, name/surname, e-mail address and password last set date.
The problem is to calculate password age. In PS it was pretty easy, but when I ran a code in Python, I get an Exception has occurred: TypeError can't subtract offset-naive and offset-aware datetimes
Here is the part of the code:
reports = getDirectReports(managers_name)
for users in reports:
for user in users.directReports.values:
if 'cn=ext.' in user.lower():
user_details = getUserDetails(user)
print(user_details[0].cn.value)
print(user_details[0].givenName.value)
print(user_details[0].sn.value)
print(user_details[0].pwdLastSet.value)
print(user_details[0].mail.value)
current_date = datetime.now()
start_date = user_details[0].pwdLastSet.value
if (start_date == 0):
password_age = 'NULL'
else:
password_age = current_date - start_date ```

Related

Getting the name of a folder using Exchangelib

I have looked at:
How to get the parent folder name of Message with Exchangelib python
But have been unable to make this work using the following debugging code:
for item in docdead.all().order_by('-datetime_received')[:3000]: #look into the inbox the first 3K emails order desc by date received
if item.datetime_received < ews_bfr: #if the mail if older than the custom date in the EWS format then apply rule
print (item.subject)
print (item.datetime_received)
print (item.sender.email_address)
print (item.sender.name)
print (item.body)
print(SingleFolderQuerySet(
account=account,
folder=account.root
).get(id=item.parent_folder_id.id))
for attachment in item.attachments:
print (attachment.name)
I get:
ValueError: EWS does not support filtering on field 'id'
I am sure its a simple error, but I would appreciate any help.
If you're just querying one folder, then parent_folder_id will always point to that folder.
If you're querying multiple folders at a time, here's the general way to look up a folder name by ID:
from exchangelib.folders import FolderId, SingleFolderQuerySet
folder_name = SingleFolderQuerySet(
account=account,
folder=FolderId(id=item.parent_folder_id.id),
).resolve().name

Python & InfluxDB: get most recent measurement

First, some context about my application:
Databases were created on InfluxDB (in my VM)
I am already writing in a measurement
The script runs at a frequency of once per minute
I need to write a Python script to read the database. I want to fetch only the most recent measurement value, not all values.
Here is my code:
from influxdb import InfluxDBClient
client = InfluxDBClient(database='test')
client = InfluxDBClient()
rs = cli.query("SELECT * from CoreTemperature")
CoreTemperature = list(rs.get_points(measurement='CoreTemperature'))
print(CoreTemperature)
I am stuck because of:
The output of this code is: **NameError: name 'cli' is not defined**
Filtering by measurement and select * from CoreTemperature will read all points saved for the measurement, but I only want the most recent value.
The first error : NameError: name 'cli' is not defined is because you defined the influxdb client as client, and in the query you are calling it as cli
rs = client.query("SELECT * from CoreTemperature")
this will resolve this error.
The second error will be solved by:
client.query('SELECT last(<field_name>), time FROM CoreTemperature ')
It sounds like you want the most recent measurement value written to CoreTemperature. You can get that using the LAST selector:
LAST()
Returns the field value with the most recent timestamp.
Like this:
SELECT LAST(*) FROM CoreTemperature
Good morning everyone
I reach the target with the following code:
>from influxdb import InfluxDBClient
>dbClient = InfluxDBClient()
>loginRecords = dbClient.query('select last(*) from CoreTemperature',
database='test')
>print(loginRecords)
Thanks for all comments and help me!

Adding expire functionality to python-rom objects

I am working with flask and redis. I've using the rom redis orm (http://pythonhosted.org/rom/) to manage some mildly complex data structures. I want to add the ability to set the objects to set an expiry time.
Based on https://github.com/josiahcarlson/rom/issues/40 and https://github.com/josiahcarlson/rom/pull/47
I have a rom model:
class A(rom.Model):
url = rom.String(required=True, unique=True)()
t = rom.String()
delete_at = rom.Float(index=True)
created_at = rom.Float(default=time.time, index=True)
which I can instantiate and save:
a_object = A(url=u, delete_at =time.time+7200) # 2 hour expiry
try:
ad_object.save()
except Exception,e:
print str(e)
I have a cronjob which executes every hour and so I want to do something like:
delete_list = A.get_by((time.time()-delete_at>0)) # pseudocode.
Obviously this is incorrect, but if I can get this into a list I could delete these. How can I express the above pseudocode using the rom ORM?
I emailed Josiah, the package developer. His answer:
"This can be done in one of 2 ways:
delete_list = A.get_by(delete_at=(0, time.time()))
delete_list = A.query.filter(delete_at=(0, time.time())).all()
The query attribute/object offers a collection of different filers, depending on your defined indexes."

Issue about Python imaplib library on method append

I'm trying to write an imapsync software that connects on host 1 to account1#host1.com and copy messages and folder to account2#host2.com host2.
Supposing I've already fetched the selected message with his UID with:
msg = connection.fetch(idOne, '(RFC822)'))
and msg is a good message, below you have the code I've tried to append the message:
date = connection.fetch(idOne, '(INTERNALDATE)')[1][0]
date = date.split("\"")[1]
authconnection1.append(folder, "", date, msg)
Error is:
ValueError: date_time not of a known type
I've tried many other possible solutions (with dateutil to convert date string to datetime object, using imaplib.Time2Internaldate I got the same error above ValueError: date_time not of a known type), but no one seems to work. I've searched around the network but nobody seems to have this issue.
Any idea? I'm getting very frustrated of it...
Thank you very much
Update:
I've resolved the date_time issue, because the "append" method of imaplib wants that date_time is an integer of seconds, so to retrieve the date I've written this code:
# Fetch message from host1
msg = connection.fetch(idOne, '(RFC822)')
# retrieve this message internal date
date = connection.fetch(idOne, '(INTERNALDATE)')[1][0].split("\"")[1]
# Cast str date to datetime object
date = parser.parse(date)
# Removes tzinfo
date = date.replace(tzinfo=None)
# Calculates total seconds between today and the message internal date
date = (datetime.datetime.now()-date).total_seconds()
# Makes the append of the message
authconnection1.append(folder, "", date, msg)
But now this fails with error:
TypeError: expected string or buffer
So the issue is only changed...
Any ideas?
Update (RESOLVED):
imaplib is not working fine, so I've made a workaround for append messages with right date/time. This is my code, I hope it will help everybody:
Function to convert date in right format:
def convertDate(date):
from time import struct_time
import datetime
from dateutil import parser
date = parser.parse(date)
date = date.timetuple()
return date
Main code:
#Get message
msg = authconnection.fetch(idOne, '(RFC822)')
#Get message date
date = authconnection.fetch(idOne, '(INTERNALDATE)')[1][0].split("\"")[1]
#Apply my function I've written above
date = convertDate(date)
#Append message with right date
authconnection1.append(folder, flags, date, msg[1][0][1])

Get the top followed followers of a user in twitter using python-twitter

I want to get the top followed followers of a user in twitter using python-twitter. And that without getting the 'Rate limit exceeded' error message.
I can get followers of a user then get the number of folowers of each one, but the problem is when that user is big (thousands).
I use the following function to get the followers ids of a particular user:
def GetFollowerIDs(self, userid=None, cursor=-1):
url = 'http://twitter.com/followers/ids.json'
parameters = {}
parameters['cursor'] = cursor
if userid:
parameters['user_id'] = userid
json = self._FetchUrl(url, parameters=parameters)
data = simplejson.loads(json)
self._CheckForTwitterError(data)
return data
and my code is:
import twitter
api = twitter.Api(consumer_key='XXXX',
consumer_secret='XXXXX',
access_token_key='XXXXX',
access_token_secret='XXXXXX')
user=api.GetUser(screen_name="XXXXXX")
users=api.GetFollowerIDs(user)
#then i make a request per follower in users so that I can sort them according to the number of followers.
the problem is that when the user has a lot of followers i get the 'Rate limit exceeded' error message.
I think you need to get the results in chunks as explained in this link.
This is the work around currently shown on the github page. But if you would want an unlimited stream, you should upgrade the subscription for your twitter application.
def GetFollowerIDs(self, userid=None, cursor=-1, count = 10):
url = 'http://twitter.com/followers/ids.json'
parameters = {}
parameters['cursor'] = cursor
if userid:
parameters['user_id'] = userid
remaining = count
while remaining > 1:
remaining -= 1
json = self._FetchUrl(url, parameters=parameters)
try:
data = simplejson.loads(json)
self._CheckForTwitterError(data)
except twitterError:
break
return data
def main():
api = twitter.Api(consumer_key='XXXX',
consumer_secret='XXXXX',
access_token_key='XXXXX',
access_token_secret='XXXXXX')
user=api.GetUser(screen_name="XXXXXX")
count = 100 # you can find optimum value by trial & error
while(#users not empty):
users=api.GetFollowerIDs(user,count)
Or another possibility might be to try running Cron jobs in intervals as explained here.
http://knightlab.northwestern.edu/2014/03/15/a-beginners-guide-to-collecting-twitter-data-and-a-bit-of-web-scraping/
Construct your scripts in a way that cycles through your API keys to stay within the rate limit.
Cronjobs — A time based job scheduler that lets you run scripts at designated times or intervals (e.g. always at 12:01 a.m. or every 15 minutes).

Categories

Resources