syslog.openlog

Here are the examples of the python api syslog.openlog taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

86 Examples 7

Example 1

Project: denyhosts
Source File: report.py
View license
    def __init__(self, hostname_lookup, use_syslog=False):
        self.report = ""
        if use_syslog and not HAS_SYSLOG:
            warn("syslog is unavailable on this platform")
        self.use_syslog = use_syslog and HAS_SYSLOG
        if self.use_syslog:
            syslog.openlog("denyhosts")
        self.hostname_lookup = is_true(hostname_lookup)

Example 2

Project: laikaboss
Source File: util.py
View license
def init_logging():
    globals()['logFacility'] = getattr(syslog, config.logfacility)
    globals()['logIdentity'] = config.logidentity
    globals()['moduleLogLevel'] = getattr(syslog, config.moduleloglevel)
    globals()['scanLogLevel'] = getattr(syslog, config.scanloglevel)
    globals()['logResultFromSource'] = config.logresultfromsource
    syslog.openlog(logIdentity, 0, logFacility)

Example 3

Project: radish
Source File: syslog_writer.py
View license
    def syslog_writer_before_all(self, features, marker):  # pylint: disable=unused-argument
        """
            Opens the syslog
        """
        syslog.openlog("radish")
        self.log(u"begin run {0}".format(marker))

Example 4

Project: home-assistant
Source File: syslog.py
View license
    def send_message(self, message="", **kwargs):
        """Send a message to a user."""
        import syslog

        title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)

        syslog.openlog(title, self._option, self._facility)
        syslog.syslog(self._priority, message)
        syslog.closelog()

Example 5

Project: pakrat
Source File: log.py
View license
def write(pri, message):
    """ Record a log message.

    Currently just uses syslog, and if unattended, writes the log messages
    to stdout so they can be piped elsewhere.
    """
    syslog.openlog('pakrat')  # sets log ident
    syslog.syslog(pri, message)
    if not sys.stdout.isatty():
        print message  # print if running unattended

Example 6

Project: oslo.log
Source File: handlers.py
View license
        def __init__(self, facility=syslog.LOG_USER):
            # Do not use super() unless type(logging.Handler) is 'type'
            # (i.e. >= Python 2.7).
            logging.Handler.__init__(self)
            binary_name = _get_binary_name()
            syslog.openlog(binary_name, 0, facility)

Example 7

Project: TrustRouter
Source File: mac.py
View license
    def __init__(self, config=None, socket_=None, verifier=None):
        if socket_ is None:
            self.socket = socket.socket(socket.PF_SYSTEM,
                                        socket.SOCK_STREAM,
                                        socket.SYSPROTO_CONTROL)
        else:
            self.socket = socket_
        
        if verifier is None:
            syslog.openlog("TrustRouter")
            def log(string):
                syslog.syslog(syslog.LOG_ALERT, string)
            self.verifier = RAVerifier(log, config)
        else:
            self.verifier = verifier

Example 8

Project: laikaboss
Source File: util.py
View license
def init_logging():
    globals()['logFacility'] = getattr(syslog, config.logfacility)
    globals()['logIdentity'] = config.logidentity
    globals()['moduleLogLevel'] = getattr(syslog, config.moduleloglevel)
    globals()['scanLogLevel'] = getattr(syslog, config.scanloglevel)
    globals()['logResultFromSource'] = config.logresultfromsource
    syslog.openlog(logIdentity, 0, logFacility)

Example 9

Project: subscription-manager
Source File: rhsm_d.py
View license
def log_syslog(level, msg):
    syslog.openlog("rhsmd")
    syslog.syslog(level, msg)
    log.info("rhsmd: %s" % msg)
    if enable_debug:
        print msg

Example 10

Project: ansible-eos
Source File: eos_facts.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 11

Project: ansible-modules-core
Source File: _accelerate.py
View license
def main():
    global DEBUG_LEVEL
    module = AnsibleModule(
        argument_spec = dict(
            port=dict(required=False, default=5099),
            ipv6=dict(required=False, default=False, type='bool'),
            multi_key=dict(required=False, default=False, type='bool'),
            timeout=dict(required=False, default=300),
            password=dict(required=True),
            minutes=dict(required=False, default=30),
            debug=dict(required=False, default=0, type='int')
        ),
        supports_check_mode=True
    )

    syslog.openlog('ansible-%s' % module._name)

    password  = base64.b64decode(module.params['password'])
    port      = int(module.params['port'])
    timeout   = int(module.params['timeout'])
    minutes   = int(module.params['minutes'])
    debug     = int(module.params['debug'])
    ipv6      = module.params['ipv6']
    multi_key = module.params['multi_key']

    if not HAS_KEYCZAR:
        module.fail_json(msg="keyczar is not installed (on the remote side)")

    DEBUG_LEVEL=debug
    pid_file = get_pid_location(module)

    daemon_pid = None
    daemon_running = False
    if os.path.exists(pid_file):
        try:
            daemon_pid = int(open(pid_file).read())
            try:
                # sending signal 0 doesn't do anything to the
                # process, other than tell the calling program
                # whether other signals can be sent
                os.kill(daemon_pid, 0)
            except OSError:
                e        = get_exception()
                message  = 'the accelerate daemon appears to be running'
                message += 'as a different user that this user cannot access'
                message += 'pid=%s' % daemon_pid

                if e.errno == errno.EPERM:
                    # no permissions means the pid is probably
                    # running, but as a different user, so fail
                    module.fail_json(msg=message)
            else:
                daemon_running = True
        except ValueError:
            # invalid pid file, unlink it - otherwise we don't care
            try:
                os.unlink(pid_file)
            except:
                pass

    if daemon_running and multi_key:
        # try to connect to the file socket for the daemon if it exists
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            try:
                s.connect(SOCKET_FILE)
                s.sendall(password + '\n')
                data = ""
                while '\n' not in data:
                    data += s.recv(2048)
                res = data.strip()
            except:
                module.fail_json(msg="failed to connect to the local socket file")
        finally:
            try:
                s.close()
            except:
                pass

        if res in ("OK", "EXISTS"):
            module.exit_json(msg="transferred new key to the existing daemon")
        else:
            module.fail_json(msg="could not transfer new key: %s" % data.strip())
    else:
        # try to start up the daemon
        daemonize(module, password, port, timeout, minutes, ipv6, pid_file)

Example 12

Project: ansible-eos
Source File: eos_mlag_interface.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 13

Project: ansible-eos
Source File: eos_config.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 14

Project: ansible-eos
Source File: eos_ethernet.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 15

Project: ansible-eos
Source File: eos_ipinterface.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 16

Project: ansible-eos
Source File: eos_mlag_config.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 17

Project: ansible-eos
Source File: eos_ping.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 18

View license
    def log(self, entry):
        """ This method will log information to the local syslog facility """
        if self.logging:
            syslog.openlog('ansible-%s' % self.module._name)
            syslog.syslog(syslog.LOG_NOTICE, entry)

Example 19

Project: ansible-eos
Source File: eos_bgp_neighbor.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 20

Project: ansible-eos
Source File: eos_command.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 21

Project: bonding
Source File: bonding.py
View license
def peers(quiet=True):
    if os.geteuid() != 0:
        print ('%sroot privileges are needed to properly check for bonding '
               'peers. Skipping...%s' % (RED, RESET))
        return {}

    syslog.openlog('bonding')
    syslog.syslog('Scanning for bonding interface peers')

    ifaces = get_iface_list()

    # Enable all normal interfaces
    if not quiet:
        sys.stdout.write('Enabling interfaces')
        sys.stdout.flush()
    for iface in ifaces:
        if is_iface_loopback(iface) or is_iface_master(iface):
            continue
        if not quiet:
            sys.stdout.write('.')
            sys.stdout.flush()
        syslog.syslog('Enabling interface %s' % iface)
        try:
            set_iface_flag(iface, IFF_UP)
        except IOError, e:
            raise SystemExit('%s %s. This generally indicates a misconfigured '
                             'interface' % (e, iface))

    if not quiet:
        print '\nSleeping 5 seconds for switch port negotiation...'
    time.sleep(5)

    if not quiet:
        sys.stdout.write('Scanning')
        sys.stdout.flush()
    secondaries = []
    groups = {}
    for send_iface in ifaces:
        if not quiet:
            sys.stdout.write('.')
            sys.stdout.flush()
        if (is_iface_loopback(send_iface) or is_iface_master(send_iface) or
                send_iface in secondaries):
            continue

        # The data required for building the frame
        # Static data for frame payload that includes the sending interface
        static = 'IF%sIF' % send_iface
        # Build the rest of the payload using random data
        payload = '%s%s' % (static, os.urandom(46 - len(static)))
        # Broadcast FF:FF:FF:FF:FF:FF
        dst_mac = '\xff\xff\xff\xff\xff\xff'
        if USEREALSRCMAC:
            # The real MAC address of the sending interface
            src_mac = get_mac_addr_raw(send_iface)
        else:
            # Invalid source MAC
            src_mac = '\x00\x00\x00\x00\x00\x00'
        # Unregistered EtherType, in this case for Interface Peer Discovery
        frame_type = '\x50\x44'

        # Set up the sending interface socket
        s1 = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
                           socket.htons(ETH_P_ALL))
        s1.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, send_iface + '\0')
        s1.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s1.bind((send_iface, 0))
        s1.setblocking(0)

        for recv_iface in ifaces:
            if not quiet:
                sys.stdout.write('.')
                sys.stdout.flush()
            if (is_iface_loopback(recv_iface) or is_iface_master(recv_iface) or
                    recv_iface == send_iface):
                continue

            # Set up the receiving interface socket
            s2 = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
                               socket.htons(ETH_P_ALL))
            s2.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE,
                          recv_iface + '\0')
            s2.bind((recv_iface, 0))
            s2.settimeout(TIMEOUT)

            # Place current receiving interface into promiscuous mode
            current_flags = 0
            ifreq = fcntl.ioctl(s2.fileno(), SIOCGIFFLAGS,
                                struct.pack('256s', recv_iface[:15]))
            (current_flags,) = struct.unpack('16xH', ifreq[:18])
            current_flags |= IFF_PROMISC
            ifreq = struct.pack('16sH', recv_iface, current_flags)
            fcntl.ioctl(s2.fileno(), SIOCSIFFLAGS, ifreq)

            # Try sending and receiving 3 times to give us better chances of
            # catching the send
            # Generally we always catch on the first time
            for i in xrange(0, 3):
                try:
                    s1.sendall('%s%s%s%s' % (dst_mac, src_mac, frame_type,
                                             payload))
                except (socket.timeout, socket.error):
                    continue
                try:
                    data = s2.recv(60)
                except (socket.timeout, socket.error):
                    continue
                recv_frame_type = data[12:14]
                recv_payload = data[14:]
                if payload == recv_payload and recv_frame_type == frame_type:
                    if send_iface not in groups:
                        groups[send_iface] = []
                    groups[send_iface].append(recv_iface)
                    secondaries.append(recv_iface)
                    break

            # Take the receiving interface out of promiscuous mode
            current_flags ^= IFF_PROMISC
            ifreq = struct.pack('16sH', recv_iface, current_flags)
            fcntl.ioctl(s1.fileno(), SIOCSIFFLAGS, ifreq)

            s2.close()

        s1.close()

    for iface in sorted(groups.keys()):
        syslog.syslog('Interface group: %s %s' %
                      (iface, ' '.join(groups[iface])))

    syslog.syslog('Scan for bonding interface peers completed')

    if not quiet:
        print 'Done'
    return groups

Example 22

Project: backintime
Source File: logger.py
View license
def changeProfile(profile_id):
    name = os.getenv('LOGNAME', 'unknown')
    syslog.openlog("%s (%s/%s)" %(APP_NAME, name, profile_id))

Example 23

Project: ansible-eos
Source File: eos_config.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 24

Project: ansible-eos
Source File: eos_portchannel.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 25

Project: ansible-eos
Source File: eos_ethernet.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 26

Project: laikaboss
Source File: laikamilter.py
View license
    def __init__(self, name, facility):
        syslog.openlog(name, 0, facility)

Example 27

Project: ansible-eos
Source File: eos_facts.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 28

Project: ansible-eos
Source File: eos_command.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 29

Project: container-agent
Source File: run_containers.py
View license
def main():
    if len(sys.argv) > 2:
        Fatal('usage: %s [containers.yaml]' % sys.argv[0])

    if len(sys.argv) == 2:
        with open(sys.argv[1], 'r') as fp:
            config = yaml.load(fp)
    else:
        config = yaml.load(sys.stdin)

    syslog.openlog(PROGNAME)
    LogInfo('processing container manifest')

    CheckVersion(config)

    all_volumes = LoadVolumes(config.get('volumes', []))
    user_containers = LoadUserContainers(config.get('containers', []),
                                         all_volumes)
    CheckGroupWideConflicts(user_containers)

    if user_containers:
        infra_containers = LoadInfraContainers(user_containers)
        RunContainers(infra_containers + user_containers)

Example 30

Project: bonding
Source File: bonding.py
View license
def bond_deb(groups, bond_info):
    syslog.openlog('bonding')
    syslog.syslog('Bonding configuration started')

    provided_bond_info = True
    if not bond_info:
        provided_bond_info = False

    if not os.path.exists('/sbin/ifenslave'):
        print ('%sThe ifenslave package must be installed for '
               'bonding to work%s' % (RED, RESET))
        syslog.syslog('/sbin/ifenslave is missing, cannot continue')
        sys.exit(203)

    if not bond_info:
        bond_info = collect_bond_info(groups, 'debian')
        syslog.syslog('Interactively collecting bonding configuration')
    else:
        syslog.syslog('Bonding configuration supplied for an unattended '
                      'or automated run')

    date = time.strftime('%Y-%m-%d')
    net_dir = '/etc/network'
    backup_dir = '%s/%s-bak-%s' % (net_dir, bond_info['master'], date)

    syslog.syslog('Backing up configuration files before modification to %s' %
                  backup_dir)
    if not provided_bond_info:
        print 'Backing up existing ifcfg files to %s' % backup_dir
    if not os.path.isdir(backup_dir):
        os.mkdir(backup_dir, 0755)
    else:
        print ('%sThe backup directory already exists, to prevent overwriting '
               'required backup files, this script will exit.%s' %
               (RED, RESET))
        syslog.syslog('The backup directory already exists, cannot continue')
        sys.exit(201)

    shutil.copyfile('/etc/network/interfaces', '%s/interfaces' % backup_dir)

    ifh = open('/etc/network/interfaces')
    interfaces_lines = ifh.readlines()
    ifh.close()

    interfaces_dict = {'auto': []}
    iface = None
    for line in interfaces_lines:
        line = line.strip()
        if line.startswith('iface'):
            fields = line.split()
            iface = fields[1]
            interfaces_dict[iface] = {
                'stanza': fields[2:],
                'conf': {
                    'dns-nameservers': '',
                    'dns-search': ''
                }
            }
        elif line.startswith('auto'):
            fields = line.split()
            interfaces_dict['auto'].append(fields[1])
        elif line.startswith('source'):
            continue  # TODO: handle this
        elif line.startswith('mapping'):
            continue  # TODO: handle this
        elif line.startswith('apply-'):
            continue  # TODO: handle this
        elif line and iface:
            if line.startswith('#'):
                continue
            fields = line.split()
            interfaces_dict[iface]['conf'][fields[0]] = ' '.join(fields[1:])

    nameservers = None
    search = None
    for iface in bond_info['slaves']:
        if (iface in interfaces_dict and
                interfaces_dict[iface]['conf']['dns-nameservers'] and
                not nameservers):
            nameservers = interfaces_dict[iface]['conf']['dns-nameservers']
        if (iface in interfaces_dict and
                interfaces_dict[iface]['conf']['dns-search'] and not search):
            search = interfaces_dict[iface]['conf']['dns-search']

    slaves = bond_info['slaves']
    bond_info['slaves'] = ' '.join(bond_info['slaves'])

    syslog.syslog('Writing /etc/network/interfaces')

    interfaces_cfg = ''
    for slave in slaves:
        interfaces_cfg += """auto %s
iface %s inet manual
    bond-master %s
\n""" % (slave, slave, bond_info['master'])

    interfaces_cfg += """auto %(master)s
iface %(master)s inet static
    address %(ipaddr)s
    netmask %(netmask)s
    bond-mode %(mode)s
    bond-miimon 100
    slaves %(slaves)s
""" % bond_info

    if bond_info['opts']:
        interfaces_cfg += """%s
""" % bond_info['opts']

    if nameservers:
        interfaces_cfg += """    dns-nameservers %s
""" % nameservers

    if search:
        interfaces_cfg += """    dns-search %s
""" % search

    if bond_info['gateway']:
        interfaces_cfg += """    gateway %s
""" % bond_info['gateway']

    for key in reversed(interfaces_dict.keys()):
        if key not in ['auto'] and key not in slaves:
            if key in interfaces_dict['auto']:
                interfaces_cfg += """
auto %s""" % key
            interfaces_cfg += """
iface %s %s
""" % (key, ' '.join(interfaces_dict[key]['stanza']))
            for conf in interfaces_dict[key]['conf']:
                if interfaces_dict[key]['conf'][conf]:
                    interfaces_cfg += """    %s %s
""" % (conf, interfaces_dict[key]['conf'][conf])

    ifh = open('/etc/network/interfaces', 'w+')
    ifh.write('%s\n' % interfaces_cfg)
    ifh.close()

    syslog.syslog('Writing /etc/modprobe.d/bonding.conf')
    mfh = open('/etc/modprobe.d/bonding.conf', 'a+')
    mfh.write('alias netdev-%s bonding\n' % bond_info['master'])
    mfh.close()

    syslog.syslog('Bonding configuration has completed')

    if not provided_bond_info:
        print ('\n%sNOTE: After you restart networking you will also have to '
               'manually remove the IP address used in the bond from the '
               'interface that previously held it as debian/ubuntu will not '
               'do this.%s' % (YELLOW, RESET))

        print ("\n%sAdditionally, be aware that networking will likely mark "
               "all slave interfaces as down if you use "
               "/etc/init.d/networking restart, you will have to ifdown and "
               "then ifup each individually, this will require Out-Of-Band "
               "(DRAC/LOM) access if the first bond has the default gateway. "
               "%s" % (YELLOW, RESET))

Example 31

Project: ansible-eos
Source File: eos_interface.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 32

Project: ansible-modules-core
Source File: _accelerate.py
View license
def main():
    global DEBUG_LEVEL
    module = AnsibleModule(
        argument_spec = dict(
            port=dict(required=False, default=5099),
            ipv6=dict(required=False, default=False, type='bool'),
            multi_key=dict(required=False, default=False, type='bool'),
            timeout=dict(required=False, default=300),
            password=dict(required=True),
            minutes=dict(required=False, default=30),
            debug=dict(required=False, default=0, type='int')
        ),
        supports_check_mode=True
    )

    syslog.openlog('ansible-%s' % module._name)

    password  = base64.b64decode(module.params['password'])
    port      = int(module.params['port'])
    timeout   = int(module.params['timeout'])
    minutes   = int(module.params['minutes'])
    debug     = int(module.params['debug'])
    ipv6      = module.params['ipv6']
    multi_key = module.params['multi_key']

    if not HAS_KEYCZAR:
        module.fail_json(msg="keyczar is not installed (on the remote side)")

    DEBUG_LEVEL=debug
    pid_file = get_pid_location(module)

    daemon_pid = None
    daemon_running = False
    if os.path.exists(pid_file):
        try:
            daemon_pid = int(open(pid_file).read())
            try:
                # sending signal 0 doesn't do anything to the
                # process, other than tell the calling program
                # whether other signals can be sent
                os.kill(daemon_pid, 0)
            except OSError:
                e        = get_exception()
                message  = 'the accelerate daemon appears to be running'
                message += 'as a different user that this user cannot access'
                message += 'pid=%s' % daemon_pid

                if e.errno == errno.EPERM:
                    # no permissions means the pid is probably
                    # running, but as a different user, so fail
                    module.fail_json(msg=message)
            else:
                daemon_running = True
        except ValueError:
            # invalid pid file, unlink it - otherwise we don't care
            try:
                os.unlink(pid_file)
            except:
                pass

    if daemon_running and multi_key:
        # try to connect to the file socket for the daemon if it exists
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            try:
                s.connect(SOCKET_FILE)
                s.sendall(password + '\n')
                data = ""
                while '\n' not in data:
                    data += s.recv(2048)
                res = data.strip()
            except:
                module.fail_json(msg="failed to connect to the local socket file")
        finally:
            try:
                s.close()
            except:
                pass

        if res in ("OK", "EXISTS"):
            module.exit_json(msg="transferred new key to the existing daemon")
        else:
            module.fail_json(msg="could not transfer new key: %s" % data.strip())
    else:
        # try to start up the daemon
        daemonize(module, password, port, timeout, minutes, ipv6, pid_file)

Example 33

Project: ansible-eos
Source File: eos.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 34

Project: bonding
Source File: bonding.py
View license
def automated():
    syslog.openlog('bonding')
    syslog.syslog('Beginning an automated bonding configuration')

    mode = 'active-backup'

    ifaces = get_iface_list()
    bond_range = range(0, 101)

    masters = {}
    for iface in ifaces:
        slaves = get_slave_iface_list(iface)
        if is_iface_master(iface):
            bond_int = int(iface.replace('bond', ''))
            del bond_range[bond_range.index(bond_int)]
            if slaves:
                masters[iface] = slaves

    bond = 'bond%s' % bond_range[0]

    gateway_dev = get_default_gateway_dev()
    gateway = get_default_gateway()
    if not gateway_dev or not gateway:
        msg = 'There are no interfaces that contain the default route.'
        print msg
        syslog.syslog(msg)
        sys.exit(100)

    if 'bond' in gateway_dev or is_iface_master(gateway_dev):
        msg = 'The gateway device is already a master/bonded interface'
        print msg
        syslog.syslog(msg)
        sys.exit(101)

    ipaddr = get_ip_address(gateway_dev)
    if not ipaddr:
        msg = ('There is no IP Address configured on the device containing '
               'the default route.')
        print msg
        syslog.syslog(msg)
        sys.exit(102)

    netmask = get_network_mask(gateway_dev)
    if not netmask:
        msg = ('There is no Network Mask configured on the device containing '
               'the default route.')
        print msg
        syslog.syslog(msg)
        sys.exit(103)

    slaves = []
    groups = peers()
    for group in groups:
        if group == gateway_dev or gateway_dev in groups[group]:
            slaves = [group] + groups[group]

    if len(slaves) != 2:
        msg = ('Automated bonding will only work when there are exactly 2 '
               'peer interfaces,\nthe first being the gateway device and '
               'another interface.\n Number of interfaces found: %s (%s)' %
               (len(slaves), ', '.join(slaves)))
        print msg
        syslog.syslog(msg)
        sys.exit(104)

    for master in masters:
        for slave in slaves:
            if slave in masters[master]:
                msg = ('%s is already part of a bond (%s)' %
                       (gateway_dev, master))
                print msg
                syslog.syslog(msg)
                sys.exit(105)

    bond_info = {
        'master': bond,
        'slaves': slaves,
        'ipaddr': ipaddr,
        'netmask': netmask,
        'gateway': gateway,
        'mode': mode,
        'opts': '',
    }

    syslog.syslog('Automated bonding configuration: %s' % repr(bond_info))

    do_bond({}, bond_info)

Example 35

Project: subscription-manager
Source File: utils.py
View license
def system_log(message, priority=syslog.LOG_NOTICE):
    syslog.openlog("subscription-manager")
    syslog.syslog(priority, message.encode("utf-8"))

Example 36

Project: ansible-eos
Source File: eos.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 37

Project: ansible-eos
Source File: eos_acl_entry.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 38

View license
    def log(self, entry):
        """ This method will log information to the local syslog facility """
        if self.logging:
            syslog.openlog('ansible-%s' % self.module._name)
            syslog.syslog(syslog.LOG_NOTICE, entry)

Example 39

Project: ansible-eos
Source File: eos_bgp_config.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 40

Project: backintime
Source File: logger.py
View license
def openlog():
    name = os.getenv('LOGNAME', 'unknown')
    syslog.openlog("%s (%s/1)" %(APP_NAME, name))
    atexit.register(closelog)

Example 41

Project: ansible-eos
Source File: eos_bgp_network.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 42

Project: ansible-eos
Source File: eos_acl_entry.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 43

Project: ansible-eos
Source File: eos_bgp_config.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 44

Project: ansible-eos
Source File: eos_purge.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 45

Project: laikaboss
Source File: laikamilter.py
View license
    def __init__(self, name, facility):
        syslog.openlog(name, 0, facility)

Example 46

Project: ansible-eos
Source File: eos_bgp_neighbor.py
View license
    def log(self, message, log_args=None, priority=None):
        if self._logging:
            syslog.openlog('ansible-eos')
            priority = priority or DEFAULT_SYSLOG_PRIORITY
            syslog.syslog(priority, str(message))

Example 47

Project: PopClip-Extensions
Source File: Klipz.py
View license
def log(msg):
	syslog.openlog("Klipz")
	syslog.syslog(syslog.LOG_ALERT, msg)
	syslog.closelog()

Example 48

Project: yum
Source File: yum-updatesd.py
View license
    def __init__(self, syslog_facility, ident = "yum-updatesd",
                 level = "WARN"):
        UpdateEmitter.__init__(self)
        syslog.openlog(ident, 0, self._facilityMap(syslog_facility))
        self.level = level

Example 49

Project: bonding
Source File: bonding.py
View license
def bond_rhel(version, distro, groups, bond_info):
    syslog.openlog('bonding')
    syslog.syslog('Bonding configuration started')

    provided_bond_info = True
    if not bond_info:
        provided_bond_info = False

    if not bond_info:
        bond_info = collect_bond_info(groups, 'redhat')
        syslog.syslog('Interactively collecting bonding configuration')
    else:
        syslog.syslog('Bonding configuration supplied for an unattended '
                      'or automated run')

    has_nm = False
    if ((LooseVersion(version) >= '6' and distro in ['redhat', 'centos']) or
            distro == 'fedora'):
        has_nm = True
        syslog.syslog('This OS was identified as including NetworkManager')

        nm_pid_path = '/var/run/NetworkManager/NetworkManager.pid'
        if os.path.exists(nm_pid_path):
            pid = open(nm_pid_path).read().strip()
            pid_comm = '/proc/%s/comm' % pid
            if (os.path.exists(pid_comm) and
                    open(pid_comm).read().strip() == 'NetworkManager'):
                print ('%sNetworkManager must be stopped and the network '
                       'service started before you can run this script.%s' %
                       (RED, RESET))
                syslog.syslog('NetworkManager is running, cannot continue')
                sys.exit(202)

    date = time.strftime('%Y-%m-%d')
    net_scripts = '/etc/sysconfig/network-scripts'
    backup_dir = '%s/%s-bak-%s' % (net_scripts, bond_info['master'], date)

    syslog.syslog('Backing up configuration files before modification to %s' %
                  backup_dir)
    if not provided_bond_info:
        print 'Backing up existing ifcfg files to %s' % backup_dir
    if not os.path.isdir(backup_dir):
        os.mkdir(backup_dir, 0755)
    else:
        print ('%sThe backup directory already exists, to prevent overwriting '
               'required backup files, this script will exit.%s' %
               (RED, RESET))
        syslog.syslog('The backup directory already exists, cannot continue')
        sys.exit(201)
    for iface in bond_info['slaves'] + [bond_info['master']]:
        if os.path.exists('%s/ifcfg-%s' % (net_scripts, iface)):
            shutil.move('%s/ifcfg-%s' % (net_scripts, iface), backup_dir)

    if not provided_bond_info:
        print 'Configuring bonding...'
    syslog.syslog('Writing %s/ifcfg-%s' % (net_scripts, bond_info['master']))
    bfh = open('%s/ifcfg-%s' % (net_scripts, bond_info['master']), 'w')
    iface_cfg = '''DEVICE=%(master)s
BOOTPROTO=none
ONBOOT=yes
NETMASK=%(netmask)s
IPADDR=%(ipaddr)s
USERCTL=no
BONDING_OPTS="mode=%(mode)s miimon=100%(opts)s"''' % bond_info
    if has_nm:
        iface_cfg += '\nNM_CONTROLLED=no'
    bfh.write('%s\n' % iface_cfg)
    bfh.close()

    for iface in bond_info['slaves']:
        syslog.syslog('Writing %s/ifcfg-%s' % (net_scripts, iface))
        sfh = open('%s/ifcfg-%s' % (net_scripts, iface), 'w')
        iface_cfg = '''DEVICE=%(slave)s
BOOTPROTO=none
ONBOOT=yes
MASTER=%(master)s
SLAVE=yes
USERCTL=no
HWADDR=%(hwaddr)s''' % dict(bond_info, slave=iface,
                            hwaddr=get_mac_addr(iface).upper())
        if has_nm:
            iface_cfg += '\nNM_CONTROLLED=no'
        sfh.write('%s\n' % iface_cfg)
        sfh.close()

    syslog.syslog('Writing /etc/modprobe.d/bonding.conf')
    mfh = open('/etc/modprobe.d/bonding.conf', 'a+')
    mfh.write('alias %s bonding\n' % bond_info['master'])
    mfh.close()

    if bond_info['gateway']:
        shutil.copy('/etc/sysconfig/network', backup_dir)
        syslog.syslog('Writing /etc/sysconfig/network')
        nfh = open('/etc/sysconfig/network')
        net_cfg = nfh.readlines()
        nfh.close()

        new_net_cfg = ''
        added_gw_dev = False
        added_gw = False
        added_ncz = False
        for line in net_cfg:
            if line.startswith('GATEWAYDEV='):
                new_net_cfg += 'GATEWAYDEV=%s\n' % bond_info['master']
                added_gw_dev = True
            elif line.startswith('GATEWAY='):
                new_net_cfg += 'GATEWAY=%s\n' % bond_info['gateway']
                added_gw = True
            elif line.startswith('NOZEROCONF='):
                new_net_cfg += 'NOZEROCONF=yes\n'
                added_ncz = True
            else:
                new_net_cfg += line

        if not added_gw:
            new_net_cfg += 'GATEWAYDEV=%s\n' % bond_info['master']

        if not added_gw_dev:
            new_net_cfg += 'GATEWAY=%s\n' % bond_info['gateway']

        if not added_ncz:
            new_net_cfg += 'NOZEROCONF=yes\n'

        nfh = open('/etc/sysconfig/network', 'w+')
        nfh.write(new_net_cfg)
        nfh.close()

    syslog.syslog('Bonding configuration has completed')

Example 50

Project: hddfancontrol
Source File: __init__.py
View license
  def __init__(self, facility, options=syslog.LOG_PID):
    syslog.openlog(logoption=options, facility=facility)
    super().__init__()