My needs check windows process number.
import sys
import os
import commands
ip = sys.argv[5]
val = sys.argv[1]
oid = "HOST-RESOURCES-MIB::hrSWRunName"
cmd = "snmpwalk -v 2c -c public %s %s" % (ip,oid)
(r_c,r_e) = commands.getstatusoutput(cmd)
if r_c != 0:
print "C - snmpwalk is Error."
else:
for i in r_e.split('\n'):
a = i.split(':')[-1].strip(' "')
print a
Result:
conhost.exe
conhost.exe
conhost.exe
conhost.exe
fdhost.exe
cmd.exe
fdhost.exe
I hope the result is. I do not know how to achieve it.
if sys.argv[1] <5:#count(conhost.exe)
print "critical -"
else:
print "OK - "
How the statistics of my results? conhost.exe 4 conhost.exe 1 conhost.exe 1
# replace here
else:
processes = r_e.split('\n')
programs = 0
for program in processes:
programFile = program.split(':')[-1].strip(' "')
# the first argument you pass to the program should be conhost.exe
if programFile == sys.argv[1]:
programs = programs + 1
if programs < 5 :#count(conhost.exe)
print "critical: running less than 5 times:", sys.argv[1]
else:
print "OK"
second version
# replace here
else:
processes = r_e.split('\n')
processes = map(lambda program: program.split(':')[-1].strip(' "'), processes)
if processes.count(sys.argv[1]) < 5 :#count(conhost.exe)
print "critical: running less than 5 times:", sys.argv[1]
else:
print "OK"
Related
The following script (which should take the output from p1 and pipe it to p2, and then output the result in the terminal) doesn't seem to work as expected.
Code as follows :
#!/binr/bin/python
# Script to lauch mosquitto_sub to monitor a mqtt topic -- SYNTAX : mosk topic
import sys
import subprocess
total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
# Pharsing args one by one
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[1]))
path = str(sys.argv[1])
print (path)
p1 = subprocess.Popen(['mosquitto_sub','-h','192.168.1.100','-t',path,'-v'], shell=False, stdout=subprocess.PIPE)
p2 = subprocess.Popen(['ts'], stdin=p1.stdout, shell=False, stdout=subprocess.PIPE)
for line in p2.stdout:
sys.stdout.write(line)
with an input as follows "./mosk2.py test/+" and whilst publishing MQTT via mosquitto on the relevant topics, I never get the expected output in the terminal
Solved - I ended up stepping neatly around the problem (cheating) as follows :
cmd = "mosquitto_sub -h 192.168.1.100 -v -t " + topic + " | ts"
print "The command which was executed is : " , cmd
def run_command(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print output.strip()
rc = process.poll()
return rc
run_command(cmd) #This is the lauch of the actual command
I have a short python script, which is reading memory of other process. When I am going through the maps, I can see that some pieces of the memory don't give me read/write permissions. That is true even when I run the script with sudo. Is there any way to get these permissions? I am using newest Ubuntu and code in python3. The code I use is shown below.
import re
import sys
def search(number,chunk):
for bit in chunk:
if bit == number:
print("Hit!: " + str(number))
def search16bits(number, chunk):
length = len(chunk)/8
#print("Length: " + str(length))
num = int(length/2)
#print(chunk[int(num/8)-1])
#for i in range(num):
#print(i)
for i in range(num - 1):
start = num
second = start + 1
result = chunk[second] + 256 * chunk[start]
#print(result)
if number == result:
print("Hit!: " + str(number))
exit()
def print_memory_of_pid(pid, only_writable=True):
"""
Run as root, take an integer PID and return the contents of memory to STDOUT
"""
memory_permissions = 'rw' if only_writable else 'r-'
sys.stderr.write("PID = %d" % pid)
with open("/proc/%d/maps" % pid, 'r') as maps_file:
with open("/proc/%d/mem" % pid, 'rb') as mem_file:
for line in maps_file.readlines(): # for each mapped region
m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r][-w])', line)
#print("m:" + str(m))
if m.group(3) == memory_permissions:
#sys.stderr.write("\nOK : \n" + line+"\n")
start = int(m.group(1), 16)
if start > 0xFFFFFFFFFFFF:
continue
end = int(m.group(2), 16)
sys.stderr.write( "start = " + str(start) + "\n")
mem_file.seek(start) # seek to region start
chunk = mem_file.read(end - start) # read region contents
#print()
#print()
print("###########################Next Chunk:######################################")
#search16bits(221, chunk)
#print(len(chunk))
#print(chunk) # dump contents to standard output
else:
print("No permission")
#sys.stderr.write("\nPASS : \n" + line+"\n")
if __name__ == '__main__': # Execute this code when run from the commandline.
try:
assert len(sys.argv) == 2, "Provide exactly 1 PID (process ID)"
pid = int(sys.argv[1])
print_memory_of_pid(pid)
except (AssertionError, ValueError) as e:
print("Please provide 1 PID as a commandline argument.")
print("You entered: %s" + str(sys.argv))
raise e
The following script is an extract from
https://github.com/RittmanMead/obi-metrics-agent/blob/master/obi-metrics-agent.py
The script is written in jython & it hits the weblogic admin console to extract metrics
The problem is it runs only once and does not loop infinitely
Here's the script that I've extracted from the original for my purpose:
import calendar, time
import sys
import getopt
print '---------------------------------------'
# Check the arguments to this script are as expected.
# argv[0] is script name.
argLen = len(sys.argv)
if argLen -1 < 2:
print "ERROR: got ", argLen -1, " args, must be at least two."
print '$FMW_HOME/oracle_common/common/bin/wlst.sh obi-metrics-agent.py <AdminUserName> <AdminPassword> [<AdminServer_t3_url>] [<Carbon|InfluxDB>] [<target host>] [<target port>] [targetDB influx db>'
exit()
outputFormat='CSV'
url='t3://localhost:7001'
targetHost='localhost'
targetDB='obi'
targetPort='8086'
try:
wls_user = sys.argv[1]
wls_pw = sys.argv[2]
url = sys.argv[3]
outputFormat=sys.argv[4]
targetHost=sys.argv[5]
targetPort=sys.argv[6]
targetDB=sys.argv[7]
except:
print ''
print wls_user, wls_pw,url, outputFormat,targetHost,targetPort,targetDB
now_epoch = calendar.timegm(time.gmtime())*1000
if outputFormat=='InfluxDB':
import httplib
influx_msgs=''
connect(wls_user,wls_pw,url)
results = displayMetricTables('Oracle_BI*','dms_cProcessInfo')
while True:
for table in results:
tableName = table.get('Table')
rows = table.get('Rows')
rowCollection = rows.values()
iter = rowCollection.iterator()
while iter.hasNext():
row = iter.next()
rowType = row.getCompositeType()
keys = rowType.keySet()
keyIter = keys.iterator()
inst_name= row.get('Name').replace(' ','-')
try:
server= row.get('Servername').replace(' ','-').replace('/','_')
except:
try:
server= row.get('ServerName').replace(' ','-').replace('/','_')
except:
server='unknown'
try:
host= row.get('Host').replace(' ','-')
except:
host=''
while keyIter.hasNext():
columnName = keyIter.next()
value = row.get(columnName )
if columnName.find('.value')>0:
metric_name=columnName.replace('.value','')
if value is not None:
if outputFormat=='InfluxDB':
influx_msg= ('%s,server=%s,host=%s,metric_group=%s,metric_instance=%s value=%s %s') % (metric_name,server,host,tableName,inst_name, value,now_epoch*1000000)
influx_msgs+='\n%s' % influx_msg
conn = httplib.HTTPConnection('%s:%s' % (targetHost,targetPort))
## TODO pretty sure should be urlencoding this ...
a=conn.request("POST", ("/write?db=%s" % targetDB), influx_msg)
r=conn.getresponse()
if r.status != 204:
print 'Failed to send to InfluxDB! Error %s Reason %s' % (r.status,r.reason)
print influx_msg
#sys.exit(2)
else:
print 'Skipping None value %s,server=%s,host=%s,metric_group=%s,metric_instance=%s value=%s %s' % (metric_name,server,host,tableName,inst_name, value,now_epoch*1000000)
I've tried to use the While loop, but that just stopped the code from exiting and not re-looping
What I want to achieve is to loop it infinitely post connection to weblogic
i.e. after this line
connect(wls_user,wls_pw,url)
and perhaps sleep for 5 seconds before re-running
Any and all help will be appreciated
Thanks
P
You can use this kind of condition for the loop :
mainLoop = 'true'
while mainLoop == 'true' :
and this for the pause between iterations :
java.lang.Thread.sleep(3 * 1000)
I would like to read Windows' event log. I am not sure if it's the best way but I would like to use the pywin32 -> win32evtlog module to do so. First and foremost is it possible to read logs from Windows 7 using this library and if so how to read events associated with applications runs (running an .exe must leave a trace in the event log in windows i guess).
I have managed to find some little example on the net but it's not enough for me and the documentation isn't well written unfortunately ;/
import win32evtlog
hand = win32evtlog.OpenEventLog(None,"Microsoft-Windows-TaskScheduler/Operational")
print win32evtlog.GetNumberOfEventLogRecords(hand)
you can find plenty of demos related to the winapi in your C:\PythonXX\Lib\site-packages\win32\Demos folder. In this folder you'll find a script named eventLogDemo.py. There you can see how to use win32evtlog module. Just start this script with eventLogDemo.py -v and you will get prints from your Windows event log with logtype Application.
In case you can't find this script:
import win32evtlog
import win32api
import win32con
import win32security # To translate NT Sids to account names.
import win32evtlogutil
def ReadLog(computer, logType="Application", dumpEachRecord = 0):
# read the entire log back.
h=win32evtlog.OpenEventLog(computer, logType)
numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
# print "There are %d records" % numRecords
num=0
while 1:
objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
if not objects:
break
for object in objects:
# get it for testing purposes, but dont print it.
msg = win32evtlogutil.SafeFormatMessage(object, logType)
if object.Sid is not None:
try:
domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
sidDesc = "%s/%s" % (domain, user)
except win32security.error:
sidDesc = str(object.Sid)
user_desc = "Event associated with user %s" % (sidDesc,)
else:
user_desc = None
if dumpEachRecord:
print "Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format())
if user_desc:
print user_desc
try:
print msg
except UnicodeError:
print "(unicode error printing message: repr() follows...)"
print repr(msg)
num = num + len(objects)
if numRecords == num:
print "Successfully read all", numRecords, "records"
else:
print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
print "(Note that some other app may have written records while we were running!)"
win32evtlog.CloseEventLog(h)
def usage():
print "Writes an event to the event log."
print "-w : Dont write any test records."
print "-r : Dont read the event log"
print "-c : computerName : Process the log on the specified computer"
print "-v : Verbose"
print "-t : LogType - Use the specified log - default = 'Application'"
def test():
# check if running on Windows NT, if not, display notice and terminate
if win32api.GetVersion() & 0x80000000:
print "This sample only runs on NT"
return
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
computer = None
do_read = do_write = 1
logType = "Application"
verbose = 0
if len(args)>0:
print "Invalid args"
usage()
return 1
for opt, val in opts:
if opt == '-t':
logType = val
if opt == '-c':
computer = val
if opt in ['-h', '-?']:
usage()
return
if opt=='-r':
do_read = 0
if opt=='-w':
do_write = 0
if opt=='-v':
verbose = verbose + 1
if do_write:
ph=win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph,win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th,win32security.TokenUser)[0]
win32evtlogutil.ReportEvent(logType, 2,
strings=["The message text for event 2","Another insert"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
strings=["A warning","An even more dire warning"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
strings=["An info","Too much info"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
print("Successfully wrote 3 records to the log")
if do_read:
ReadLog(computer, logType, verbose > 0)
if __name__=='__main__':
test()
I hope this script fits your needs
I am trying to develop this program which is used to start tomcat server version 7 using python. I am using ubuntu OS.
#!/usr/bin/python
import os
import subprocess
proc=raw_input("Enter the mode :")
os.environ["JAVA_HOME"] = '/usr/lib/jvm/java-7-openjdk-amd64/bin';
os.environ["JRE_HOME"]='/usr/lib/jvm/java-7-openjdk-amd64/jre';
os.environ["CATALINA_HOME"] = '/export/apps/tomcat7';
os.environ["PATH"] = '$JAVA_HOME/bin:$PATH';
if proc == "start":
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'start'])
elif proc == "stop":
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'stop'])
print "Tomcat stopped successfully"
elif proc == "restart":
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'stop'])
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'start'])
print "tomcat restarted successfully"
else:
print "error: give any mode"
print "Thank you"
But i keep getting this error.
/export/apps/tomcat7/bin/catalina.sh: 1: /export/apps/tomcat7/bin/catalina.sh: uname: not found
/export/apps/tomcat7/bin/catalina.sh: 1: /export/apps/tomcat7/bin/catalina.sh: dirname: not found
/export/apps/tomcat7/bin/catalina.sh: 1: /export/apps/tomcat7/bin/catalina.sh: tty: not found
/export/apps/tomcat7/bin/catalina.sh: 379: /export/apps/tomcat7/bin/catalina.sh: touch: not found
Anyone please help me to rectify this error..
Finally i got the solution to develop a python script used to start tomcat server automatically. Herewith i have submitted my code..
#!/usr/bin/python
import os
import subprocess
proc=raw_input("Enter the mode :")
os.environ["JAVA_HOME"] = '/usr/lib/jvm/java-7-openjdk-amd64'
os.environ["CATALINA_HOME"] = '/export/apps/tomcat7'
if proc == "start":
os.getcwd()
os.chdir("/export/apps/tomcat7/bin/")
os.getcwd()
subprocess.call('sh catalina.sh start',shell=True)
print "Tomcat started successfully"
elif proc == "stop":
os.getcwd()
os.chdir("/export/apps/tomcat7/bin/")
os.getcwd()
subprocess.call('sh catalina.sh stop',shell=True)
print "Tomcat stopped successfully"
elif proc == "restart":
os.getcwd()
os.chdir("/export/apps/tomcat7/bin/")
os.getcwd()
subprocess.call('sh catalina.sh stop',shell=True)
subprocess.call('sh catalina.sh start',shell=True)
print "tomcat restarted successfully"
else:
print "error: give any mode"
print "Thank you"
The python script to start, stop, check status & restart tomcat. That works for Python 2.6
#!/usr/bin/env python
# This is an init script to start, stop, check status & restart tomcat.
import sys
import subprocess
import time
scriptName = 'tomact_init.py'
tomcatBinDir = '/apps/apache-tomcat-7.0.63/bin'
tomcatShutdownPeriod = 5
commandToCheckTomcatProcess = "ps -ef | grep -v grep | grep " + tomcatBinDir + " | wc -l"
commandToFindTomcatProcessId = 'ps -ef | grep -v grep | grep ' + tomcatBinDir + ' | awk \'{print $2}\''
def isProcessRunning():
pStatus = True
tProcess = subprocess.Popen(commandToCheckTomcatProcess, stdout=subprocess.PIPE, shell=True)
out, err = tProcess.communicate()
if int(out) < 1:
pStatus = False
return pStatus
def usage():
print "Usage: python " + scriptName + " start|stop|status|restart"
print "or"
print "Usage: <path>/" + scriptName + " start|stop|status|restart"
def start():
if isProcessRunning():
print "Tomcat process is already running"
else:
print "Starting the tomcat"
subprocess.Popen([tomcatBinDir + "/startup.sh"], stdout=subprocess.PIPE)
def stop():
if isProcessRunning():
print "Stopping the tomcat"
subprocess.Popen([tomcatBinDir + "/shutdown.sh"], stdout=subprocess.PIPE)
time.sleep(tomcatShutdownPeriod)
if isProcessRunning():
tPid = subprocess.Popen([commandToFindTomcatProcessId], stdout=subprocess.PIPE, shell=True)
out, err = tPid.communicate()
subprocess.Popen(["kill -9 " + out], stdout=subprocess.PIPE, shell=True)
print "Tomcat failed to shutdown, so killed with PID " + out
else:
print "Tomcat process is not running"
def status():
if isProcessRunning():
tPid = subprocess.Popen([commandToFindTomcatProcessId], stdout=subprocess.PIPE, shell=True)
out, err = tPid.communicate()
print "Tomcat process is running with PID " + out
else:
print "Tomcat process is not running"
if len(sys.argv) != 2:
print "Missing argument"
usage()
sys.exit(0)
else:
action = sys.argv[1]
if action == 'start':
start()
elif action == 'stop':
stop()
elif action == 'status':
status()
elif action == 'restart':
stop()
start()
else:
print "Invalid argument"
usage()
Python does not perform variable substitution as shell does, so you're passing a wrong PATH. You should try with
os.environ["PATH"] = '/usr/lib/jvm/java-7-openjdk-amd64/bin:%s' % os.environ["PATH"]