예제 #1
0
	def getloadavg():
		"""
		Uses /proc/loadavg to emulate os.getloadavg().
		Raises OSError if the load average was unobtainable.
		"""
		try:
			if platform.system() in ["AIX", "HP-UX"]:
				loadavg_str = os.popen('LANG=C /usr/bin/uptime 2>/dev/null').readline().split()
				while loadavg_str[0] != 'load' and loadavg_str[1] != 'average:':
				    loadavg_str = loadavg_str[1:]
				loadavg_str = loadavg_str[2:5]
				loadavg_str = [x.rstrip(',') for x in loadavg_str]
				loadavg_str = ' '.join(loadavg_str)
			else:
				with open('/proc/loadavg') as f:
					loadavg_str = f.readline()
		except (IOError, IndexError):
			# getloadavg() is only supposed to raise OSError, so convert
			raise OSError('unknown')
		loadavg_split = loadavg_str.split()
		if len(loadavg_split) < 3:
			raise OSError('unknown')
		loadavg_floats = []
		for i in range(3):
			try:
				loadavg_floats.append(float(loadavg_split[i]))
			except ValueError:
				raise OSError('unknown')
		return tuple(loadavg_floats)
예제 #2
0
def send_mail(mysettings, message):

    import smtplib

    mymailhost = "localhost"
    mymailport = 25
    mymailuser = ""
    mymailpasswd = ""
    myrecipient = "root@localhost"

    # Syntax for PORTAGE_ELOG_MAILURI (if defined):
    # adress [[user:passwd@]mailserver[:port]]
    # where adress:     recipient adress
    #       user:       username for smtp auth (defaults to none)
    #       passwd:     password for smtp auth (defaults to none)
    #       mailserver: smtp server that should be used to deliver the mail (defaults to localhost)
    #					alternatively this can also be the absolute path to a sendmail binary if you don't want to use smtp
    #       port:       port to use on the given smtp server (defaults to 25, values > 100000 indicate that starttls should be used on (port-100000))
    if " " in mysettings["PORTAGE_ELOG_MAILURI"]:
        myrecipient, mymailuri = mysettings["PORTAGE_ELOG_MAILURI"].split()
        if "@" in mymailuri:
            myauthdata, myconndata = mymailuri.rsplit("@", 1)
            try:
                mymailuser, mymailpasswd = myauthdata.split(":")
            except ValueError:
                print(
                    _("!!! invalid SMTP AUTH configuration, trying unauthenticated ..."
                      ))
        else:
            myconndata = mymailuri
        if ":" in myconndata:
            mymailhost, mymailport = myconndata.split(":")
        else:
            mymailhost = myconndata
    else:
        myrecipient = mysettings["PORTAGE_ELOG_MAILURI"]

    myfrom = message.get("From")

    if sys.hexversion < 0x3000000:
        myrecipient = _unicode_encode(myrecipient,
                                      encoding=_encodings['content'],
                                      errors='strict')
        mymailhost = _unicode_encode(mymailhost,
                                     encoding=_encodings['content'],
                                     errors='strict')
        mymailport = _unicode_encode(mymailport,
                                     encoding=_encodings['content'],
                                     errors='strict')
        myfrom = _unicode_encode(myfrom,
                                 encoding=_encodings['content'],
                                 errors='strict')
        mymailuser = _unicode_encode(mymailuser,
                                     encoding=_encodings['content'],
                                     errors='strict')
        mymailpasswd = _unicode_encode(mymailpasswd,
                                       encoding=_encodings['content'],
                                       errors='strict')

    # user wants to use a sendmail binary instead of smtp
    if mymailhost[0] == os.sep and os.path.exists(mymailhost):
        fd = os.popen(mymailhost + " -f " + myfrom + " " + myrecipient, "w")
        fd.write(message.as_string())
        if fd.close() != None:
            sys.stderr.write(
                _("!!! %s returned with a non-zero exit code. This generally indicates an error.\n"
                  ) % mymailhost)
    else:
        try:
            if int(mymailport) > 100000:
                myconn = smtplib.SMTP(mymailhost, int(mymailport) - 100000)
                myconn.ehlo()
                if not myconn.has_extn("STARTTLS"):
                    raise portage.exception.PortageException(
                        _("!!! TLS support requested for logmail but not suported by server"
                          ))
                myconn.starttls()
                myconn.ehlo()
            else:
                myconn = smtplib.SMTP(mymailhost, mymailport)
            if mymailuser != "" and mymailpasswd != "":
                myconn.login(mymailuser, mymailpasswd)

            message_str = message.as_string()
            if sys.hexversion >= 0x3000000:
                # Force ascii encoding in order to avoid UnicodeEncodeError
                # from smtplib.sendmail with python3 (bug #291331).
                message_str = _unicode_encode(message_str,
                                              encoding='ascii',
                                              errors='backslashreplace')
                message_str = _unicode_decode(message_str,
                                              encoding='ascii',
                                              errors='replace')

            myconn.sendmail(myfrom, myrecipient, message_str)
            myconn.quit()
        except smtplib.SMTPException as e:
            raise portage.exception.PortageException(
                _("!!! An error occured while trying to send logmail:\n") +
                str(e))
        except socket.error as e:
            raise portage.exception.PortageException(
                _("!!! A network error occured while trying to send logmail:\n%s\nSure you configured PORTAGE_ELOG_MAILURI correctly?"
                  ) % str(e))
    return
예제 #3
0
def send_mail(mysettings, message):

	import smtplib

	mymailhost = "localhost"
	mymailport = 25
	mymailuser = ""
	mymailpasswd = ""
	myrecipient = "root@localhost"
	
	# Syntax for PORTAGE_ELOG_MAILURI (if defined):
	# adress [[user:passwd@]mailserver[:port]]
	# where adress:     recipient adress
	#       user:       username for smtp auth (defaults to none)
	#       passwd:     password for smtp auth (defaults to none)
	#       mailserver: smtp server that should be used to deliver the mail (defaults to localhost)
	#					alternatively this can also be the absolute path to a sendmail binary if you don't want to use smtp
	#       port:       port to use on the given smtp server (defaults to 25, values > 100000 indicate that starttls should be used on (port-100000))
	if " " in mysettings["PORTAGE_ELOG_MAILURI"]:
		myrecipient, mymailuri = mysettings["PORTAGE_ELOG_MAILURI"].split()
		if "@" in mymailuri:
			myauthdata, myconndata = mymailuri.rsplit("@", 1)
			try:
				mymailuser,mymailpasswd = myauthdata.split(":")
			except ValueError:
				print(_("!!! invalid SMTP AUTH configuration, trying unauthenticated ..."))
		else:
			myconndata = mymailuri
		if ":" in myconndata:
			mymailhost,mymailport = myconndata.split(":")
		else:
			mymailhost = myconndata
	else:
		myrecipient = mysettings["PORTAGE_ELOG_MAILURI"]
	
	myfrom = message.get("From")

	if sys.hexversion < 0x3000000:
		myrecipient = _unicode_encode(myrecipient,
			encoding=_encodings['content'], errors='strict')
		mymailhost = _unicode_encode(mymailhost,
			encoding=_encodings['content'], errors='strict')
		mymailport = _unicode_encode(mymailport,
			encoding=_encodings['content'], errors='strict')
		myfrom = _unicode_encode(myfrom,
			encoding=_encodings['content'], errors='strict')
		mymailuser = _unicode_encode(mymailuser,
			encoding=_encodings['content'], errors='strict')
		mymailpasswd = _unicode_encode(mymailpasswd,
			encoding=_encodings['content'], errors='strict')

	# user wants to use a sendmail binary instead of smtp
	if mymailhost[0] == os.sep and os.path.exists(mymailhost):
		fd = os.popen(mymailhost+" -f "+myfrom+" "+myrecipient, "w")
		fd.write(message.as_string())
		if fd.close() != None:
			sys.stderr.write(_("!!! %s returned with a non-zero exit code. This generally indicates an error.\n") % mymailhost)
	else:
		try:
			if int(mymailport) > 100000:
				myconn = smtplib.SMTP(mymailhost, int(mymailport) - 100000)
				myconn.ehlo()
				if not myconn.has_extn("STARTTLS"):
					raise portage.exception.PortageException(_("!!! TLS support requested for logmail but not suported by server"))
				myconn.starttls()
				myconn.ehlo()
			else:
				myconn = smtplib.SMTP(mymailhost, mymailport)
			if mymailuser != "" and mymailpasswd != "":
				myconn.login(mymailuser, mymailpasswd)

			message_str = message.as_string()
			if sys.hexversion >= 0x3000000:
				# Force ascii encoding in order to avoid UnicodeEncodeError
				# from smtplib.sendmail with python3 (bug #291331).
				message_str = _unicode_encode(message_str,
					encoding='ascii', errors='backslashreplace')
				message_str = _unicode_decode(message_str,
					encoding='ascii', errors='replace')

			myconn.sendmail(myfrom, myrecipient, message_str)
			myconn.quit()
		except smtplib.SMTPException as e:
			raise portage.exception.PortageException(_("!!! An error occured while trying to send logmail:\n")+str(e))
		except socket.error as e:
			raise portage.exception.PortageException(_("!!! A network error occured while trying to send logmail:\n%s\nSure you configured PORTAGE_ELOG_MAILURI correctly?") % str(e))
	return
예제 #4
0
파일: mail.py 프로젝트: thesamesam/portage
def send_mail(mysettings, message):

    import smtplib

    mymailhost = "localhost"
    mymailport = 25
    mymailuser = ""
    mymailpasswd = ""
    myrecipient = "root@localhost"

    # Syntax for PORTAGE_ELOG_MAILURI (if defined):
    # address [[user:passwd@]mailserver[:port]]
    # where address:    recipient address
    #       user:       username for smtp auth (defaults to none)
    #       passwd:     password for smtp auth (defaults to none)
    #       mailserver: smtp server that should be used to deliver the mail (defaults to localhost)
    # 					alternatively this can also be the absolute path to a sendmail binary if you don't want to use smtp
    #       port:       port to use on the given smtp server (defaults to 25, values > 100000 indicate that starttls should be used on (port-100000))
    if " " in mysettings.get("PORTAGE_ELOG_MAILURI", ""):
        myrecipient, mymailuri = mysettings["PORTAGE_ELOG_MAILURI"].split()
        if "@" in mymailuri:
            myauthdata, myconndata = mymailuri.rsplit("@", 1)
            try:
                mymailuser, mymailpasswd = myauthdata.split(":")
            except ValueError:
                print(
                    _("!!! invalid SMTP AUTH configuration, trying unauthenticated ..."
                      ))
        else:
            myconndata = mymailuri
        if ":" in myconndata:
            mymailhost, mymailport = myconndata.split(":")
        else:
            mymailhost = myconndata
    else:
        myrecipient = mysettings.get("PORTAGE_ELOG_MAILURI", "")

    myfrom = message.get("From")

    # user wants to use a sendmail binary instead of smtp
    if mymailhost[0] == os.sep and os.path.exists(mymailhost):
        fd = os.popen(f"{mymailhost } -f {myfrom} {myrecipient}", "w")
        fd.write(_force_ascii_if_necessary(message.as_string()))
        if fd.close() is not None:
            sys.stderr.write(
                _(f"!!! {mymailhost} returned with a non-zero exit code. This generally indicates an error.\n"
                  ))
    else:
        try:
            if int(mymailport) > 100000:
                myconn = smtplib.SMTP(mymailhost, int(mymailport) - 100000)
                myconn.ehlo()
                if not myconn.has_extn("STARTTLS"):
                    raise portage.exception.PortageException(
                        _("!!! TLS support requested for logmail but not supported by server"
                          ))
                myconn.starttls()
                myconn.ehlo()
            else:
                myconn = smtplib.SMTP(mymailhost, mymailport)
            if mymailuser != "" and mymailpasswd != "":
                myconn.login(mymailuser, mymailpasswd)

            message_str = _force_ascii_if_necessary(message.as_string())
            myconn.sendmail(myfrom, myrecipient, message_str)
            myconn.quit()
        except smtplib.SMTPException as e:
            raise portage.exception.PortageException(
                _(f"!!! An error occurred while trying to send logmail:\n{e}"))
        except socket.error as e:
            raise portage.exception.PortageException(
                _(f"!!! A network error occurred while trying to send logmail:\n{e}\nSure you configured PORTAGE_ELOG_MAILURI correctly?"
                  ))