configd_ctl.py 3.92 KB
Newer Older
1
#!/usr/local/bin/python2.7
2

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
"""
    Copyright (c) 2015 Ad Schellevis
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    --------------------------------------------------------------------------------------
29

30 31 32
    package : configd
    function: commandline tool to send commands to configd (response to stdout)
"""
33

34
import socket
35 36 37
import os.path
import traceback
import syslog
38
import sys
39
import time
40 41 42

__author__ = 'Ad Schellevis'

43
configd_socket_name = '/var/run/configd.socket'
44
configd_socket_wait = 20
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

def exec_config_cmd(exec_command):
    """ execute command using configd socket
    :param exec_command: command string
    :return: string
    """
    # Create and open unix domain socket
    try:
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.connect(configd_socket_name)
    except socket.error:
        syslog.syslog(syslog.LOG_ERR,'unable to connect to configd socket (@%s)'%configd_socket_name)
        print('unable to connect to configd socket (@%s)'%configd_socket_name)
        return None

    try:
        sock.send(exec_command)
63
        data = []
64
        while True:
65
            line = sock.recv(65536)
66
            if line:
67
                data.append(line)
68 69

            # end of stream marker found, exit
70 71 72
            if line.find("%c%c%c"%(chr(0), chr(0), chr(0))) > -1 or (
                len(line) < 3 and len(data) > 1 and (''.join(data[-2:])).find("%c%c%c"%(chr(0), chr(0), chr(0))) > -1
            ):
73 74
                break

75
        return ''.join(data)[:-3]
76 77 78 79 80 81 82 83
    except:
        print ('error in configd communication %s, see syslog for details')
        syslog.syslog(syslog.LOG_ERR,'error in configd communication \n%s'%traceback.format_exc())
    finally:
        sock.close()



84 85
# set a timeout to the socket
socket.setdefaulttimeout(120)
86

87
# validate parameters
88
if len(sys.argv) <= 1:
89
    print ('usage : %s [-m] <command>'%sys.argv[0])
90
    sys.exit(0)
91 92

# check if configd socket exists
93 94 95 96 97 98 99 100
# (wait for a maximum of "configd_socket_wait" seconds for configd to start)
i=0
while not os.path.exists(configd_socket_name):
    if i >= configd_socket_wait:
        break
    time.sleep(1)
    i += 1

101 102 103 104 105 106 107 108 109 110
if not os.path.exists(configd_socket_name):
    print ('configd socket missing (@%s)'%configd_socket_name)
    sys.exit(-1)

if sys.argv[1] == '-m':
    # execute multiple commands at once ( -m "action1 param .." "action2 param .." )
    for exec_command in sys.argv[2:]:
        result=exec_config_cmd(exec_command=exec_command)
        if result is None:
            sys.exit(-1)
111
        print('%s' % (result.strip()))
112
else:
113 114 115 116 117
    # execute single command sequence
    exec_command=' '.join(sys.argv[1:])
    result=exec_config_cmd(exec_command=exec_command)
    if result is None:
        sys.exit(-1)
118
    print('%s' % (result.strip()))