I have python script which run during the start of the linux VM:
I have added it in the chkconfig 345
script is supposed to check the hostname and if it is localhost.localdom then it should exit
#!/usr/bin/python
import subprocess,platform,os,sys,logging,shlex
system_name = os.getenv('HOSTNAME')
if system_name == 'localhost.localdom':
logging.info('Please correct host name for proxies, it is showing localhost')
sys.exit()"
if I run it manually it works fine. But during the startup process, even though the hostname is localhost.localdom. It does not exit.
so it look like during the boot process,
os.getenv('HOSTNAME')
is not returning the localshot.localdom what I have set in condition.
Please help getting this to work during reboot.
Thanks,
Jitendra Singh
posting an answer using the info in Isedev's comment...
you could try getting the hostname by:
import os
system_name = os.popen('/bin/hostname')
if system_name.read().rstrip() == 'localhost.localdom':
logging.info('Please correct host name for proxies, it is showing localhost')
sys.exit()
Related
By no means do I write scripts very often, but I am trying to write a Nagios plugin to check the status of a RAID controller on a remote host. The issue is that the command to get the output requires elevated privileges. What would be the correct, and most effective way to pull this off? The goal is to run:
'/opt/MegaRAID/MegaCli/MegaCli64 -ShowSummary -a0'
on a remote host from the monitoring server,
and then follow the basic idea of this logic:
#Nagios Plugin for Testing LSI Raid Status
import os, sys
import argparse
import socket
import subprocess
#nagios exit codes do not change#
OK = 0
WARNING = 1
CRITICAL = 2
DEPENDENT = 3
UNKNOWN = 4
#nagios exit codes do not change#
#patterns to be searched
active = str("Active")
online = str("Online")
k = str("OK")
degrade = str("Degraded")
fail = str("Failed")
parser = argparse.ArgumentParser(description='Py3 script for monitoring RAID status.')
#arguments
parser.add_argument("--user",
metavar = '-U',
help = "username for remote connection")
parser.add_argument("--hostname",
metavar = '-H',
help = "hostname of the remote host")
args = parser.parse_args()
print(args)
#turning args into variables
hostname = args.hostname
user = args.user
ssh = subprocess.Popen(f"ssh {user}#{hostname} /opt/MegaRAID/MegaCli/MegaCli64 -ShowSummary -a0", shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
check = ssh.stdoutreadlines()
OK_STR = str("RAID is OK!")
WARN_STR = str("Warning! Something is wrong with the RAID!")
CRIT_STR = str("CRITICAL! THE RAID IS BROKEN")
UNK_STR = str("Uh oh! Something ain't right?")
if (degrade) in (check):
print(WARN_STR) and exit(WARNING)
elif (fail) in (check):
print (CRIT_STR) and exit(CRITICAL)
elif (active) or (online) or (k) in (check):
print(OK_STR) and exit(OK)
else:
print(UNK_STR) and exit(UNKNOWN)
Any thoughts? This is far from my forte (and also an unfinished script) so I apologize for the layman format and any confusion in my phrasing.
I am trying to write a Nagios plugin to check the status of a RAID controller on a remote host. The issue is that the command to get the output requires elevated privileges. What would be the correct, and most effective way to pull this off?
I would recommend running the script remotely over NRPE on the system in question, and then give the user the NRPE daemon is running as (probably nagios or similar) sudo permissions to run that script with some very exact parameters.
The nrpe.cfg file mentions this example:
# Usage scenario:
# Execute restricted commmands using sudo. For this to work, you need to add
# the nagios user to your /etc/sudoers. An example entry for alllowing
# execution of the plugins from might be:
#
# nagios ALL=(ALL) NOPASSWD: /usr/lib/nagios/plugins/
...but there's no reason to be so forgiving, you can make it a lot safer by only allowing an exact command:
nagios ALL = NOPASSWD: /usr/sbin/megacli
Note that this allows any parameters with that command, this is even safer as it will not allow any other variants (example):
nagios ALL = NOPASSWD: /usr/sbin/megacli -a foo -b bar -c5 -w1
Then configure the nrpe command to run the above with sudo before it, and it should work. You can verify by su:ing to the nagios user and trying the sudo command yourself.
Also, note that there are very likely some available modules you can import for python nagios plugins that makes it easier for you, to get built-in support for things like thresholds and their syntax.
I have a python application with gunicorn and flask on a centos machine. I access the application from another machine in the following way:
http://host:port/nameOfFunction?path=https://site/directory1/directory2/directory3/file.pdf
The path is correct, because it works. When i enter the same path multiple times, sometimes it works, others, don't.
I am using gunicorn (with the follow command):
gunicorn -b 0.0.0.0:8080 start:app
to start my application. When the answer returns, the screen showing gunicorn prints some piece of code that i put to see some informations.
When it returns me error 500, the code from start isn't printed at all.
I dont have a clue what is the cause of this.
the beginning of the code is:
#app.route("/call", methods=['POST', 'GET'])
def call():
print '\n============================BEGINS======================\n'
path =request.args.get('path')
newPath = path.rsplit('/',1)[1]
directoriesRoot(root)
directoriesRoot(pdfs)
parameters = ["curl", path.replace(' ','%20'), '--output',pdfs+newPath]
p = subprocess.Popen(parameters, stdout=subprocess.PIPE)
output, err = p.communicate()
if err:
return 'ERROR'
person= functionSecundaryWithNoImportance([newPath])
return jsonify(person)
Someone has some clue or already pass for a similar problem?
With the help of user3788685, i found out that my python application was on port 8080 (and probably one of apache's default ports were 8080) so it conflicts. Sometimes it directs to python, others to apache. So i changed the port for my python application to 1234:
gunicorn -b 0.0.0.0:1234 start:app
and now works as a charm!
Using xmlrpclib from Python2 it give back OpaqueRef but I would like to get more informations like the status of all VMs and their names, bandwidth, VCPU
#!/usr/bin/env python
import xmlrpclib
xen = xmlrpclib.Server('http://xen.server.address')
session = xen.session.login_with_password('user', '*****')['Value']
all_vms = xen.VM.get_all(session)['Value']
print(all_vms)
I have tried to works on the status part but do not find the way to print the status of all.
For one VM :
power_state = (records['OpaqueRef:***']['power_state'])
print 'KO' if power_state == 'Halted' else 'OK'
But get stuck on doing that for all VMs of the Host
I log on my VPS with SSH method and set up a test web page with web.py
After I run the server with below command, the VPS come into the server state and I can't do other things to the VPS, e.g. open a browser to check if the server works...
Anyone know how can I do other thing with the server running? In the local computer, it seems no problem obviously.
My terminal operation screen shot
my main.py code is as follows:
# filename: main.py
import web
urls = (
'/wx', 'Handle',
)
class Handle(object):
def GET(self):
return "hello, this is a test"
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
Script is working properly. The app.run() call puts the program in an infinite loop waiting for clients to connect with it.
As #Andersson suggests, you could execute the script, putting it in the background. Or, open another SSH session and use one window for your script & another for whatever else you want to do on your server.
For production systems, you should run web.py under nginx or apache.
See http://webpy.org/cookbook/, scroll down to "Deployments", for guidance on running under Apache and Nginx.
I'm rather new to Python and Pyro4. So I try to follow the second example of this page Pyro - Python Remote Objects - 4.41, but when I run the server throw this exception:
Traceback (most recent call last):
File "greeting-server.py", line 10, in <module>
ns = Pyro4.locateNS() # find the name server
File "/usr/lib/python2.7/dist-packages/Pyro4/naming.py", line 344, in locateNS
raise e
Pyro4.errors.NamingError: Failed to locate the nameserver
Code Server:
# saved as greeting-server.py
import Pyro4
class GreetingMaker(object):
def get_fortune(self, name):
return "Hello, {0}. Here is your fortune message:\n" \
"Tomorrow's lucky number is 12345678.".format(name)
daemon = Pyro4.Daemon() # make a Pyro daemon
ns = Pyro4.locateNS() # find the name server
uri = daemon.register(GreetingMaker) # register the greeting maker as a Pyro object
ns.register("example.greeting", uri) # register the object with a name in the name server
print("Ready.")
daemon.requestLoop() # start the event loop of the server to wait for calls
Run pyro-ns in another terminial first:
$pyro-ns
*** Pyro Name Server ***
Name server listening on: ('0.0.0.0', 9090)
WARNING: daemon bound on hostname that resolves to loopback address 127.0.x.x
URI is: PYRO://127.0.1.1:9090/7f0001011d2a21ca9fb63702dd216e1143
URI written to: /home/guille/Documents/pyro examples/Pyro4-master/examples/banks/Pyro_NS_URI
Name Server started.
Remark: I work on Debian 8 and I've installed:
sudo apt-get install pyro4
sudo apt-get install python2-pyro4
pip install https://pypi.python.org/packages/2.7/s/serpent/serpent-
1.7-py2.py3-none-any.whl
to run this example
Maybe I missed something. Any ideas why this is not working, or things that I'm doing wrong?
thanks in advance.
This work for me:
Run python -m Pyro4.naming in another terminial first:
Not starting broadcast server for localhost.
NS running on localhost:9090 (127.0.0.1)
URI = PYRO:Pyro.NameServer#localhost:9090
and not pyro-ns I've done before for pyro4 as you see this procedure change
While the URI method in the docs is great, another way to connect is register the domain / IP using Pyro4 SimpleServe
Edit:
This was written for use with Python 3, thanks to #Cyberguille for pointing out that raw_input should be used instead of input on the client code when using Python 2.x
Server
Note that 0.0.0.0 exposes it to the world
# saved as greeting-server.py
import Pyro4
#Pyro4.expose
class GreetingMaker(object):
def get_fortune(self, name):
return "Hello, {0}. Here is your fortune message:\n" \
"Behold the warranty -- the bold print giveth and the fine print taketh away.".format(name)
Pyro4.Daemon.serveSimple({
GreetingMaker: 'Greeting',
}, host="0.0.0.0", port=9090, ns=False, verbose=True)
Then running python greeting-server.py to start the script
Client
# saved as greeting-client.py
import Pyro4
ipAddressServer = "" # TODO add your server remote IP here
# Works for Python3, see edit above for notes on Python 2.x
name = input("What is your name? ").strip()
greetingMaker = Pyro4.core.Proxy('PYRO:Greeting#' + ipAddressServer + ':9090')
print(greetingMaker.get_fortune(name)) # call method normally
I think you are mixing python 3 and python 2 versions here, because you wrote you had to install both 'pyro4' and 'python2-pyro4' packages.
I suspect the former is for python 3 and the latter is the legacy python 2 version.
The 'pyro-ns' shell command seems to launch an older, incompatible version of the name server.