Hello everyone.

I am insisting on two python modules for windows event collection, I still 
don't have a satisfactory result

as the solution eventlog_0.py the win32evtlog module of the pypiwin32 library I 
can connect to the RPC service but only on a local PC,

have a readable parsing of the events and then forward it to the soc, I have to 
insist on remote login.

* learning about the topic and exchanging emails with the WIN32 API community, 
they wrote me about the possibility

to launch a script on a remote computer to authorize the share of the eventlog 
also on guest users, then

the strategy would be with WMI with admin connection, modification of the 
parameters useful for the log dump

and connection with win32 for parsing the event log.



As for the solution using the WMI, I encountered the reverse problem, 
connecting to the remote host

happens correctly (after entering the registrations), with an SQL query I log in

to Win32_NTLogEvent, but I don't know the schema of the db and I have not found 
snippet that readable results.



I had believed in the use of win32, theoretically and from what they tell me in 
the community it is necessary first

authenticate with the win32security.LogonUser () module and then invoke the RPC 
service, which I did but it didn't

results. The win32evtlog library apparently does not have a method for posting 
les

article when establishing the connection.


I spent less time on WMI because I found little fiction about managing the 
eventlog with python.






eventlog_0.py

#python C:\python\5_Forensic_Basic\eventlog.py

# Windows Event Log Viewer
# FB - 201012116
import win32evtlog # requires pywin32 pre-installed


server = 'localhost' # name of the target computer to get event logs


try:

    logtype = 'System' # 'Application' # 'Security'
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = 
win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)

    while True:
        print ("test")
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                print ('Event Category:', event.EventCategory)
                print ('Time Generated:', event.TimeGenerated)
                print ('Source Name:', event.SourceName)
                print ('Event ID:', event.EventID)
                print ('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print ('Event Data:')
                    for msg in data:
                        print (msg)
                print()

except Exception as err:
    print("Exception")

    print(str(err))

if __name__ == "__main__":
    try:
        print ("start")
    except getopt.GetoptError as err:
        print(str(err))


#ModuleNotFoundError: No module named 'win32evtlog'
#pip install pypiwin32

#Server RPC non disponibile.



login_eventlog.py
import getpass
import win32security

import win32evtlog # requires pywin32 pre-installed


domain = input("Domain: ")
username = input("Username: ")
password = getpass.getpass ("Password: ")


def simple_logon():
    try:
        hUser = win32security.LogonUser (
            username,
            domain,
            password,
            win32security.LOGON32_LOGON_NETWORK,
            win32security.LOGON32_PROVIDER_DEFAULT
        )
    except win32security.error:
        print ("Failed")
    else:

        print ("Succeeded")





if __name__ == "__main__":
    simple_logon()

    try:


    logtype = 'System' # 'Application' # 'Security'
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = 
win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    pdb.set_trace()

    while True:
        print ("test")
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                print ('Event Category:', event.EventCategory)
                print ('Time Generated:', event.TimeGenerated)
                print ('Source Name:', event.SourceName)
                print ('Event ID:', event.EventID)
                print ('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print ('Event Data:')
                    for msg in data:
                        print (msg)
                print()

except Exception as err:
    print("Exception")

    print(str(err))

    #print (logonUser("/\norazero\norazero"))


wmi_2
import wmi

ip = '192.168.1.10'
username =
password =
from socket import *
try:
    print("Establishing connection to %s" %ip)
    conn = wmi.WMI(ip, user=username, password=password)
    print("Connection established")
    print(conn)

    if False:
        print("list processes")
        # list processes
        for process in conn.Win32_Process():
            print("ID: {0}\nHandleCount: {1}\nProcessName: {2}\n".format(
            process.ProcessId, process.HandleCount, process.Name
            )
            )

    if False:
        for s in conn.Win32_Service(StartMode="Auto", State="Running"):
            print(s.State, s.StartMode, s.Name, s.DisplayName)

        # filter service names
            if 'Update' in s.Name:
                print(s.State, s.StartMode, s.Name, s.DisplayName)

    if False:
        wmi_obj = wmi.WMI('.') #Initialize WMI object and query.
        wmi_query = "SELECT * FROM Win32_NTLogEvent WHERE Logfile='System' AND 
EventType=1"
        query_result = wmi_obj.query(wmi_query) # Query WMI object
        print(query_result)

   #for group in conn.Win32_Group():
    for group in conn.Win32_Group():
        print(group.Caption)

        # loop
        #for user in group.associators(wmi_result_class="Win32_UserAccount"):
        #    print(" [+]", user.Caption)

except wmi.x_wmi:
    print("Your Username and Password of "+getfqdn(ip)+" are wrong.")






Ruggero Paolo Basile

Cellulare: 3403216393
Mail:  ruggeropaolo.bas...@ora-0.it<mailto:gabriele.salt...@ora-0.it>
Privacy Policy<https://ora-0.it/privacy-policy/>     Company 
Policy<https://ora-0.it/wp-content/uploads/2020/08/politica_aziendale_it.pdf>
[cid:image001.png@01D789E4.08355260]


________________________________
Da: python-win32 <python-win32-bounces+ruggeropaolo.basile=ora-0...@python.org> 
per conto di Ruggero Paolo Basile <ruggeropaolo.bas...@ora-0.it>
Inviato: giovedì 16 settembre 2021 15:51:37
A: Mark Hammond; python-win32@python.org
Oggetto: Re: [python-win32] pywintypes.error: (5, 'OpenEventLogW', 'Access is 
denied.')




OK well , i dint try the experiment becouse i wont modify the

other host, only i have to connect to a remote host in the local lan

but i cant find any parameter to connect to an host with  
win32security.LogonUser().


Gretings




Ruggero Paolo Basile

Cellulare: 3403216393
Mail:  ruggeropaolo.bas...@ora-0.it<mailto:gabriele.salt...@ora-0.it>
Privacy Policy<https://ora-0.it/privacy-policy/>     Company 
Policy<https://ora-0.it/wp-content/uploads/2020/08/politica_aziendale_it.pdf>
[cid:image001.png@01D789E4.08355260]


________________________________
Da: Mark Hammond <mhamm...@skippinet.com.au>
Inviato: giovedì 16 settembre 2021 11:30:34
A: Ruggero Paolo Basile; python-win32@python.org
Oggetto: Re: [python-win32] pywintypes.error: (5, 'OpenEventLogW', 'Access is 
denied.')

On 16/09/2021 7:17 pm, Ruggero Paolo Basile wrote:
> OK , let's explain the case
>
>
> My goal is to read the event log of the remote windows machine. I have
> experienced the *wmi library,* the wmi problem is that I have to create
> parsers, I have not found any code. On the remote machine I have no
> authentication problems as I connect to the local network.

If you have a username and password that works on the *server*, you may
be able to use win32security.LogonUser().

You still haven't answered:

> Tim also suggested a specific experiment you should try - did you try
> it? What happened?

It's likely you will be prompted for a username and password here. If
you have a username/password that works, win32security.LogonUser() is
likely to work with the same username/password.

Mark


import getpass
import win32security

import win32evtlog # requires pywin32 pre-installed


domain = input("Domain: ")
username = input("Username: ")
password = getpass.getpass ("Password: ")


def simple_logon():
    try:
        hUser = win32security.LogonUser (
            username,
            domain,
            password,
            win32security.LOGON32_LOGON_NETWORK,
            win32security.LOGON32_PROVIDER_DEFAULT
        )
    except win32security.error:
        print ("Failed")
    else:
        
        print ("Succeeded")
       

   
    

if __name__ == "__main__":
    simple_logon()
    
    try:

   
    logtype = 'System' # 'Application' # 'Security'
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)
    pdb.set_trace()
    
    while True:
        print ("test")
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                print ('Event Category:', event.EventCategory)
                print ('Time Generated:', event.TimeGenerated)
                print ('Source Name:', event.SourceName)
                print ('Event ID:', event.EventID)
                print ('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print ('Event Data:')
                    for msg in data:
                        print (msg)
                print()
    
except Exception as err:
    print("Exception")
    
    print(str(err))
    
    #print (logonUser("/\norazero\norazero"))


#python C:\python\5_Forensic_Basic\eventlog.py

# Windows Event Log Viewer
# FB - 201012116
import win32evtlog # requires pywin32 pre-installed


server = 'localhost' # name of the target computer to get event logs


try:

   
    logtype = 'System' # 'Application' # 'Security'
    hand = win32evtlog.OpenEventLog(server,logtype)
    flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
    total = win32evtlog.GetNumberOfEventLogRecords(hand)

    while True:
        print ("test")
        events = win32evtlog.ReadEventLog(hand, flags,0)
        if events:
            for event in events:
                print ('Event Category:', event.EventCategory)
                print ('Time Generated:', event.TimeGenerated)
                print ('Source Name:', event.SourceName)
                print ('Event ID:', event.EventID)
                print ('Event Type:', event.EventType)
                data = event.StringInserts
                if data:
                    print ('Event Data:')
                    for msg in data:
                        print (msg)
                print()
    
except Exception as err:
    print("Exception")
    
    print(str(err))
    
if __name__ == "__main__":
    try:
        print ("start")
    except getopt.GetoptError as err:
        print(str(err))


#ModuleNotFoundError: No module named 'win32evtlog'
#pip install pypiwin32

#Server RPC non disponibile.
import wmi

ip = '192.168.1.10'
username = 
password = 
from socket import *
try:
    print("Establishing connection to %s" %ip)
    conn = wmi.WMI(ip, user=username, password=password)
    print("Connection established")
    print(conn)
    
    if False:        
        print("list processes")
        # list processes
        for process in conn.Win32_Process():
            print("ID: {0}\nHandleCount: {1}\nProcessName: {2}\n".format(
            process.ProcessId, process.HandleCount, process.Name
            )
            )
    
    if False:      
        for s in conn.Win32_Service(StartMode="Auto", State="Running"):
            print(s.State, s.StartMode, s.Name, s.DisplayName)
        
        # filter service names
            if 'Update' in s.Name:
                print(s.State, s.StartMode, s.Name, s.DisplayName)
        
    if False:
        wmi_obj = wmi.WMI('.') #Initialize WMI object and query.
        wmi_query = "SELECT * FROM Win32_NTLogEvent WHERE Logfile='System' AND EventType=1"
        query_result = wmi_obj.query(wmi_query) # Query WMI object
        print(query_result)
   
   #for group in conn.Win32_Group():
    for group in conn.Win32_Group():
        print(group.Caption)
        
        # loop
        #for user in group.associators(wmi_result_class="Win32_UserAccount"):
        #    print(" [+]", user.Caption)

except wmi.x_wmi:
    print("Your Username and Password of "+getfqdn(ip)+" are wrong.")
_______________________________________________
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32

Reply via email to