I am trying to read event logs from Applications and Services log using python. However the output are not as expected. (Actual 10 vs output 838)
I am using the following code. Was wondering if there is a mistake with the parameters.
import win32evtlog
server = 'localhost'
logtype = "Microsoft-Windows-Storage-Storport/Operational"
hand = win32evtlog.OpenEventLog(server, logtype)
flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
while True:
events = win32evtlog.ReadEventLog(hand, flags,0)
if events:
for event in events:
print ('Source Name:', event.SourceName)
print ('Event ID:', event.EventID)
print ('Time Generated:', event.TimeGenerated)
Found a method to get the information through the use of powershell using python.
import subprocess
getinfo = subprocess.check_output(
['powershell.exe', 'get-Winevent Microsoft-Windows-xxx/Operational'])
where xxx is a variable
Related
I have consulted several topics on the subject, but I didn't see any related to launching an app on a device directly using a ppadb command.
I managed to do this code:
import ppadb
import subprocess
from ppadb.client import Client as AdbClient
# Create the connect functiun
def connect():
client = AdbClient(host='localhost', port=5037)
devices = client.devices()
for device in devices:
print (device.serial)
if len(devices) == 0:
print('no device connected')
quit()
phone = devices[0]
print (f'connected to {phone.serial}')
return phone, client
if __name__ == '__main__':
phone, client = connect()
import time
time.sleep(5)
# How to print each app on the emulator
list = phone.list_packages()
for truc in list:
print(truc)
# Launch the desired app through phone.shell using the package name
phone.shell(????????????????)
From there, I have access to each app package (com.package.name). I would like to launch it through a phone.shell() command but I can't access the correct syntax.
I can execute a tap or a keyevent and it's perfectly working, but I want to be sure my code won't be disturbed by any change in position.
From How to start an application using Android ADB tools, the shell command to launch an app is
am start -n com.package.name/com.package.name.ActivityName
Hence you would call
phone.shell("am start -n com.package.name/com.package.name.ActivityName")
A given package may have multiple activities. To find out what they are, you can use dumpsys package as follows:
def parse_activities(package, connection, retval):
out = ""
while True:
data = connection.read(1024)
if not data: break
out += data.decode('utf-8')
retval.clear()
retval += [l.split()[-1] for l in out.splitlines() if package in l and "Activity" in l]
connection.close()
activities = []
phone.shell("dumpsys package", handler=lambda c: parse_activities("com.package.name", c, activities))
print(activities)
Here is the correct and easiest answer:
phone.shell('monkey -p com.package.name 1')
This method will launch the app without needing to have acces to the ActivityName
Using AndroidViewClient/cluebra, you can launch the MAIN Activity of a package as follows:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from com.dtmilano.android.viewclient import ViewClient
ViewClient.connectToDeviceOrExit()[0].startActivity(package='com.example.package')
This connects to the device (waiting if necessary) and then invokes startActivity() just using the package name.
startActivity() can also receive a component which is used when you know the package and the activity.
I'm studying vCenter 6.5 and community samples help a lot, but in this particular situation I can't figure out, what's going on. The script:
from __future__ import with_statement
import atexit
from tools import cli
from pyVim import connect
from pyVmomi import vim, vmodl
def get_args():
*Boring args parsing works*
return args
def main():
args = get_args()
try:
service_instance = connect.SmartConnectNoSSL(host=args.host,
user=args.user,
pwd=args.password,
port=int(args.port))
atexit.register(connect.Disconnect, service_instance)
content = service_instance.RetrieveContent()
vm = content.searchIndex.FindByUuid(None, args.vm_uuid, True)
creds = vim.vm.guest.NamePasswordAuthentication(
username=args.vm_user, password=args.vm_pwd
)
try:
pm = content.guestOperationsManager.processManager
ps = vim.vm.guest.ProcessManager.ProgramSpec(
programPath=args.path_to_program,
arguments=args.program_arguments
)
res = pm.StartProgramInGuest(vm, creds, ps)
if res > 0:
print "Program executed, PID is %d" % res
except IOError, e:
print e
except vmodl.MethodFault as error:
print "Caught vmodl fault : " + error.msg
return -1
return 0
# Start program
if __name__ == "__main__":
main()
When I execute it in console, it successfully connects to the target virtual machine and prints
Program executed, PID is 2036
In task manager I see process with mentioned PID, it was created by the correct user, but there is no GUI of the process (calc.exe). RMB click does not allow to "Expand" the process.
I suppose, that this process was created with special parameters, maybe in different session.
In addition, I tried to run batch file to check if it actually executes, but the answer is no, batch file does not execute.
Any help, advices, clues would be awesome.
P.S. I tried other scripts and successfully transferred a file to the VM.
P.P.S. Sorry for my English.
Update: All such processes start in session 0.
Have you tried interactiveSession ?
https://github.com/vmware/pyvmomi/blob/master/docs/vim/vm/guest/GuestAuthentication.rst
This boolean argument passed to NamePasswordAuthentication and means the following:
This is set to true if the client wants an interactive session in the guest.
Ansible-playbook has a --list-hosts cli switch that just outputs the hosts affected by each play in a playbook. I am looking for a way to access to same information through the python API.
The (very) basic script I am using to test right now is
#!/usr/bin/python
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json
# hosts list
hosts = ["127.0.0.1"]
# set up the inventory, if no group is defined then 'all' group is used by default
example_inventory = ansible.inventory.Inventory(hosts)
pm = ansible.runner.Runner(
module_name = 'command',
module_args = 'uname -a',
timeout = 5,
inventory = example_inventory,
subset = 'all' # name of the hosts group
)
out = pm.run()
print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))
I just can't figure out what to add to ansible.runner.Runner() to make it output affected hosts and exit.
I'm not sure what are you trying to achieve, but ansible.runner.Runner is actually one task and not playbook.
Your script is a more kind of ansible CLI and not ansible-playbook.
And ansible doesn't have any kind of --list-hosts, while ansible-playbook does.
You can see how listhosts is done here.
I have automated the creation of a PowerPoint slide-deck via Python and have set-up a trigger in Task Scheduler for a daily report to be generated.
This is all fine while my computer is logged in, but the script fails when the setting: "Run whether is logged in or not".
I checked to see what line was at fault and it turns out it is this one:
Presentation.SaveAs('C:\\Users\\me\\Desktop\\test.pptx')
I am running Task Scheduler with highest priority but it only runs this task with the "User is logged in" state.
Below is the entire basic code segment for reference:
import win32com.client, MSO, MSPPT, sys, os
g = globals()
for c in dir(MSO.constants): g[c] = getattr(MSO.constants, c)
for c in dir(MSPPT.constants): g[c] = getattr(MSPPT.constants, c)
error_file = open('C:\\Users\\me\\Desktop\\error_file.txt', 'wb')
run = False
try:
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
Presentation = Application.Presentations.Add()
Slide = Presentation.Slides.Add(1, ppLayoutBlank)
Presentation.SaveAs('C:\\Users\\me\\Desktop\\test.pptx')
Presentation.Close()
Application.Quit()
run = True
except:
run = False
if run == True:
error_file.write('ok')
else:
error_file.write('fail')
Any help on this would be much appreciated.
Thanks,
JP
How can I print the IP or hostname of the client pc who delete a file in my shared folder?This code is working but it only print my own IP and Hostname not the other pc that delete a file inside my shared folder.
Im using Centos 6.3.I use Samba to share my folder.I use Python 2.7 and PYinotify script.
This is my code
import pyinotify
wm = pyinotify.WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
print "",now.strftime("%b-%d-%Y # %I:%M %p")," " ,socket.gethostname()," ","Create "," ",event.name," ",event.path
def process_IN_DELETE(self, event):
print "",now.strftime("%b-%d-%Y # %I:%M %p")," " ,socket.gethostname()," ","Shift+Del","",event.name," ",event.path
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch('/echoshare', mask, rec=True)
auto_add = '/echoshare'
notifier.loop()
I think you misunderstand what (py)inotify is.
It is a way to monitor filesystem events and you will get information about operations done by samba server on local filesystem.
If you take a look on inotify documentation you will notice that inotify_event structure does not carry any information about user performing the operations.
I guess a simplest solution to you problem would be to enable event logging on your samba server and parse generated events for information you want