def _get_arp_entries_linux(): arp_cmd = ["/sbin/arp", "-an"] arp_pipe = lib_common.SubProcPOpen(arp_cmd) arp_last_output, arp_err = arp_pipe.communicate() # TODO/ Should be a generator ! # Converts to string for Python3. asstr = arp_last_output.decode("utf-8") lines = asstr.split('\n') for lin in lines: tmp_split = re.findall(r"[^ ]+", lin) if len(tmp_split) < 4: continue if tmp_split[4] == "on": lin_split = [tmp_split[1][1:-1], tmp_split[3], "", tmp_split[5]] elif tmp_split[5] == "on": lin_split = [tmp_split[1][1:-1], tmp_split[3], "", tmp_split[6]] else: continue if lin_split[1] == "<incomplete>": lin_split[1] = "" logging.debug("Split=%s", str(lin_split)) yield lin_split
def GetSLPServices(service_name): dict_services = {} cmd_slp_tool = [ "slptool", 'findsrvs', 'service:' + service_name, ] resu_p_open = lib_common.SubProcPOpen(cmd_slp_tool) out_stream_slp_tool, err_stream_slp_tool = resu_p_open.communicate() split_resu_slp_tool = out_stream_slp_tool.split("\n") for lin_resu_slp_tool in split_resu_slp_tool: logging.debug("GetSLPServices serviceName=%s lin_resu_slp_tool=%s", service_name, lin_resu_slp_tool) # service:survol:http://mymachine:8000/survol/entity.py,65535 # service:wbem:http://mymachine,65535 mtch_spl_tool = re.match(r'service:[^:]*:([^,]*)(.*)', lin_resu_slp_tool) if mtch_spl_tool: slp_host = mtch_spl_tool.group(1) slp_attrs = GetSLPAttributes(service_name, slp_host) dict_services[slp_host] = slp_attrs else: logging.debug("No match:%s", lin_resu_slp_tool) return dict_services
def GetSLPAttributes(serviceName, slpHost): dictAttributes = {} cmdSlpFindAttrs = [ "slptool", 'findattrs', 'service:%s:%s' % (serviceName, slpHost), ] resuFindAttrs = lib_common.SubProcPOpen(cmdSlpFindAttrs) (outStreamFindAttrs, errStreamFindAttrs) = resuFindAttrs.communicate() splitResuFindAttrs = outStreamFindAttrs.split("\n") for linResuFindAttrs in splitResuFindAttrs: DEBUG("GetSLPAttributes slpHost=%s linResuFindAttrs=%s", slpHost, linResuFindAttrs) # service:survol:http://rchateau-hp:8000/survol/entity.py,65535 # service:wbem:http://rchateau-hp,65535 mtchFindAttrs = re.match(r'\(([^=]*)=([^)]*)\)', linResuFindAttrs) if mtchFindAttrs: slpAttrKey = mtchFindAttrs.group(1) slpAttrVal = mtchFindAttrs.group(2) dictAttributes[slpAttrKey] = slpAttrVal else: DEBUG("No match for attributes:%s", linResuFindAttrs) return dictAttributes
def GetSLPAttributes(service_name, slp_host): dict_attributes = {} cmd_slp_find_attrs = [ "slptool", 'findattrs', 'service:%s:%s' % (service_name, slp_host), ] resu_find_attrs = lib_common.SubProcPOpen(cmd_slp_find_attrs) out_stream_find_attrs, err_stream_find_attrs = resu_find_attrs.communicate( ) split_resu_find_attrs = out_stream_find_attrs.split("\n") for lin_resu_find_attrs in split_resu_find_attrs: logging.debug("GetSLPAttributes slpHost=%s lin_resu_find_attrs=%s", slp_host, lin_resu_find_attrs) # service:survol:http://mymachine:8000/survol/entity.py,65535 # service:wbem:http://mymachine,65535 mtch_find_attrs = re.match(r'\(([^=]*)=([^)]*)\)', lin_resu_find_attrs) if mtch_find_attrs: slp_attr_key = mtch_find_attrs.group(1) slp_attr_val = mtch_find_attrs.group(2) dict_attributes[slp_attr_key] = slp_attr_val else: logging.debug("No match for attributes:%s", lin_resu_find_attrs) return dict_attributes
def Main(): # This is similar to the script displaying shares for a given SMB server. # Maybe in the future it will have to be different, no idea now. cgiEnv = lib_common.CgiEnv() hostName = cgiEnv.GetId() grph = cgiEnv.GetGraph() nodeSmbShr = lib_common.gUriGen.SmbServerUri( hostName ) smbclient_cmd = [ "smbclient", "-L", hostName, "-N" ] try: smbclient_pipe = lib_common.SubProcPOpen(smbclient_cmd) # except WindowsError: except Exception: lib_common.ErrorMessageHtml("Cannot run command:"+" ".join(smbclient_cmd)) ( smbclient_last_output, smbclient_err ) = smbclient_pipe.communicate() lines = smbclient_last_output.split('\n') modeSharedList = False for lin in lines: # print( "l="+lin+"<br>" ) # Normally this is only the first line # session setup failed: NT_STATUS_LOGON_FAILURE mtch_net = re.match(r"^.*(NT_STATUS_.*)", lin) if mtch_net: # print("OK<br>") lib_common.ErrorMessageHtml("Smb failure: " + mtch_net.group(1) + " to smb share:" + nodeSmbShr) if re.match(r"^\sServer\s+Comment", lin): modeSharedList = False continue if re.match(r"^\sWorkgroup\s+Master", lin): modeSharedList = False continue if re.match(r"^\sSharename\s+Type\s+Comment", lin): modeSharedList = True continue if re.match (r"^\s*----+ +---+ +", lin): continue # print("m="+str(modeSharedList)) # print("l="+lin) if modeSharedList: # The type can be "Disk", "Printer" or "IPC". mtch_share = re.match(r"^\s+([^\s]+)\s+Disk\s+(.*)$", lin) if mtch_share: shareName = mtch_share.group(1) shareNode = lib_common.gUriGen.SmbShareUri( "//" + hostName + "/" + shareName ) grph.add( ( nodeSmbShr, pc.property_smbshare, shareNode ) ) cgiEnv.OutCgiRdf()
def GetSLPServices(serviceName): dictServices = {} cmdSlpTool = [ "slptool", 'findsrvs', 'service:' + serviceName, ] resuPOpen = lib_common.SubProcPOpen(cmdSlpTool) (outStreamSlpTool, errStreamSlpTool) = resuPOpen.communicate() splitResuSlpTool = outStreamSlpTool.split("\n") for linResuSlpTool in splitResuSlpTool: DEBUG("GetSLPServices serviceName=%s linResuSlpTool=%s", serviceName, linResuSlpTool) # service:survol:http://rchateau-hp:8000/survol/entity.py,65535 # service:wbem:http://rchateau-hp,65535 mtchSplTool = re.match(r'service:[^:]*:([^,]*)(.*)', linResuSlpTool) if mtchSplTool: slpHost = mtchSplTool.group(1) slpAttrs = GetSLPAttributes(serviceName, slpHost) dictServices[slpHost] = slpAttrs else: DEBUG("No match:%s", linResuSlpTool) return dictServices
def GetArpEntriesWindows(): arp_cmd = ["arp", "-a"] arp_pipe = lib_common.SubProcPOpen(arp_cmd) (arp_last_output, arp_err) = arp_pipe.communicate() # Converts to string for Python3. asstr = arp_last_output.decode("utf-8") lines = asstr.split('\n') for lin in lines: # Maybe should check if other interfaces ?? # Maybe should create the entity "network interface", # instead of this confusion between machines and addresses. # ['255.255.255.255', 'ff-ff-ff-ff-ff-ff', 'static', '\\r'] linSplit = re.findall(r"[^ ]+", lin) # sys.stderr.write("GetArpEntriesWindows Split=%s\n"%str(linSplit)) # Probably not the best test. if len(linSplit) != 4: continue if linSplit[0] == "Interface:": continue # Network interface. linSplit.append("") yield (linSplit)
def GetArpEntriesLinux(): arp_cmd = ["/sbin/arp", "-an"] arp_pipe = lib_common.SubProcPOpen(arp_cmd) (arp_last_output, arp_err) = arp_pipe.communicate() # TODO/ Should be a generator ! # Converts to string for Python3. asstr = arp_last_output.decode("utf-8") lines = asstr.split('\n') for lin in lines: tmpSplit = re.findall(r"[^ ]+", lin) if len(tmpSplit) < 4: continue if tmpSplit[4] == "on": linSplit = [tmpSplit[1][1:-1], tmpSplit[3], "", tmpSplit[5]] elif tmpSplit[5] == "on": linSplit = [tmpSplit[1][1:-1], tmpSplit[3], "", tmpSplit[6]] else: continue if linSplit[1] == "<incomplete>": linSplit[1] = "" sys.stderr.write("Split=%s\n" % str(linSplit)) yield (linSplit)
def Main(): cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() propPidPath = lib_common.MakeProp("Process") propType = lib_common.MakeProp("Type") propState = lib_common.MakeProp("State") propINode = lib_common.MakeProp("INode") args = [ "netstat", '-a', '--unix', '-p', ] pOpNetstat = lib_common.SubProcPOpen(args) (netstat_last_output, netstat_err) = pOpNetstat.communicate() asstr = netstat_last_output.decode("utf-8") DEBUG("assstr:%s", asstr) # Do not read the header on the first four lines. for lin in asstr.split('\n')[4:]: try: sockType = lin[25:36].strip() # sys.stderr.write("sockType %s\n"%sockType) sockState = lin[36:50].strip() # sys.stderr.write("sockState %s\n"%sockState) sockINode = lin[50:59].strip() # sys.stderr.write("sockINode %s\n"%sockINode) sockPath = lin[80:].strip() except: WARNING("Cannot parse:%s", lin) continue if sockPath: nodePath = lib_common.gUriGen.FileUri(sockPath) grph.add((nodePath, propType, lib_common.NodeLiteral(sockType))) grph.add((nodePath, propState, lib_common.NodeLiteral(sockState))) grph.add((nodePath, propINode, lib_common.NodeLiteral(sockINode))) sockPidProg = lin[59:80].strip() if sockPidProg not in ["-", ""]: sockPidProgSplit = sockPidProg.split("/") sockPid = sockPidProgSplit[0] # sys.stderr.write("sockPid %s\n"%sockPid) # Not used, and index error on Python 3. # sockProgNam = sockPidProgSplit[1] nodeProc = lib_common.gUriGen.PidUri(sockPid) if sockPath: grph.add((nodePath, propPidPath, nodeProc)) # grph.add( ( nodeProc, pc.property_information, lib_common.NodeLiteral(sockProgNam) ) ) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() # TODO: Should test Linux instead ? if lib_util.isPlatformWindows: lib_common.ErrorMessageHtml("smbtree not available on Windows") grph = cgiEnv.GetGraph() smbtree_cmd = ["smbtree", "-N", "-b", "--debuglevel=0"] smbtree_pipe = lib_common.SubProcPOpen(smbtree_cmd) (smbtree_last_output, smbtree_err) = smbtree_pipe.communicate() lines = smbtree_last_output.split('\n') for lin in lines: # print(lin) tst_domain = re.match(r'^([A-Z]+) *', lin) if tst_domain: domain = tst_domain.group(1) # print( "Domain=" + tst_domain.group(1) ) continue tst_machine = re.match(r'^[ \t]+\\\\([A-Z0-9_]+)[ \t]+([^\t].*)', lin) if tst_machine: machine = tst_machine.group(1) addr = NetBiosLookup(machine) # print( "Machine=" + tst_machine.group(1) + " Comment=" + tst_machine.group(2) ) nodeHost = lib_common.gUriGen.HostnameUri(addr) grph.add((nodeHost, pc.property_netbios, lib_common.gUriGen.SmbServerUri(machine))) # TODO: Maybe will create a specific node for a domain. grph.add((nodeHost, pc.property_domain, lib_common.gUriGen.SmbDomainUri(domain))) continue tst_share = re.match( r'^[ \t]+\\\\([A-Z0-9_]+)\\([^ \t]+)[ \t]+([^\t].*)', lin) if tst_share: machine = tst_share.group(1) share = tst_share.group(2) shareNode = lib_common.gUriGen.SmbShareUri("//" + machine + "/" + share) grph.add((nodeHost, pc.property_smbshare, shareNode)) continue # print( smbtree_last_output ) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() userNameWithHost = cgiEnv.GetId() if not lib_util.isPlatformLinux: lib_common.ErrorMessageHtml("id command on Linux only") # Usernames have the syntax user@host userSplit = userNameWithHost.split('@') userName = userSplit[0] if len(userSplit) > 1: userHost = userSplit[1] if userHost != lib_util.currentHostname: # TODO: Should interrogate other host with "finger" protocol. lib_common.ErrorMessageHtml( "Cannot get user properties on different host:" + userHost) if not userName: lib_common.ErrorMessageHtml( "Linux username should not be an empty string") grph = cgiEnv.GetGraph() userNode = lib_common.gUriGen.UserUri(userName) id_cmd = ["id", userName] id_pipe = lib_common.SubProcPOpen(id_cmd) (id_last_output, id_err) = id_pipe.communicate() lines = id_last_output.split('\n') sys.stderr.write("id=" + userName + " lines=" + str(lines) + "\n") sys.stderr.write("Lines=" + str(len(lines)) + "\n") # $ id rchateau # uid=500(rchateau) gid=500(guest) groupes=500(guest),81(audio) firstLine = lines[0] sys.stderr.write("First=" + firstLine + "\n") firstSplit = SplitId(firstLine) userId = ParseIdNam(firstSplit[0])[0] grph.add((userNode, pc.property_userid, lib_common.NodeLiteral(userId))) for grpStr in firstSplit[2].split(','): (grpId, grpNam) = ParseIdNam(grpStr) grpNode = lib_common.gUriGen.GroupUri(grpNam) grph.add((grpNode, pc.property_groupid, lib_common.NodeLiteral(grpId))) grph.add((userNode, pc.property_group, grpNode)) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.ScriptEnvironment() grph = cgiEnv.GetGraph() net_share_cmd = ["net", "share"] net_share_pipe = lib_common.SubProcPOpen(net_share_cmd) net_share_last_output, net_share_err = net_share_pipe.communicate() # Converts to string for Python3. as_str = net_share_last_output.decode("utf-8") lines = as_str.split('\n') seen_hyphens = False for lin in lines: if re.match(".*-------.*", lin): seen_hyphens = True continue if re.match(".*The command completed successfully.*", lin): break if not seen_hyphens: continue tst_share = re.match(r'^([A-Za-z0-9_$]+) +([^ ]+).*', lin) if not tst_share: continue shr_nam = tst_share.group(1) # Nasty formatting of "NET SHARE" command. if len(lin) >= 45: # There is a remark or a very long resource. if lin[44] == ' ': # Character just before remark is a space. shr_res = lin[13:44].rstrip() else: shr_res = lin[13:] else: shr_res = lin[13:] share_node = lib_uris.gUriGen.SmbShareUri(shr_nam) grph.add((lib_common.nodeMachine, pc.property_smbshare, share_node)) # mount_node = lib_uris.gUriGen.FileUri( "//" + lib_util.currentHostname + "/" + shr_res ) shr_res = shr_res.strip() shr_res = lib_util.standardized_file_path(shr_res) mount_node = lib_uris.gUriGen.DirectoryUri(shr_res) grph.add((share_node, pc.property_smbmount, mount_node)) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() userNameWithHost = cgiEnv.GetId() # Usernames have the syntax user@host user_split = userNameWithHost.split('@') user_name = user_split[0] if len(user_split) > 1: user_host = user_split[1] if user_host != lib_util.currentHostname: # TODO: Should interrogate other host with "finger" protocol. lib_common.ErrorMessageHtml( "Cannot get user properties on different host:" + user_host) if not user_name: lib_common.ErrorMessageHtml( "Linux username should not be an empty string") grph = cgiEnv.GetGraph() user_node = lib_common.gUriGen.UserUri(user_name) # It runs this Linux command which returns a single line. id_cmd = ["id", user_name] id_pipe = lib_common.SubProcPOpen(id_cmd) (id_last_output, id_err) = id_pipe.communicate() lines = id_last_output.split(b'\n') sys.stderr.write("lines=%s\n" % lines) DEBUG("id=" + user_name + " lines=" + str(lines)) # $ id my_user # uid=500(my_user) gid=500(guest) groupes=500(guest),81(audio) first_line = lines[0] first_split = split_id(first_line) user_id = parse_id_name(first_split[0])[0] grph.add((user_node, pc.property_userid, lib_common.NodeLiteral(user_id))) for grp_str in first_split[2].split(b','): sys.stderr.write("grp_str=%s\n" % grp_str) (group_id, group_name) = parse_id_name(grp_str) grpNode = lib_common.gUriGen.GroupUri(group_name) grph.add( (grpNode, pc.property_groupid, lib_common.NodeLiteral(group_id))) grph.add((user_node, pc.property_group, grpNode)) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.ScriptEnvironment() smb_server = cgiEnv.GetId() grph = cgiEnv.GetGraph() node_smb_shr = lib_uris.gUriGen.SmbServerUri(smb_server) smbclient_cmd = ["smbclient", "-L", smb_server, "-N"] smbclient_pipe = lib_common.SubProcPOpen(smbclient_cmd) smbclient_last_output, smbclient_err = smbclient_pipe.communicate() lines = smbclient_last_output.split('\n') mode_shared_list = False for lin in lines: # Normally this is only the first line # session setup failed: NT_STATUS_LOGON_FAILURE mtch_net = re.match(r"^.*(NT_STATUS_.*)", lin) if mtch_net: lib_common.ErrorMessageHtml("Smb failure: " + mtch_net.group(1) + " to smb share:" + smb_server) if re.match(r"^\sServer\s+Comment", lin): mode_shared_list = False continue if re.match(r"^\sWorkgroup\s+Master", lin): mode_shared_list = False continue if re.match(r"^\sSharename\s+Type\s+Comment", lin): mode_shared_list = True continue if re.match(r"^\s*----+ +---+ +", lin): continue if mode_shared_list: # The type can be "Disk", "Printer" or "IPC". mtch_share = re.match(r"^\s+([^\s]+)\s+Disk\s+(.*)$", lin) if mtch_share: share_name = mtch_share.group(1) share_node = lib_uris.MachineBox(smb_server).SmbShareUri( share_name) grph.add((node_smb_shr, pc.property_smbshare, share_node)) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.ScriptEnvironment() grph = cgiEnv.GetGraph() # C:\Users\the_user>wmic logicaldisk get name,description,ProviderName # Description Name ProviderName # Local Fixed Disk C: # Local Fixed Disk D: # Local Fixed Disk E: # CD-ROM Disc F: # Network Connection Y: \\192.168.1.115\EmuleDownload # Network Connection Z: \\192.168.1.61\Public drivelist = lib_common.SubProcPOpen('wmic logicaldisk get name,description,ProviderName') drivelisto, err = drivelist.communicate() strlist = drivelisto if lib_util.is_py3: strlist_str = str(strlist, encoding='utf8') else: strlist_str = str(strlist) drive_lines = strlist_str.split('\n') for lin in drive_lines[1:]: devtype = lin[0:18].strip() devname = lin[20:21] devprov = lin[22:].strip() # End of the list not interesting. if devtype == "": break if devtype != "Network Connection": continue dev_split = devprov.split('\\') host_name = dev_split[2] share_name = dev_split[3] share_box = lib_uris.MachineBox(host_name) remote_share_node = share_box.SmbShareUri(share_name) host_node = lib_uris.gUriGen.HostnameUri(host_name) # See net_use.py which creates the same type of output. Win32_NetworkConnection key is the disk name. connected_disk_node = lib_uris.gUriGen.Win32_NetworkConnectionUri(devname) connected_file_node = lib_uris.gUriGen.FileUri(devname) logging.debug("share_name=%s", share_name) logging.debug("share_box=%s", share_box) grph.add((connected_disk_node, pc.property_mount, remote_share_node)) grph.add((host_node, pc.property_smbshare, remote_share_node)) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() args = [ "nmap", '-oX', '-', '--script', "broadcast-netbios-master-browser", ] # The returned IP address is wrong when launched from a Windows machine where the DB is running. p = lib_common.SubProcPOpen(args) grph = cgiEnv.GetGraph() (nmap_last_output, nmap_err) = p.communicate() dom = xml.dom.minidom.parseString(nmap_last_output) # <script id="broadcast-netbios-master-browser" output="..."/> # TODO: Remove line "ip server domain" for aScript in dom.getElementsByTagName('script'): # output="
ip server domain
192.168.0.15 WDMYCLOUDMIRROR WORKGROUP
" anOutput = aScript.getAttributeNode('output').value.strip() sys.stderr.write("anOutput=%s\n" % str(anOutput)) arrSplit = [aWrd.strip() for aWrd in anOutput.split("\n")] sys.stderr.write("arrSplit=%s\n" % str(arrSplit)) theMachFull = arrSplit[1].strip() sys.stderr.write("theMachFull=%s\n" % str(theMachFull)) machSplit = re.split("[\t ]+", theMachFull) sys.stderr.write("machSplit=%s\n" % str(machSplit)) machIp = machSplit[0].strip() machNam = machSplit[1].strip() nameDomain = machSplit[2].strip() nodeHost = lib_common.gUriGen.HostnameUri(machNam) grph.add((nodeHost, lib_common.MakeProp("IP address"), lib_common.NodeLiteral(machIp))) grph.add((nodeHost, lib_common.MakeProp("Domain"), lib_common.NodeLiteral(nameDomain))) grph.add((nodeHost, pc.property_information, lib_common.NodeLiteral(arrSplit[0]))) cgiEnv.OutCgiRdf()
def AddFromSmbClient(grph, smbDir, smbShr, passWrd, rootNode): smbclient_cmd = ["smbclient", "-c", "ls", "-D", smbDir, smbShr, passWrd] # This print is temporary until we know how to display smb-shared files. sys.stderr.write("Command=%s\n" % str(smbclient_cmd)) smbclient_pipe = lib_common.SubProcPOpen(smbclient_cmd) (smbclient_last_output, smbclient_err) = smbclient_pipe.communicate() lines = smbclient_last_output.split('\n') for lin in lines: sys.stderr.write("l=" + lin + "\n") # Normally this is only the first line # session setup failed: NT_STATUS_LOGON_FAILURE mtch_net = re.match("^.*(NT_STATUS_.*)", lin) if mtch_net: # print("OK<br>") lib_common.ErrorMessageHtml("Smb failure: " + mtch_net.group(1) + " smbShr:" + smbShr + " smbDir:" + smbDir) # . D 0 Wed Jul 23 23:22:34 2014 # .. D 0 Sat Oct 19 00:25:58 2013 #Dumezil - Idees romaines.pdf 7389096 Fri Aug 27 14:00:44 2010 #02 Hubert Felix Thiefaine - Je Ne Sais Plus Quoi Faire Pour Te Decevoir.mp3 3679004 Sat Jun 5 09:06:45 2010 #fldigi.exe A 40177610 Sat Jun 29 00:20:46 2013 # My Playlists D 0 Wed May 1 14:14:55 2013 # Sample Music DR 0 Wed May 1 19:46:06 2013 regDate = '[A-Za-z]+ +[A-Za-z]+ +[0-9]+ +[0-9]+:[0-9]+:[0-9]+ +[0-9]+' regFull = '^(.*) ([0-9]+) +' + regDate tstFil = re.match(regFull, lin) if tstFil: filNam = tstFil.group(1)[2:] filSz = tstFil.group(2) filNam = SmbCleanupFilNam(filNam, filSz) sys.stderr.write("Fi=%s, Sz=%s\n" % (filNam, filSz)) filNod = lib_common.gUriGen.SmbFileUri(smbShr, smbDir + "/" + filNam) grph.add((rootNode, pc.property_directory, filNod))
def Main(): cgiEnv = lib_common.ScriptEnvironment() grph = cgiEnv.GetGraph() prop_pid_path = lib_common.MakeProp("Process") prop_type = lib_common.MakeProp("Type") prop_state = lib_common.MakeProp("State") prop_inode = lib_common.MakeProp("INode") args = [ "netstat", '-a', '--unix', '-p', ] pOpNetstat = lib_common.SubProcPOpen(args) netstat_last_output, netstat_err = pOpNetstat.communicate() asstr = netstat_last_output.decode("utf-8") # Do not read the header on the first four lines. for lin in asstr.split('\n')[4:]: try: sock_type = lin[25:36].strip() sock_state = lin[36:50].strip() sock_inode = lin[50:59].strip() sock_path = lin[80:].strip() except: logging.warning("Cannot parse:%s", lin) continue if sock_path: node_path = lib_uris.gUriGen.FileUri(sock_path) grph.add((node_path, prop_type, lib_util.NodeLiteral(sock_type))) grph.add((node_path, prop_state, lib_util.NodeLiteral(sock_state))) grph.add((node_path, prop_inode, lib_util.NodeLiteral(sock_inode))) sock_pid_prog = lin[59:80].strip() if sock_pid_prog not in ["-", ""]: sock_pid_prog_split = sock_pid_prog.split("/") sock_pid = sock_pid_prog_split[0] node_proc = lib_uris.gUriGen.PidUri(sock_pid) if sock_path: grph.add((node_path, prop_pid_path, node_proc)) cgiEnv.OutCgiRdf()
def NetBiosLookupHelper(machine): nmblookup_cmd = ["nmblookup", "--debuglevel=0", machine] nmblookup_pipe = lib_common.SubProcPOpen(nmblookup_cmd) nmblookup_last_output, nmblookup_err = nmblookup_pipe.communicate() lines = nmblookup_last_output.split('\n') mtch = re.match(r'^([^ \t]*)', lines[1]) if mtch: return mtch.group(1) return "0.0.0.0"
def RunGdbCommand(the_pid, command): tmpGdb = lib_common.TmpFile("gdbstack", "gdb") gdbFilNam = tmpGdb.Name gdbFil = open(gdbFilNam, "w") gdbFil.write(command + "\n") gdbFil.write("quit\n") gdbFil.close() # TODO: See python/__init__.py which also runs a gdb command. gdb_cmd = ["gdb", "-q", "-p", str(the_pid), "-x", gdbFilNam] DEBUG("gdb command=%s", " ".join(gdb_cmd)) try: gdb_pipe = lib_common.SubProcPOpen(gdb_cmd) #except FileNotFoundError: # lib_common.ErrorMessageHtml("gdb is not available") except Exception: exc = sys.exc_info()[1] lib_common.ErrorMessageHtml("Gdb:" + str(exc)) # TODO: How can we get the stderr message: "ptrace: Operation not permitted." which comes after "Attaching to process 6063" ???? (gdb_last_output, gdb_err) = gdb_pipe.communicate() resu = [] # Removes the heading information and the lines beginning with a prompt. # [rchateau@DuoLnx BY_process]$ gdb -q -p 6513 -x stack.gdb # Attaching to process 6513 # Reading symbols from /usr/bin/kdeinit...(no debugging symbols found)...done. for lin in gdb_last_output.split(b'\n'): if lib_util.is_py3: # This return a bytes. lin = lin.decode("utf-8") DEBUG("rungdb:%s", lin) # Not sure the prompt is displayed when in non-interactive mode. if lin.startswith("(gdb)"): continue if lin.startswith("Reading symbols "): continue if lin.startswith("Loaded symbols "): continue resu.append(lin) if len(gdb_err) != 0: DEBUG("Err:%s", gdb_err) lib_common.ErrorMessageHtml("No gdb output:" + gdb_err) return resu
def AddFromSmbClient(grph, smb_dir, smb_shr, pass_wrd, root_node): smbclient_cmd = ["smbclient", "-c", "ls", "-D", smb_dir, smb_shr, pass_wrd] # This print is temporary until we know how to display smb-shared files. logging.debug("Command=%s", str(smbclient_cmd)) smbclient_pipe = lib_common.SubProcPOpen(smbclient_cmd) smbclient_last_output, smbclient_err = smbclient_pipe.communicate() lines = smbclient_last_output.split('\n') for lin in lines: logging.debug("l=" + lin) # Normally this is only the first line # session setup failed: NT_STATUS_LOGON_FAILURE mtch_net = re.match("^.*(NT_STATUS_.*)", lin) if mtch_net: lib_common.ErrorMessageHtml("Smb failure: " + mtch_net.group(1) + " shr:" + smb_shr + " dir:" + smb_dir) # . D 0 Wed Jul 23 23:22:34 2014 # .. D 0 Sat Oct 19 00:25:58 2013 #fldigi.exe A 40177610 Sat Jun 29 00:20:46 2013 # My Playlists D 0 Wed May 1 14:14:55 2013 # Sample Music DR 0 Wed May 1 19:46:06 2013 reg_date = '[A-Za-z]+ +[A-Za-z]+ +[0-9]+ +[0-9]+:[0-9]+:[0-9]+ +[0-9]+' reg_full = '^(.*) ([0-9]+) +' + reg_date tst_fil = re.match(reg_full, lin) if tst_fil: fil_nam = tst_fil.group(1)[2:] fil_sz = tst_fil.group(2) fil_nam = SmbCleanupFilNam(fil_nam,fil_sz) logging.debug("Fi=%s, Sz=%s", fil_nam, fil_sz) fil_nod = lib_uris.gUriGen.SmbFileUri(smb_shr, smb_dir + "/" + fil_nam) grph.add((root_node, pc.property_directory, fil_nod))
def Main(): cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() arp_cmd = ["/sbin/arp", "-a"] arp_pipe = lib_common.SubProcPOpen(arp_cmd) (arp_last_output, arp_err) = arp_pipe.communicate() # Converts to string for Python3. asstr = arp_last_output.decode("utf-8") lines = asstr.split('\n') lookup_threads = [] cnt = 0 for lin in lines: sys.stderr.write("Lin=%s\n" % lin) #print("se="+str(seenHyphens)+" Lin=("+lin+")") # Maybe should check if other interfaces ?? # Maybe should create the entity "network interface", # instead of this confusion between machines and addresses. # BThomehub.home (192.168.1.254) at 18:62:2C:63:98:6A [ether] on eth0 mtch_arp = re.match("([^ ]+) \(([^)]+)\) at ([^ ]+) .*", lin) if not mtch_arp: continue hostName = mtch_arp.group(1) hostNode = lib_common.gUriGen.HostnameUri(hostName) grph.add((hostNode, pc.property_information, lib_common.NodeLiteral(mtch_arp.group(2)))) grph.add((hostNode, pc.property_information, lib_common.NodeLiteral(mtch_arp.group(3)))) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() net_view_cmd = ["net", "view"] net_view_pipe = lib_common.SubProcPOpen(net_view_cmd) (net_view_last_output, net_view_err) = net_view_pipe.communicate() # Converts to string for Python3. asstr = net_view_last_output.decode("utf-8") lines = asstr.split('\n') seenHyphens = False for lin in lines: if re.match(".*-------.*", lin): seenHyphens = True continue if re.match(".*The command completed successfully.*", lin): break if not seenHyphens: continue #print("se="+str(seenHyphens)+" Lin2=("+lin+")") tst_view = re.match(r'^\\\\([A-Za-z0-9_$]+)', lin) if not tst_view: continue shrSrv = tst_view.group(1) shareSrvNode = lib_common.gUriGen.SmbServerUri(shrSrv) grph.add((lib_common.nodeMachine, pc.property_smbview, shareSrvNode)) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.ScriptEnvironment() grph = cgiEnv.GetGraph() arp_cmd = ["/sbin/arp", "-a"] arp_pipe = lib_common.SubProcPOpen(arp_cmd) arp_last_output, arp_err = arp_pipe.communicate() # Converts to string for Python3. asstr = arp_last_output.decode("utf-8") lines = asstr.split('\n') for lin in lines: logging.debug("Lin=%s", lin) # Maybe should check if other interfaces ?? # Maybe should create the entity "network interface", # instead of this confusion between machines and addresses. # BThomehub.home (192.168.1.254) at 18:62:2C:63:98:6A [ether] on eth0 mtch_arp = re.match(r"([^ ]+) \(([^)]+)\) at ([^ ]+) .*", lin) if not mtch_arp: continue host_name = mtch_arp.group(1) host_node = lib_uris.gUriGen.HostnameUri(host_name) grph.add((host_node, pc.property_information, lib_util.NodeLiteral(mtch_arp.group(2)))) grph.add((host_node, pc.property_information, lib_util.NodeLiteral(mtch_arp.group(3)))) cgiEnv.OutCgiRdf()
def Main(): paramkeyPortsRange = "Ports Range" paramkeyGraphDisplay = "Graph display" cgiEnv = lib_common.CgiEnv( { paramkeyPortsRange : "22-443", paramkeyGraphDisplay: False} ) # This is just a first experimentation with nmap. # This scans a couple of ports from the current host. # Ideally, the port range could be changed in edit mode of this script. # toto = "C:\\Program Files (x86)\\Nmap\\nmap.exe" # nmap_path="nmap" # The program nmap must be in the PATH. # args = ["nmap", '-oX', '-', '127.0.0.1', '-p', '22-443' ] portsRange = cgiEnv.get_parameters( paramkeyPortsRange ) args = ["nmap", '-oX', '-', '127.0.0.1', '-p', portsRange ] # C:\Program Files (x86)\Nmap; isGraphDisplay = cgiEnv.get_parameters( paramkeyGraphDisplay ) #try: p = lib_common.SubProcPOpen(args) #except WindowsError: # On Windows, this cannot find "FileNotFoundError" # exc = sys.exc_info()[1] # lib_common.ErrorMessageHtml("Cannot find nmap:"+str(exc)+". Maybe a dependency problem") #except FileNotFoundError: # lib_common.ErrorMessageHtml("Cannot find nmap") grph = cgiEnv.GetGraph() ( nmap_last_output, nmap_err) = p.communicate() dom = xml.dom.minidom.parseString(nmap_last_output) # sys.stderr.write(str(nmap_last_output)) for dhost in dom.getElementsByTagName('host'): host = dhost.getElementsByTagName('address')[0].getAttributeNode('addr').value # print("host="+host) nodeHost = lib_common.gUriGen.HostnameUri( host ) for dhostname in dhost.getElementsByTagName('hostname'): hostnam = dhostname.getAttributeNode('name').value # print(" hostnam="+hostnam) grph.add( ( nodeHost, pc.property_hostname, lib_common.NodeLiteral( hostnam ) ) ) #for dstatus in dhost.getElementsByTagName('status'): # status : up... # print(" State="+dstatus.getAttributeNode('state').value ) # print(" Reason="+dstatus.getAttributeNode('reason').value ) for dport in dhost.getElementsByTagName('port'): # protocol proto = dport.getAttributeNode('protocol').value # print(" proto="+proto) port = int(dport.getAttributeNode('portid').value) socketNode = lib_common.gUriGen.AddrUri( host, port, proto ) if not isGraphDisplay: state = dport.getElementsByTagName('state')[0].getAttributeNode('state').value #sys.stderr.write("state="+state+"\n") grph.add( ( socketNode, lib_common.MakeProp("State"), lib_common.NodeLiteral(state) ) ) reason = dport.getElementsByTagName('state')[0].getAttributeNode('reason').value #sys.stderr.write("reason="+reason) grph.add( ( socketNode, lib_common.MakeProp("Reason"), lib_common.NodeLiteral(reason) ) ) # name if any #for dname in dport.getElementsByTagName('service'): # name = dname.getAttributeNode('name').value # print(" name="+name) #for dscript in dport.getElementsByTagName('script'): # script_id = dscript.getAttributeNode('id').value # script_out = dscript.getAttributeNode('output').value # print("script_id="+script_id) # print("script_out="+script_out) # BEWARE: Normally the LHS node should be a process !!! grph.add( ( nodeHost, pc.property_has_socket, socketNode ) ) if isGraphDisplay: cgiEnv.OutCgiRdf() else: cgiEnv.OutCgiRdf( "LAYOUT_RECT", [pc.property_has_socket])
def Main(): paramkeyPortsRange = "Ports Range" cgiEnv = lib_common.ScriptEnvironment() # net_mask = "192.168.1.0/24" # '10.102.235.173' local_ip_addr = lib_util.GlobalGetHostByName(socket.gethostname()) split_ip_addr = local_ip_addr.split(".") split_ip_addr[3] = "0" net_mask = ".".join(split_ip_addr) + "/24" # "sP" is ping scan. # args = ["nmap", '-oX', '-', '-sP', '192.168.1.0/24', ] args = [ "nmap", '-oX', '-', '-sP', net_mask, ] # TODO: Get the netmask for the interface. # The program nmap must be in the PATH. p = lib_common.SubProcPOpen(args) grph = cgiEnv.GetGraph() nmap_last_output, nmap_err = p.communicate() dom = xml.dom.minidom.parseString(nmap_last_output) # <host><status state="down" reason="no-response"/> # <address addr="192.168.1.67" addrtype="ipv4" /> # </host> # <host><status state="up" reason="syn-ack"/> # <address addr="192.168.1.68" addrtype="ipv4" /> # <hostnames><hostname name="Unknown-00-18-e7-08-02-81.home" type="PTR" /></hostnames> # </host> # Possibly # <address addr="08:2E:5F:13:0E:48" addrtype="mac" vendor="Hewlett Packard"/> for dhost in dom.getElementsByTagName('host'): status = dhost.getElementsByTagName('status')[0].getAttributeNode( 'state').value node_host = None addr_vendor = None # TODO: This could be an option. Test this. if status != "up": continue for addr_element in dhost.getElementsByTagName('address'): # "mac", "ipv4" addr_type = addr_element.getAttributeNode('addrtype').value if addr_type == "ipv4": host = addr_element.getAttributeNode('addr').value node_host = lib_uris.gUriGen.HostnameUri(host) elif addr_type == "mac": try: addr_vendor = addr_element.getAttributeNode('vendor').value mac_addr = addr_element.getAttributeNode('addr').value except: addr_vendor = None if node_host: if addr_vendor: grph.add((node_host, lib_common.MakeProp("MAC address"), lib_util.NodeLiteral(mac_addr))) grph.add((node_host, lib_common.MakeProp("Vendor"), lib_util.NodeLiteral(addr_vendor))) for dhostname in dhost.getElementsByTagName('hostname'): hostnam = dhostname.getAttributeNode('name').value grph.add((node_host, pc.property_hostname, lib_util.NodeLiteral(hostnam))) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.ScriptEnvironment() try: the_pid = int(cgiEnv.GetId()) except Exception: lib_common.ErrorMessageHtml("Must provide a pid") # If cannot be the current pid, otherwise it will block. if the_pid == os.getpid(): lib_common.ErrorMessageHtml("Cannot debug current process") if not lib_util.isPlatformWindows: lib_common.ErrorMessageHtml("This works only on Windows platforms") grph = cgiEnv.GetGraph() # Starts a second session cdb_fil = lib_util.TmpFile("CdbCommand", "cdb") cdb_fd = open(cdb_fil.Name, "w") cdb_fd.write("lm\n") # List loaded modules cdb_fd.write("k\n") # Display stack backtrace. cdb_fd.write("qd\n") # Quit and detach. cdb_fd.close() cdb_cmd = "cdb -p " + str(the_pid) + " -cf " + cdb_fil.Name proc_node = lib_uris.gUriGen.PidUri(the_pid) call_node_prev = None modules_map = {} logging.debug("Starting cdb_cmd=%s", cdb_cmd) try: cdb_pipe = lib_common.SubProcPOpen(cdb_cmd) except WindowsError as exc: lib_common.ErrorMessageHtml("cdb not available: Caught:%s" % str(exc)) logging.debug("Started cdb_cmd=%s", cdb_cmd) cdb_output, cdb_err = cdb_pipe.communicate() # Without decode, "TypeError: Type str does not support the buffer API" cdb_str = cdb_output.decode("utf-8") call_depth = 0 for dot_line in cdb_str.split('\n'): err_match = re.match(".*parameter is incorrect.*", dot_line) if err_match: lib_common.ErrorMessageHtml("CDB:"+dot_line) # 76590000 766a0000 kernel32 (export symbols) C:\Windows\syswow64\kernel32.dll match_lm = re.match(r"[0-9a-fA-F]+ [0-9a-fA-F]+ +([^ ]*) +\(export symbols\) +(.*)", dot_line ) if match_lm: module_name = match_lm.group(1) dll_name_raw = match_lm.group(2).strip() dll_name = lib_util.standardized_file_path(dll_name_raw) logging.debug("module_name=%s dll_name=%s", module_name, dll_name) modules_map[module_name] = dll_name continue # 295cfb0c 00000000 ntdll!RtlInitializeExceptionChain+0x36 # Another format, maybe because of a 64 bits machine. # 00000000`02edff90 00000000`00000000 ntdll!RtlUserThreadStart+0x21 match_k = re.match("[`0-9a-fA-F]+ [`0-9a-fA-F]+ ([^!]*)!([^+]*)", dot_line) if match_k: module_name = match_k.group(1) try: dll_name = modules_map[module_name] except KeyError: dll_name = module_name func_name = match_k.group(2).strip() logging.debug("module_name=%s dll_name=%s func_name=%s", module_name, dll_name, func_name) dll_name = CDB.TestIfKnownDll(dll_name) call_node_prev = survol_symbol.AddFunctionCall(grph, call_node_prev, proc_node, func_name, dll_name) grph.add((call_node_prev, lib_properties.MakeProp("Call_depth"), lib_util.NodeLiteral(call_depth))) call_depth += 1 continue logging.debug("dot_line=%s", dot_line) logging.debug("Parsed cdb result") call_node_prev = survol_symbol.AddFunctionCall(grph, call_node_prev, proc_node, None, None) CIM_Process.AddInfo(grph, proc_node, [the_pid]) # http://msdn.microsoft.com/en-us/library/windows/hardware/ff539058(v=vs.85).aspx # # This section describes how to perform basic debugging tasks using # the Microsoft Console Debugger (CDB) and Microsoft NT Symbolic Debugger (NTSD). # CDB and NTSD are identical in every way, except that NTSD spawns # a new text window when it is started, whereas CDB inherits # the Command Prompt window from which it was invoked. # The instructions in this section are given for CDB, # but they work equally well for NTSD. For a discussion # of when to use CDB or NTSD, see Debugging Environments. cgiEnv.OutCgiRdf("LAYOUT_SPLINE")
def Main(): paramkeyGroupByDirs = "Group by directories" cgiEnv = lib_common.CgiEnv(parameters={paramkeyGroupByDirs: True}) flagGroupByDirs = bool(cgiEnv.get_parameters(paramkeyGroupByDirs)) win_module = cgiEnv.GetId() lib_win32.CheckWindowsModule(win_module) # This has to be in the path. Is it the 32 bits or 64 bits one ? depends_bin = "depends.exe" DEBUG("depends_bin=%s", depends_bin) tmpFilObj = lib_common.TmpFile("depends") tmpOutFil = tmpFilObj.Name args = [depends_bin, "/c", "/OC:", tmpOutFil, win_module] DEBUG("Depends command=%s", str(args)) grph = cgiEnv.GetGraph() nodeDLL = lib_common.gUriGen.FileUri(win_module) # TODO: Check the return value. # http://www.dependencywalker.com/help/html/hidr_command_line_help.htm p = lib_common.SubProcPOpen(args) (nmap_last_output, nmap_err) = p.communicate() for lin in nmap_last_output: continue # Wait for the end, otherwise the file will not be ready. try: DEBUG("Depends tmpOutFil=%s", tmpOutFil) input_file = open(tmpOutFil, 'r') except Exception: exc = sys.exc_info()[1] lib_common.ErrorMessageHtml("Caught " + str(exc) + " when processing:" + tmpOutFil) # Status,Module,File Time Stamp,Link Time Stamp,File Size,Attr.,Link Checksum,Real Checksum,CPU,Subsystem,Symbols,Preferred Base,Actual Base,Virtual Size,Load Order,File Ver,Product Ver,Image Ver,Linker Ver,OS Ver,Subsystem Ver # ?,"MSVCR80D.DLL","Error opening file. The system cannot find the file specified (2).",,,,,,,,,,,,,,,,,, # D?,"XLCALL32.DLL","Error opening file. The system cannot find the file specified (2).",,,,,,,,,,,,,,,,,, # E6,"c:\windows\system32\ADVAPI32.DLL",2012-10-18 21:27:04,2012-10-18 21:27:12,876544,A,0x000D9B98,0x000D9B98,x64,Console,"CV",0x000007FF7FF10000,Unknown,0x000DB000,Not Loaded,6.1.7601.22137,6.1.7601.22137,6.1,9.0,6.1,6.1 # E6,"c:\windows\system32\API-MS-WIN-CORE-CONSOLE-L1-1-0.DLL",2013-08-02 03:12:18,2013-08-02 03:12:52,3072,HA,0x000081B6,0x000081B6,x64,Console,"CV",0x0000000000400000,Unknown,0x00003000,Not Loaded,6.1.7601.18229,6.1.7601.18229,6.1,9.0,6.1,6.1 # Used only if libraries are grouped by directory. dirsToNodes = {} for lin in input_file: # TODO: Beware of commas in file names!!!!! Maybe module shlex ? linargs = lin.split(',') module = linargs[1] # The library filename is enclosed in double-quotes, that we must remove. modulNam = module[1:-1] libNode = lib_common.gUriGen.SharedLibUri(modulNam) # If the libraries are displayed in groups belnging to a dir, this is clearer. if flagGroupByDirs: dirNam = os.path.dirname(modulNam) if dirNam == "": dirNam = "Unspecified dir" try: dirNod = dirsToNodes[dirNam] except KeyError: # TODO: Beware, in fact this is a directory. dirNod = lib_common.gUriGen.FileUri(dirNam) grph.add((nodeDLL, pc.property_library_depends, dirNod)) dirsToNodes[dirNam] = dirNod grph.add((dirNod, pc.property_library_depends, libNode)) else: grph.add((nodeDLL, pc.property_library_depends, libNode)) if linargs[0] != '?': cpu = linargs[8] if cpu not in ["", "CPU"]: grph.add((nodeDLL, pc.property_library_cpu, lib_common.NodeLiteral(cpu))) # Temporary file removed by constructor. input_file.close() cgiEnv.OutCgiRdf()
def DoTheJob(TheEngine, Deserializer, AppName, Title, dot_layout="", collapsed_properties=[]): srvSingle = SrvSingleton(AppName) PortNum = srvSingle.m_PortNumber run_word = "run" GblLog("DoTheJob:" + str(sys.argv) + " title=" + Title + " dot_layout=" + dot_layout) if srvSingle.m_PortNumber != None: GblLog("Title=%s PortNum=%d" % (Title, PortNum)) else: GblLog("Title=%s PortNum not defined yet" % (Title)) # So we can answer immediately to "info" requests, without creating the subserver. cgiEnv = lib_common.CgiEnv(Title, "", {"port_number": PortNum}) # This is the subprocess of the specialised http server. if (len(sys.argv) > 1) and (sys.argv[1] == run_word): if srvSingle.GetRunning(): GblLog("Subprocess: Race condition: Port " + str(PortNum) + " allocated. Leaving.") sys.exit(0) # Called before creating the subserver because we will be stuck into it. if not srvSingle.SetRunning(): GblLog("CANNOT SET RUNNING STATE: Race condition ?") return # This time the port must be valid. PortNum = srvSingle.m_PortNumber GblLog("Subprocess: Port %d free. About to create subserver." % PortNum) try: # Normally we are stuck in this, answering HTTP requests and accumulating data. # TODO: It is probably not necessary to send Title and DotLayout. layoutParams = lib_common.make_dot_layout(dot_layout, collapsed_properties) # Now, will append log at the end. srvSingle.m_logFd.close() gServer = RdfStreamServer(PortNum, TheEngine, Deserializer, Title, layoutParams, srvSingle.m_logFilNam) GblLog("Should never be here") except Exception: exc = sys.exc_info()[1] msg = Task() + " Caught when starting RdfStreamServer:" + str(exc) GblLog(msg) srvSingle.CancelRunning() lib_common.ErrorMessageHtml("From RDFStreamServer, caught:" + msg) sys.exit(0) # if the subserver is not running, we start it, then redirects the browser # to initiate a new connection. After that, we exit() but this will never really # exit until our subserver subprocess, exits first. if not srvSingle.GetRunning(): GblLog("About to start:" + AppName) try: # Do not pipe the output otherwise it would not run in the background. # Si necessaire, on pourrait lancer un process avec l'user root ? # sub_proc = lib_common.SubProcPOpen( [ "python", AppName, run_word ] ) # Share standard error. sub_proc = lib_common.SubProcPOpen(["python", AppName, run_word], stderr=sys.stderr) GblLog("Started sub http server:" + AppName + " subpid=" + str(sub_proc.pid)) # We need the cgi arguments, especially the entity id. origUrl = os.environ["REQUEST_URI"] GblLog("About to redirect browser to:" + origUrl) # IMPORTANT: We leave time enough for the subprocess to start, # otherwise it will be started TWICE. time.sleep(0.1) GblLog("After pause") SendRedirection(sys.stdout, origUrl) # This blocks until the subprocess exists. GblLog("Waiting for end of subpid=" + str(sub_proc.pid)) sys.exit(0) except Exception: exc = sys.exc_info()[1] lib_common.ErrorMessageHtml("When starting server=" + AppName + ", caught:" + str(exc)) GblLog("Service exists. Port=" + str(PortNum)) # Here, we know that the subserver is running. url = SubServerUrl(PortNum, cgiEnv) # Do we have to stop the subserver ? if MustStop(): # Equivalent to 'ModedUrl("stop")' url_stop = lib_util.ConcatenateCgi(url, "mode=stop") # TODO: We could also load this URL, this would be nicer. SendRedirection(sys.stdout, url_stop) sys.exit(0) mode = lib_util.GuessDisplayMode() GblLog("mode:" + mode) # Equivalent to 'ModedUrl(mode)' url_mode = lib_util.ConcatenateCgi(url, "mode=" + mode) GblLog("url_mode:" + url_mode) SendRedirection(sys.stdout, url_mode) GblLog("Finished:" + AppName)
def Main(): cgiEnv = lib_common.CgiEnv() args = [ "nmap", '-oX', '-', '--script', "broadcast-ms-sql-discover", ] # The returned IP address is wrong when launched from a Windows machine where the DB is running. p = lib_common.SubProcPOpen(args) grph = cgiEnv.GetGraph() (nmap_last_output, nmap_err) = p.communicate() dom = xml.dom.minidom.parseString(nmap_last_output) # <script id="broadcast-ms-sql-discover" output="
 192.168.0.14 (RCHATEAU-HP)
 [192.168.0.14\SQLEXPRESS]
 Name: SQLEXPRESS
 Product: Microsoft SQL Server 2012
 TCP port: 1433
 Named pipe: \\192.168.0.14\pipe\MSSQL$SQLEXPRESS\sql\query
"/> for aScript in dom.getElementsByTagName('script'): anOutput = aScript.getAttributeNode('output').value.strip() DEBUG("anOutput=%s", str(anOutput)) arrSplit = [aWrd.strip() for aWrd in anOutput.split("\n")] DEBUG("arrSplit=%s", str(arrSplit)) # "192.168.0.14 (RCHATEAU-HP)" theMachFull = arrSplit[0].strip() reMach = re.match("([^ ]*) *\(([^)]*)\)", theMachFull) if reMach: machIp = reMach.group(1) machNam = reMach.group(2) nodeHost = lib_common.gUriGen.HostnameUri(machNam) grph.add((nodeHost, lib_common.MakeProp("IP address"), lib_common.NodeLiteral(machIp))) else: nodeHost = lib_common.gUriGen.HostnameUri(theMachFull) machIp = None machNam = theMachFull theNameDB = arrSplit[1].strip() grph.add((nodeHost, lib_common.MakeProp("Sql server instance"), lib_common.NodeLiteral(theNameDB))) tcpPort = None srvName = None # RCHATEAU-HP IP_address 192.168.0.14 # Name SQLEXPRESS # Named_pipe \\192.168.0.14\pipe\MSSQL$SQLEXPRESS\sql\query # Product Microsoft SQL Server 2012 # Sql_server_instance [192.168.0.14\SQLEXPRESS] # TCP_port 1433 for oneWrd in arrSplit[2:]: DEBUG("oneWrd=%s", oneWrd) oneSplit = [aSplit.strip() for aSplit in oneWrd.split(":")] oneKey = oneSplit[0] if len(oneSplit) > 1: oneVal = ":".join(oneSplit[1:]) # In case there would be more than one ":" grph.add((nodeHost, lib_common.MakeProp(oneKey), lib_common.NodeLiteral(oneVal))) if oneKey == "TCP port": tcpPort = oneVal elif oneKey == "Name": srvName = oneVal else: pass else: grph.add((nodeHost, pc.property_information, lib_common.NodeLiteral(oneKey))) if tcpPort and srvName and pyodbc: AddOdbcNode(grph, machNam, srvName, tcpPort) AddOdbcNode(grph, machIp, srvName, tcpPort) cgiEnv.OutCgiRdf()