Reading UserID and IP mapping with python on Active Directory

193 views Asked by At

I have a project and I try to find correct algoritm and method for that.

I have a file called ADUserIPmap.txt which is located one of the Active Directory's path.

This file includes lines like this:

172.16.205.5 domain\administrator 1482857637 Tue Dec 27 19:53:57 2016

172.16.200.237 domain\admin 1482857408 Tue Dec 27 19:50:08 2016

172.16.200.254 domain\cppm 1482857802 Tue Dec 27 19:56:42 2016

172.16.200.200 domain\admin 1482857830 Tue Dec 27 19:57:10 2016

I have to replace third column (1482857637) with givenName of that user. And this givenName data comes from a powershell command output like this.

C:\Users\Administrator> Get -ADuser -Identity 1482857637
GivenName: nthere
SamAccountName: 1482857637

Python script will work on Active Directory and powershell command as well.

After all of these steps done, I will send these informations to a firewall with xml api.

Question 1) ADUserIPmap.txt is a log file and lines will increase constantly. I don't want to read all file again and again. What is the correct method for this case?

2) Are there any simple way to get GivenName field from Active Directory

Thanks

1

There are 1 answers

0
wwii On

Q1) After reading the file the first time, assign the current position to a variable. Then jump there before iterating.

with open('foo.txt') as f:
    z = f.seek(last_read)
    for line in f:
        print(line)
    last_read = f.tell()

If you need to persist last_read, use pickle

import pickle
# retrieve before processing
with open('last_read.pkl') as f:
    last_read = pickle.load(f)

#process
with open('foo.txt') as f:
    z = f.seek(last_read)
    for line in f:
        print(line)
    last_read = f.tell()


# save after processing
with open('last_read.pkl', 'wb') as f:
    pickle.dump(last_read, f)

If you want to persist multiple things, put them in a dictionary and pickle the dictionary.


Q2) Looks like there are a few active directory libraries in PyPi