cocluto/cocluto/Util.py

135 lines
4.4 KiB
Python

import time
import subprocess
import re
import logging
# from wol import *
# import os
# import signal
import smtplib
import sys
if sys.version_info < (3, 0):
from HTMLParser import HTMLParser
from email.MIMEText import MIMEText
else:
from html.parser import HTMLParser
from email.mime.text import MIMEText
def send_text_mail(strFrom, to, strSubject, text):
# from = "SimpaCluster <guillaume.raffy@univ-rennes1.fr>"
mail = MIMEText(text)
mail['From'] = strFrom
mail['Subject'] = strSubject
mail['To'] = to
smtp = smtplib.SMTP('smtp.univ-rennes1.fr', 25)
# smtp.connect()
# smtp.login('guillaume.raffy@univ-rennes1.fr', 'password')
smtp.sendmail(strFrom, [to], mail.as_string())
smtp.close()
class Error(Exception):
message: str
def __init__(self, strMessage):
self.message = strMessage
def getHostName():
(returnCode, stdout, stderr) = execute_program(['hostname', '-s'])
if returnCode != 0:
raise Error(stderr)
strHostName = re.sub(r"\n", "", stdout)
return strHostName
def log(message):
print(time.asctime(time.localtime()) + ' : ' + message)
def execute_program(astrArguments):
# log('execute_program : program [%s]' % (','.join(astrArguments)))
popen = subprocess.Popen(astrArguments, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # bufsize=1 seems to prevent deadlocks that happen 50% the time
stdout, stderr = popen.communicate()
# popen.wait()
result = (popen.returncode, stdout.decode(), stderr)
# log('execute_program : command %s popen.pid = %d' % (astrArguments[0], popen.pid))
# os.kill(popen.pid, signal.SIGTERM)
return result
def execute_command(command):
"""
executes the shell command such as 'set x=1; myprog $x'
"""
popen = subprocess.Popen([command], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable='/bin/bash') # bufsize=1 seems to prevent deadlocks that happen 50% the time
# if we don't specify the optional executable argument, then the default non interactive shell will be used. On debian, the default non-interactive shell is dash, which doesn't understand the keyword 'source' that we use in many places
stdout, stderr = popen.communicate()
# popen.wait()
result = (popen.returncode, stdout.decode(), stderr.decode())
return result
def execute_commandOn(target_machine_fqdn: str, command: str, user: str = None):
"""
execute command on a local or remote machine (using ssh then)
:param str user: if not None, the user that should be used to execute the command (instead of the current user)
"""
logging.debug("executing %s on %s as %s", command, target_machine_fqdn, user)
if getHostName() == target_machine_fqdn.split('.')[0]:
if user is not None:
# su -c "ls -l /tmp" graffy
result = execute_command("su -c '%s' %s" % (command, user))
else:
result = execute_command(command)
else:
if user is not None:
target = '%s@%s' % (user, target_machine_fqdn)
else:
target = target_machine_fqdn
result = execute_program(['ssh', target, "%s" % command])
logging.debug("finished executing %s on %s as %s", command, target_machine_fqdn, user)
return result
def getUpsStatus():
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.token_list = []
def handle_data(self, data):
data = data.strip()
if data and len(data) > 0:
self.token_list.append(data)
# print data
def get_token_list(self):
return self.token_list
from urllib.request import urlopen
try:
url = 'http://Net Vision:public@129.20.27.119/PageMonComprehensive.html'
f = urlopen(url)
res = f.read()
f.close()
except BaseException:
print("bad read")
return
h = MyHTMLParser()
h.feed(res)
_tokensList = h.get_token_list() # noqa:F841
raise NotImplementedError('the implementation is not complete')
if __name__ == '__main__':
from .SimpaDbUtil import wakeUp
# for i in range(30):
# machineName = 'simpatix%d' % (i+10)
# print 'lom ip of %s is %s' % (machineName, getLightOutManagementIpAddress(machineName))
wakeUp('simpatix21')
# print putToSleep('simpatix13')
# print isNonRespondingMachineSleeping('simpatix13')