Exemplo n.º 1
0
def install_key_ssh_relayserver(keypriv, private=False):
    """
        This function installs the sshkey
        Args:
            keypriv: The name of the key to copy on the dest machine
            private: Tell if this is the private of the public ssh key
    """

    if private == True:
        keyname = "id_rsa"
        keyperm = 0o600
    else:
        keyname = "id_rsa.pub"
        keyperm = 0o644

    if sys.platform.startswith('linux'):
        if not os.path.isdir(os.path.join(os.path.expanduser('~pulseuser'), ".ssh/")):
            os.makedirs(os.path.join(os.path.expanduser('~pulseuser'), ".ssh/"))
        filekey = os.path.join(os.path.expanduser('~pulseuser'), ".ssh", keyname)
    elif sys.platform.startswith('win'):
        filekey = os.path.join(os.environ["ProgramFiles"], "Pulse", ".ssh", keyname)
    elif sys.platform.startswith('darwin'):
        if not os.path.isdir(os.path.join(os.path.expanduser('~pulse'), ".ssh")):
            os.makedirs(os.path.join(os.path.expanduser('~pulse'), ".ssh"))
        filekey = os.path.join(os.path.expanduser('~pulse'), ".ssh", keyname)
    else:
        return

    file_put_contents(filekey, keypriv)
    if sys.platform.startswith('win'):
        import win32security
        import ntsecuritycon
        user, domain, type = win32security.LookupAccountName ("", "System")
        sd = win32security.GetFileSecurity(filekey, win32security.DACL_SECURITY_INFORMATION)
        dacl = win32security.ACL ()
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_GENERIC_READ | ntsecuritycon.FILE_GENERIC_WRITE, user)
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(filekey, win32security.DACL_SECURITY_INFORMATION, sd)
    else:
        os.chmod(filekey, keyperm)
Exemplo n.º 2
0
def action( objectxmpp, action, sessionid, data, message, dataerreur ):
    print plugin
    print "############data in############### %s"%message['from']
    print json.dumps(data, indent=4)
    print "############data in###############"
    returnmessage = dataerreur
    returnmessage['ret'] = 0
    if objectxmpp.config.agenttype in ['relayserver']:
        #verify key exist
        if not os.path.isfile(os.path.join("/","var","lib","pulse2","clients","reversessh",".ssh","id_rsa")) or not \
            os.path.isfile(os.path.join("/","var","lib","pulse2","clients","reversessh",".ssh","id_rsa.pub")):
            genratekeyforARSreverseSSH()
        print "PROCESSING RELAYSERVER"
        if message['from'] == "console":
            if not "request" in data :
                objectxmpp.send_message_agent("console", dataerreur)
                return
            print message['from']
            print "master@pulse/MASTER"
            if data['request'] == "askinfo":
                print "Processing of request askinfo"
                returnmessage['data'] = data
                returnmessage['data']['fromplugin'] = plugin['NAME']
                returnmessage['data']['typeinfo']  = "info_xmppmachinebyuuid"
                returnmessage['data']['sendother'] = "data@infos@jid"
                returnmessage['data']['sendemettor'] = True
                returnmessage['data']['relayserverip'] = objectxmpp.ipconnection
                returnmessage['data']['key'] = load_key_ssh_relayserver(private=True)
                returnmessage['data']['keypub'] = load_key_ssh_relayserver()
                returnmessage['ret'] = 0
                returnmessage['action'] = "askinfo"
                del returnmessage['data']['request']
                print "Send master this data"
                print json.dumps(returnmessage, indent = 4)
                objectxmpp.send_message_agent( "master@pulse/MASTER",
                                             returnmessage,
                                             mtype = 'chat')
                objectxmpp.send_message_agent("console", returnmessage)
                return
        if message['from'] == message['to']:
            if not "request" in data :
                objectxmpp.send_message_agent(message['to'], dataerreur)
                return
            if data['request'] == "askinfo":
                print "Processing of request askinfo"
                returnmessage['data'] = data
                returnmessage['data']['fromplugin'] = plugin['NAME']
                returnmessage['data']['typeinfo']  = "info_xmppmachinebyuuid"
                returnmessage['data']['sendother'] = "data@infos@jid"
                returnmessage['data']['sendemettor'] = True
                returnmessage['data']['relayserverip'] = objectxmpp.ipconnection
                returnmessage['data']['key'] = load_key_ssh_relayserver(private=True)
                returnmessage['data']['keypub'] = load_key_ssh_relayserver()
                returnmessage['ret'] = 0
                returnmessage['action'] = "askinfo"
                returnmessage['sessionid'] = sessionid
                del returnmessage['data']['request']
                print "Send relayagent this data"
                print json.dumps(returnmessage, indent = 4)
                objectxmpp.send_message_agent( "master@pulse/MASTER",
                                             returnmessage,
                                             mtype = 'chat')
                return
    else:
        print "PROCESSING MACHINE \n%s\n"%json.dumps(data, indent = 4)
        objectxmpp.xmpplog(  "REVERSE SSH",
                                    type = 'noset',
                                    sessionname = sessionid,
                                    priority = -1,
                                    action = "",
                                    who = objectxmpp.boundjid.bare,
                                    how = "",
                                    why = "",
                                    module = "Notify | Packaging | Reversessh",
                                    date = None ,
                                    fromuser = "",
                                    touser = "")

        if data['options'] == "createreversessh":
            install_key_ssh_relayserver(data['key'], private=True)
            install_key_ssh_relayserver(data['keypub'])
            try:
                reversetype = data['reversetype']
            except Exception:
                reversetype = 'R'
            try:
                remoteport = data['remoteport']
            except Exception:
                remoteport = '22'

            objectxmpp.xmpplog( 'create reverse ssh on machine : %s '\
                                  'type reverse : %s port :%s'%(message['to'], reversetype, data['port']),
                                type = 'noset',
                                sessionname = sessionid,
                                priority = -1,
                                action = "",
                                who = objectxmpp.boundjid.bare,
                                how = "",
                                why = "",
                                module = "Notify | Packaging | Reversessh",
                                date = None ,
                                fromuser = "",
                                touser = "")

            if sys.platform.startswith('linux'):
                filekey = os.path.join(os.path.expanduser('~pulseuser'), ".ssh", "id_rsa")
                dd = """#!/bin/bash
                /usr/bin/ssh -t -t -%s %s:localhost:%s -o StrictHostKeyChecking=no -i "%s" -l reversessh %s&
                """%(reversetype, data['port'], remoteport, filekey, data['relayserverip'])
                reversesshsh = os.path.join(os.path.expanduser('~pulseuser'), "reversessh.sh")
                file_put_contents(reversesshsh,  dd)
                os.chmod(reversesshsh, 0o700)
                args = shlex.split(reversesshsh)
                if not 'persistance' in data:
                    data['persistance'] = "no"
                if 'persistance' in data and data['persistance'].lower() != "no":
                    if data['persistance'] in objectxmpp.reversesshmanage:
                        logging.getLogger().info("suppression reversessh %s"%str(objectxmpp.reversesshmanage[data['persistance']]))
                        cmd = "kill -9 %s"%str(objectxmpp.reversesshmanage[data['persistance']])
                        logging.getLogger().info(cmd)
                        simplecommandstr(cmd)
                        objectxmpp.xmpplog( "suppression reversessh %s"%str(objectxmpp.reversesshmanage[data['persistance']]),
                                        type = 'noset',
                                        sessionname = sessionid,
                                        priority = -1,
                                        action = "",
                                        who = objectxmpp.boundjid.bare,
                                        how = "",
                                        why = "",
                                        module = "Notify | Reversessh",
                                        date = None ,
                                        fromuser = "",
                                        touser = "")
                result = subprocess.Popen(args)
                if 'persistance' in data and data['persistance'].lower() != "no":
                    objectxmpp.reversesshmanage[data['persistance']] = str(result.pid)
                else:
                    objectxmpp.reversesshmanage['other'] = str(result.pid)
                logging.getLogger().info("creation reverse ssh pid = %s"% str(result.pid))
                objectxmpp.xmpplog( 'create reverse ssh on machine : %s '\
                                  'type reverse : %s port :%s'%(message['to'], reversetype, data['port']),
                                type = 'noset',
                                sessionname = sessionid,
                                priority = -1,
                                action = "",
                                who = objectxmpp.boundjid.bare,
                                how = "",
                                why = "",
                                module = "Notify | Packaging | Reversessh",
                                date = None ,
                                fromuser = "",
                                touser = "")
            elif sys.platform.startswith('win'):
                filekey = os.path.join(os.environ["ProgramFiles"], "Pulse", ".ssh", "id_rsa")
                os_platform = os.environ['PROCESSOR_ARCHITECTURE']
                try:
                    os_platform = os.environ["PROCESSOR_ARCHITEW6432"] # Will raise exception if x86 arch
                except KeyError:
                    pass
                sshexec =  os.path.join(os.environ["ProgramFiles"], "OpenSSH", "ssh.exe")
                reversesshbat = os.path.join(os.environ["ProgramFiles"], "Pulse", "bin", "reversessh.bat")
                dd = """"%s" -t -t -%s %s:localhost:%s -o StrictHostKeyChecking=no -i "%s" -l reversessh %s
                """%(sshexec, reversetype, data['port'], remoteport, filekey, data['relayserverip'])
                if not os.path.exists(os.path.join(os.environ["ProgramFiles"], "Pulse", "bin")):
                    os.makedirs(os.path.join(os.environ["ProgramFiles"], "Pulse", "bin"))
                file_put_contents(reversesshbat,  dd)
                if not 'persistance' in data:
                    data['persistance'] = "no"

                if 'persistance' in data and data['persistance'].lower() != "no":
                    ###autre piste.
                    ###### voir cela powershell.exe "Stop-Process -Force (Get-NetTCPConnection -LocalPort 22).OwningProcess"
                    #### cmd = 'wmic path win32_process Where "Commandline like \'%reversessh%\'" Call Terminate'
                    if data['persistance'] in objectxmpp.reversesshmanage:
                        logging.getLogger().info("suppression reversessh %s"%str(objectxmpp.reversesshmanage[data['persistance']]))
                        cmd = "taskkill /F /PID %s"%str(objectxmpp.reversesshmanage[data['persistance']])
                        logging.getLogger().info(cmd)
                        simplecommandstr(cmd)
                        objectxmpp.xmpplog( "suppression reversessh %s"%str(objectxmpp.reversesshmanage[data['persistance']]),
                                        type = 'noset',
                                        sessionname = sessionid,
                                        priority = -1,
                                        action = "",
                                        who = objectxmpp.boundjid.bare,
                                        how = "",
                                        why = "",
                                        module = "Notify | Reversessh",
                                        date = None ,
                                        fromuser = "",
                                        touser = "")

                result = subprocess.Popen(reversesshbat)

                if 'persistance' in data and data['persistance'].lower() != "no":
                    objectxmpp.reversesshmanage[data['persistance']] = str(result.pid)
                else:
                    objectxmpp.reversesshmanage['other'] = str(result.pid)
                logging.getLogger().info("creation reverse ssh pid = %s"% str(result.pid))
                objectxmpp.xmpplog( 'create reverse ssh on machine : %s '\
                                  'type reverse : %s port :%s'%(message['to'], reversetype, data['port']),
                                type = 'noset',
                                sessionname = sessionid,
                                priority = -1,
                                action = "",
                                who = objectxmpp.boundjid.bare,
                                how = "",
                                why = "",
                                module = "Notify | Packaging | Reversessh",
                                date = None ,
                                fromuser = "",
                                touser = "")

            elif sys.platform.startswith('darwin'):
                filekey = os.path.join(os.path.expanduser('~pulse'), ".ssh", "id_rsa")
                dd = """#!/bin/bash
                /usr/bin/ssh -t -t -%s %s:localhost:%s -o StrictHostKeyChecking=no -i "%s" -l reversessh %s&
                """%(reversetype, data['port'], remoteport, filekey, data['relayserverip'])
                reversesshsh = os.path.join(os.path.expanduser('~pulse'), "reversessh.sh")
                file_put_contents(reversesshsh,  dd)
                os.chmod(reversesshsh, 0o700)
                args = shlex.split(reversesshsh)
                if not 'persistance' in data:
                    data['persistance'] = "no"
                if 'persistance' in data and data['persistance'].lower() != "no":
                    if data['persistance'] in objectxmpp.reversesshmanage:
                        logging.getLogger().info("suppression reversessh %s"%str(objectxmpp.reversesshmanage[data['persistance']]))
                        cmd = "kill -9 %s"%str(objectxmpp.reversesshmanage[data['persistance']])
                        logging.getLogger().info(cmd)
                        simplecommandstr(cmd)
                        objectxmpp.xmpplog( "suppression reversessh %s"%str(objectxmpp.reversesshmanage[data['persistance']]),
                                        type = 'noset',
                                        sessionname = sessionid,
                                        priority = -1,
                                        action = "",
                                        who = objectxmpp.boundjid.bare,
                                        how = "",
                                        why = "",
                                        module = "Notify | Reversessh",
                                        date = None ,
                                        fromuser = "",
                                        touser = "")
                result = subprocess.Popen(args)
                if 'persistance' in data and data['persistance'].lower() != "no":
                    objectxmpp.reversesshmanage[data['persistance']] = str(result.pid)
                else:
                    objectxmpp.reversesshmanage['other'] = str(result.pid)
                    data['persistance'] = "no"
                logging.getLogger().info("creation reverse ssh pid = %s"% str(result.pid))
                objectxmpp.xmpplog(  "creation reverse ssh pid = %s"% str(result.pid),
                                    type = 'noset',
                                    sessionname = sessionid,
                                    priority = -1,
                                    action = "",
                                    who = objectxmpp.boundjid.bare,
                                    how = "",
                                    why = "",
                                    module = "Notify | Reversessh",
                                    date = None ,
                                    fromuser = "",
                                    touser = "")
            else:
                dd=""
        elif data['options'] == "stopreversessh":
            if sys.platform.startswith('win'):
                ### voir cela powershell.exe "Stop-Process -Force (Get-NetTCPConnection -LocalPort 22).OwningProcess"

                cmd = 'wmic path win32_process Where "Commandline like \'%reversessh%\'" Call Terminate'
                subprocess.Popen(cmd)
            else:
                os.system("lpid=$(ps aux | grep reversessh | grep -v grep | awk '{print $2}');kill -9 $lpid")
                objectxmpp.reversessh = None

        returnmessage = dataerreur
        returnmessage['data'] = data
        returnmessage['ret'] = 0
def action(objectxmpp, action, sessionid, data, message, dataerreur):
    logging.getLogger().debug(
        "###################################################")
    logging.getLogger().debug("call %s from %s" % (plugin, message['from']))
    logging.getLogger().debug(
        "###################################################")
    dataerreur = {
        "action": "result" + action,
        "data": {
            "msg": "error plugin : " + action
        },
        'sessionid': sessionid,
        'ret': 255,
        'base64': False
    }

    if objectxmpp.config.agenttype in ['machine']:
        logging.getLogger().debug(
            "#######################################################")
        logging.getLogger().debug(
            "##############AGENT INSTALL KEY MACHINE################")
        logging.getLogger().debug(
            "#######################################################")
        if not 'key' in data:
            objectxmpp.send_message_agent(message['from'],
                                          dataerreur,
                                          mtype='chat')
            return
        #install keypub on AM
        if sys.platform.startswith('linux'):
            import pwd
            import grp
            #verify compte pulse exist
            try:
                uid = pwd.getpwnam("pulseuser").pw_uid
                gid = grp.getgrnam("pulseuser").gr_gid
                gidroot = grp.getgrnam("root").gr_gid
            except:
                #le compte n'existe pas
                result = simplecommand(
                    encode_strconsole(
                        "adduser --system --group --home /var/lib/pulse2 --shell /bin/rbash --disabled-password pulseuser"
                    ))
            uid = pwd.getpwnam("pulseuser").pw_uid
            gid = grp.getgrnam("pulseuser").gr_gid
            gidroot = grp.getgrnam("root").gr_gid
            authorized_keys_path = os.path.join(
                os.path.expanduser('~pulseuser'), '.ssh', 'authorized_keys')
            if not os.path.isdir(os.path.dirname(authorized_keys_path)):
                os.makedirs(os.path.dirname(authorized_keys_path), 0700)
            if not os.path.isfile(authorized_keys_path):
                file_put_contents(authorized_keys_path, "")
            os.chown(os.path.dirname(authorized_keys_path), uid, gid)
            os.chown(authorized_keys_path, uid, gid)
            os.chown(authorized_keys_path, uid, gid)
            packagepath = os.path.join(os.path.expanduser('~pulseuser'),
                                       'packages')
            pathuser = os.path.join(os.path.expanduser('~pulseuser'))
            if not os.path.isdir(pathuser):
                os.chmod(pathuser, 751)
            if not os.path.isdir(packagepath):
                os.makedirs(packagepath, 0764)
            os.chown(packagepath, uid, gidroot)
            os.chmod(os.path.dirname(authorized_keys_path), 0700)
            os.chmod(authorized_keys_path, 0644)
            os.chmod(packagepath, 0764)
            result = simplecommand(
                encode_strconsole("chown -R pulseuser: '******'"))
        elif sys.platform.startswith('win'):
            import win32net
            # check if pulse account exists
            try:
                win32net.NetUserGetInfo('', 'pulse', 0)
            except:
                # pulse account doesn't exist
                pulseuserpassword = uuid.uuid4().hex
                pulseuserhome = os.path.join(os.environ["ProgramFiles"],
                                             'Pulse')
                result = simplecommand(
                    encode_strconsole(
                        'net user "pulse" "%s" /ADD /COMMENT:"Pulse user with admin rights on the system" /PROFILEPATH:"%s"'
                        % (pulseuserpassword, pulseuserhome)))
                logging.getLogger().debug("Creation of pulse user: %s" %
                                          result)
            authorized_keys_path = os.path.join(os.environ["ProgramFiles"],
                                                'Pulse', '.ssh',
                                                'authorized_keys')
            if not os.path.isdir(os.path.dirname(authorized_keys_path)):
                os.makedirs(os.path.dirname(authorized_keys_path), 0700)
            if not os.path.isfile(authorized_keys_path):
                file_put_contents(authorized_keys_path, "")
            currentdir = os.getcwd()
            os.chdir(os.path.join(os.environ["ProgramFiles"], 'OpenSSH'))
            result = simplecommand(
                encode_strconsole(
                    'powershell -ExecutionPolicy Bypass -Command ". .\FixHostFilePermissions.ps1 -Confirm:$false"'
                ))
            os.chdir(currentdir)
            logging.getLogger().debug(
                "Reset of permissions on ssh keys and folders: %s" % result)
        elif sys.platform.startswith('darwin'):
            authorized_keys_path = os.path.join(
                os.path.join(os.path.expanduser('~pulse'), '.ssh',
                             'authorized_keys'))
        else:
            return

        authorized_keys_content = file_get_contents(authorized_keys_path)
        if not data['key'] in authorized_keys_content:
            #add en append la key dans le fichier
            file_put_contents_w_a(authorized_keys_path, data['key'], "a")
            logging.getLogger().debug("install key ARS [%s]" % message['from'])
            if sessionid.startswith("command"):
                notify = "Notify | QuickAction"
            else:
                notify = "Deployment | Cluster | Notify"

            objectxmpp.xmpplog('INSTALL key ARS %s on AM %s' %
                               (message['from'], objectxmpp.boundjid.bare),
                               type='deploy',
                               sessionname=sessionid,
                               priority=-1,
                               action="",
                               who=objectxmpp.boundjid.bare,
                               how="",
                               why="",
                               module=notify,
                               date=None,
                               fromuser="",
                               touser="")
        else:
            logging.getLogger().warning(
                "key ARS [%s] : is already installed." % message['from'])
            #if on veut que ce soit notifier dans le deployement
            #if sessionid.startswith("command"):
            #notify = "Notify | QuickAction"
            #else:
            #notify = "Deployment | Cluster | Notify"
            #objectxmpp.xmpplog("key ARS [%s] : is already installed on AM %s."%(message['from'], objectxmpp.boundjid.bare),
            #type = 'deploy',
            #sessionname = sessionid,
            #priority = -1,
            #action = "",
            #who = objectxmpp.boundjid.bare,
            #how = "",
            #why = "",
            #module = notify,
            #date = None ,
            #fromuser = "",
            #touser = "")
    else:
        logging.getLogger().debug(
            "#######################################################")
        logging.getLogger().debug(
            "##############AGENT RELAY SERVER KEY MACHINE###########")
        logging.getLogger().debug(
            "#######################################################")
        # send keupub ARM TO AM
        # ARM ONLY DEBIAN
        # lit la key Public
        key = ""
        key = file_get_contents(os.path.join('/', 'root', '.ssh',
                                             'id_rsa.pub'))
        if key == "":
            dataerreur['data'][
                'msg'] = "%s : KEY ARM MISSING" % dataerreur['data']['msg']
            objectxmpp.send_message_agent(message['from'],
                                          dataerreur,
                                          mtype='chat')
            return
        if not 'jidAM' in data:
            dataerreur['data'][
                'msg'] = "%s JID AM MISSING" % dataerreur['data']['msg']
            objectxmpp.send_message_agent(message['from'],
                                          dataerreur,
                                          mtype='chat')
            return

        datasend = {
            "action": action,
            "data": {
                "key": key
            },
            'sessionid': sessionid,
            'ret': 255,
            'base64': False
        }

        objectxmpp.send_message_agent(data['jidAM'], datasend, mtype='chat')
Exemplo n.º 4
0
def action(objectxmpp, action, sessionid, data, message, dataerreur):
    logging.getLogger().debug(
        "###################################################")
    logging.getLogger().debug("call %s from %s" % (plugin, message['from']))
    logging.getLogger().debug(
        "###################################################")
    print json.dumps(data, indent=4)
    #--------------------search si besoin d'un reverse ssh------------------------------------
    #
    logger.debug("Install key ARS in authorized_keys on agent machine")
    body = {
        'action': 'installkey',
        'sessionid': sessionid,
        'data': {
            'jidAM': data['jidmachine']
        }
    }
    objectxmpp.send_message(mto=objectxmpp.boundjid.bare,
                            mbody=json.dumps(body),
                            mtype='chat')
    reversessh = False
    localport = 22
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(5.0)
    try:
        sock.connect((data['ipmachine'], 22))
        reversessh = False
        #create file for command scp remote to remote direct connection remote
        cretefileconfigrescp = "Host %s\nPort %s\nHost %s\nPort %s\n" % (
            data['ipmaster'], paramglobal['portsshmaster'], data['ipmachine'],
            localport)
    except socket.error:
        localport = randint(49152, 65535)
        reversessh = True
        #send create reverse ssh to machine
        objectxmpp.xmpplog('Call Reverse ssh for nat machine %s' %
                           data['hostname'],
                           type='noset',
                           sessionname=sessionid,
                           priority=-1,
                           action="",
                           who=objectxmpp.boundjid.bare,
                           how="",
                           why="",
                           module="Notify | Download | Transfertfile",
                           date=None,
                           fromuser="",
                           touser="")
        cretefileconfigrescp = "Host %s\nPort %s\nHost %s\nPort %s\n" % (
            data['ipmaster'], paramglobal['portsshmaster'], "localhost",
            localport)
        datareversessh = {
            'action': 'reverse_ssh_on',
            'sessionid': sessionid,
            'data': {
                'request': 'askinfo',
                'port': localport,
                'host': data['host'],
                'remoteport': paramglobal['remoteport'],
                'reversetype': 'R',
                'options': 'createreversessh',
                'persistance': 'Downloadfile'
            },
            'ret': 0,
            'base64': False
        }
        #self call plugin creation reverse ssh for host data['host']
        objectxmpp.send_message(mto=message['to'],
                                mbody=json.dumps(datareversessh),
                                mtype='chat')
        #time for create reverse ssh
        time.sleep(paramglobal['timeupreverssh'])
    finally:
        sock.close()
    file_put_contents(paramglobal['filetmpconfigssh'], cretefileconfigrescp)
    ##scp file from 2 hosts
    #------------------------------------------------- ssh------------------------------------
    #####
    # Scp les fichiers et repertoires.
    # on commence par les repertoires.

    data['path_src_machine_dir'] = data['path_src_machine_dir'] + data[
        'path_src_machine_file']
    for directory in data['path_src_machine_dir']:
        if reversessh == False:
            if str(data['osmachine']).startswith('Linux'):
                source = create_path(type="linux",
                                     host="pulseuser",
                                     ipordomain=data['ipmachine'],
                                     path=r'%s' % directory)
            elif str(data['osmachine']).startswith('darwin'):
                source = create_path(type="linux",
                                     host="pulse",
                                     ipordomain=data['ipmachine'],
                                     path=r'%s' % directory)
            else:
                source = create_path(type="windows",
                                     host="pulse",
                                     ipordomain=data['ipmachine'],
                                     path=r'%s' % directory)
        else:
            if str(data['osmachine']).startswith('Linux'):
                source = create_path(type="linux",
                                     host="pulseuser",
                                     ipordomain="localhost",
                                     path=r'%s' % directory)
            elif str(data['osmachine']).startswith('darwin'):
                source = create_path(type="linux",
                                     host="pulse",
                                     ipordomain="localhost",
                                     path=r'%s' % directory)
            else:
                source = create_path(type="windows",
                                     host="pulse",
                                     ipordomain="localhost",
                                     path=r'%s' % directory)

        dest = create_path(type="linux",
                           host="root",
                           ipordomain=data['ipmaster'],
                           path=data['path_dest_master'])
        if reversessh == False:
            command = scpfile(source, dest, objectxmpp, sessionid)
        else:
            # initialise se cp
            command = scpfile(source,
                              dest,
                              objectxmpp,
                              sessionid,
                              reverbool=True)

        print "source %s" % source
        print "dest %s" % dest
        print "command %s" % command

        #time.sleep(paramglobal['timeupreverssh'])

        print json.dumps(data, indent=4)
        print "----------------------------"
        print "exec command\n %s" % command
        print "----------------------------"
        print "----------------------------"
        objectxmpp.xmpplog('Copy file %s from machine %s to Master' %
                           (os.path.basename(directory), data['hostname']),
                           type='noset',
                           sessionname=sessionid,
                           priority=-1,
                           action="",
                           who=objectxmpp.boundjid.bare,
                           how="",
                           why="",
                           module="Notify | Download | Transfertfile",
                           date=None,
                           fromuser="",
                           touser="")

        z = simplecommand(command)
        print z['result']
        print z['code']
        print "----------------------------"

        if z['code'] != 0:
            objectxmpp.xmpplog('error Copy file %s from machine %s to Master' %
                               (os.path.basename(directory), data['hostname']),
                               type='noset',
                               sessionname=sessionid,
                               priority=-1,
                               action="",
                               who=objectxmpp.boundjid.bare,
                               how="",
                               why="",
                               module="Notify | Download",
                               date=None,
                               fromuser="",
                               touser="")
            objectxmpp.xmpplog('error : %s' % z['result'],
                               type='noset',
                               sessionname=sessionid,
                               priority=-1,
                               action="",
                               who=objectxmpp.boundjid.bare,
                               how="",
                               why="",
                               module="Notify | Download | Transfertfile",
                               date=None,
                               fromuser="",
                               touser="")
        else:
            objectxmpp.xmpplog(
                'success Copy file %s from machine %s to Master' %
                (os.path.basename(directory), data['hostname']),
                type='noset',
                sessionname=sessionid,
                priority=-1,
                action="",
                who=objectxmpp.boundjid.bare,
                how="",
                why="",
                module="Notify | Download | Transfertfile",
                date=None,
                fromuser="",
                touser="")
            # chang mod file dest
            tabdest = str(dest).split('"')
            cmd = "ssh %s -o IdentityFile=/root/.ssh/id_rsa "\
                        "-o StrictHostKeyChecking=no "\
                        "-o UserKnownHostsFile=/dev/null "\
                        "-o Batchmode=yes "\
                        "-o PasswordAuthentication=no "\
                        "-o ServerAliveInterval=10 "\
                        "-o CheckHostIP=no "\
                        "-o ConnectTimeout=10 'chmod 777 -R %s'"%(str(tabdest[0][:-1]),os.path.dirname(tabdest[1]))
            objectxmpp.xmpplog('cmd : ' + cmd,
                               type='noset',
                               sessionname=sessionid,
                               priority=-1,
                               action="",
                               who=objectxmpp.boundjid.bare,
                               how="",
                               why="",
                               module="Notify | Download | Transfertfile",
                               date=None,
                               fromuser="",
                               touser="")
            z = simplecommand(cmd)
            if z['code'] == 0:
                objectxmpp.xmpplog('result transfert : ' +
                                   '\n'.join(z['result']),
                                   type='noset',
                                   sessionname=sessionid,
                                   priority=-1,
                                   action="",
                                   who=objectxmpp.boundjid.bare,
                                   how="",
                                   why="",
                                   module="Notify | Download | Transfertfile",
                                   date=None,
                                   fromuser="",
                                   touser="")
                objectxmpp.xmpplog('change mode 777 for file %s ' %
                                   (os.path.basename(directory)),
                                   type='noset',
                                   sessionname=sessionid,
                                   priority=-1,
                                   action="",
                                   who=objectxmpp.boundjid.bare,
                                   how="",
                                   why="",
                                   module="Notify | Download | Transfertfile",
                                   date=None,
                                   fromuser="",
                                   touser="")
            else:
                objectxmpp.xmpplog('error change mode 777 for file %s : %s' %
                                   (os.path.basename(directory), z['result']),
                                   type='noset',
                                   sessionname=sessionid,
                                   priority=-1,
                                   action="",
                                   who=objectxmpp.boundjid.bare,
                                   how="",
                                   why="",
                                   module="Notify | Download | Transfertfile",
                                   date=None,
                                   fromuser="",
                                   touser="")
Exemplo n.º 5
0
def action(objectxmpp, action, sessionid, data, message, dataerreur):
    logger.debug("###################################################")
    logger.debug("call %s from %s" % (plugin, message['from']))
    logger.debug("###################################################")
    if "subaction" in data:
        if data['subaction'] == "descriptor":
            difference = {}
            supprimefileimage = []
            file_put_contents(
                os.path.join(objectxmpp.pathagent, "BOOL_UPDATE_AGENT"),
                "use file boolean update. enable verify update.")
            if 'version' in data['descriptoragent']:
                #copy version agent master to image
                vers = (data['descriptoragent']['version']).replace(
                    "\n", "").replace("\r", "").strip()
                file_put_contents(
                    os.path.join(objectxmpp.img_agent, "agentversion"), vers)
                file_put_contents(
                    os.path.join(objectxmpp.pathagent, "agentversion"), vers)
            # on genere descriptor actuel de l image
            objdescriptorimage = Update_Remote_Agent(objectxmpp.img_agent)
            descriptorimage = objdescriptorimage.get_md5_descriptor_agent()
            # on recoit le nouveau descripteur depuis base de l'agent.
            objectxmpp.descriptor_master = data['descriptoragent']

            # il faut supprimer les fichier dans l'image qui ont ete supprimer dans la base.
            # on recherche les differences entre base de l'agent et l'image de la base.

            for directory_agent in objectxmpp.descriptor_master:
                if directory_agent in [
                        "fingerprint", "version", "version_agent"
                ]:
                    continue

                diff, supp = search_action_on_agent_cp_and_del(
                    objectxmpp.descriptor_master[directory_agent],
                    descriptorimage[directory_agent])
                if directory_agent == "program_agent":
                    dirname = ""
                elif directory_agent == "lib_agent":
                    dirname = "lib"
                elif directory_agent == "script_agent":
                    dirname = "script"
                supp2 = [
                    os.path.join(objectxmpp.img_agent, dirname, x)
                    for x in supp
                ]
                difference[directory_agent] = diff
                supprimefileimage.extend(supp2)
                for delfile in supp2:
                    try:
                        os.remove(delfile)
                    except:
                        pass
            logger.debug("delete unnecessary files in image %s" %
                         json.dumps(supprimefileimage, indent=4))

            if len(supprimefileimage) != 0:
                #on genere le descripteur de l'image, on a supprimer les fichiers qui sont dans l'image et pas dans la l'agent base
                objdescriptorimage = Update_Remote_Agent(objectxmpp.img_agent)
                descriptorimage = objdescriptorimage.get_md5_descriptor_agent()

                objectxmpp.Update_Remote_Agentlist = Update_Remote_Agent(
                    objectxmpp.pathagent)
                descriptoragent = objectxmpp.Update_Remote_Agentlist.get_md5_descriptor_agent(
                )

                # on regarde si il y a des diff entre img, base, et agent
                if (objectxmpp.descriptor_master['fingerprint'] == descriptorimage['fingerprint']) and\
                   ( objectxmpp.descriptor_master['fingerprint'] != descriptoragent['fingerprint']):
                    # on peut mettre a jour l'agent suite a une suppression de fichier inutile
                    objectxmpp.reinstall_agent()

            logger.debug("to updating files %s" %
                         json.dumps(difference, indent=4))
            try:
                # on demande les fichiers differents pour la mise a jour de l'image
                if len(difference['program_agent']) != 0 or \
                    len(difference['lib_agent']) != 0 or \
                        len(difference['script_agent']) != 0:
                    # demande de mise à jour.
                    # todo send message only files for updating.
                    msgupdate_me = {
                        'action': "result%s" % action,
                        'sessionid': sessionid,
                        'data': {
                            "subaction": "update_me",
                            "descriptoragent": difference
                        },
                        'ret': 0,
                        'base64': False
                    }
                    # renvoi descriptor pour demander la mise a jour
                    agent_installor = "master@pulse/MASTER"
                    if 'ars_update' in data and data['ars_update'] != "":
                        agent_installor = data['ars_update']
                        msgupdate_me['action'] = "relayupdateagent"
                    # temporisation pour envoi demande attente entre
                    # time.sleep(randint(plugin['waittingmin'],plugin['waittingmax']))
                    objectxmpp.send_message(mto=agent_installor,
                                            mbody=json.dumps(msgupdate_me),
                                            mtype='chat')
                    return
                else:
                    objdescriptorimage = Update_Remote_Agent(
                        objectxmpp.img_agent)
                    descriptorimage = objdescriptorimage.get_md5_descriptor_agent(
                    )

                    objectxmpp.Update_Remote_Agentlist = Update_Remote_Agent(
                        objectxmpp.pathagent)
                    descriptoragent = objectxmpp.Update_Remote_Agentlist.get_md5_descriptor_agent(
                    )

                    # on regarde si il y a des diff entre img, base, et agent
                    if (objectxmpp.descriptor_master['fingerprint'] == descriptorimage['fingerprint']) and\
                    ( objectxmpp.descriptor_master['fingerprint'] != descriptoragent['fingerprint']):
                        # on peut mettre a jour l'agent suite a une suppression de fichier inutile
                        objectxmpp.reinstall_agent()
                    return
            except Exception as e:
                logger.error(str(e))
                traceback.print_exc(file=sys.stdout)
        elif data['subaction'] == "install_lib_agent":
            if not ('namescript' in data and data['namescript'] != ""):
                logger.error("update agent install lib name missing")
                return
            else:
                content = zlib.decompress(base64.b64decode(data['content']))
                dump_file_in_img(objectxmpp, data['namescript'], content,
                                 "lib_agent")
        elif data['subaction'] == "install_program_agent":
            if not ('namescript' in data and data['namescript'] != ""):
                logger.error("update agent install program name missing")
                return
            else:
                content = zlib.decompress(base64.b64decode(data['content']))
                dump_file_in_img(objectxmpp, data['namescript'], content,
                                 "program_agent")
        elif data['subaction'] == "install_script_agent":
            if not ('namescript' in data and data['namescript'] != ""):
                logger.error("updateagent install script name missing")
                return
            else:
                content = zlib.decompress(base64.b64decode(data['content']))
                dump_file_in_img(objectxmpp, data['namescript'], content,
                                 "script_agent")
        elif data['subaction'] == "ars_update":
            #verify agent type relayserver.
            logger.debug( "recu update agent from %s"\
                  " for update agent %s "\
                      "[ descriptor %s ]"%( message['from'],
                                            data['jidagent'],
                                            data['descriptoragent']))
            senddescriptormd5(objectxmpp, data)