-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
64 lines (54 loc) · 2.39 KB
/
db.py
1
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from neo4j import GraphDatabase
from pathlib import Path
URI = "neo4j://localhost:7687"
AUTH = ("neo4j", "password")
def check_connection():
with GraphDatabase.driver(URI, auth=AUTH) as driver:
try:
driver.verify_connectivity()
driver.close()
except Exception:
raise Exception('Please ensure that neo4j instance is running.')
def exportdb():
directory_path = Path(__file__).parent.absolute()
with GraphDatabase.driver(URI, auth=AUTH) as driver:
try:
# Initialize constraints
driver.execute_query(
"CREATE CONSTRAINT pidPidConstraint IF NOT EXISTS FOR (p:Pid) REQUIRE p.pid IS UNIQUE"
)
driver.execute_query(
"CREATE CONSTRAINT syscallLogIdConstraint IF NOT EXISTS FOR (s:Syscall) REQUIRE s.log_id IS UNIQUE;"
)
# Delete current data
driver.execute_query(
"MATCH (n) DETACH DELETE n;"
)
# Load data and relationships
# pid table
driver.execute_query(
f"LOAD CSV WITH HEADERS FROM \"file://{directory_path}/pid.csv\" AS csvLine " +
"MERGE (p1:Pid {pid: toInteger(csvLine.pid)}) " +
"ON CREATE SET p1.name = csvLine.name, p1.path = csvLine.path " +
"MERGE (p2:Pid {pid: toInteger(csvLine.ppid)}) " +
"MERGE (p2)-[:PARENT_OF]->(p1);"
)
# syscall table
driver.execute_query(
f"LOAD CSV WITH HEADERS FROM \"file://{directory_path}/syscall.csv\" AS csvLine " +
"CREATE (s:Syscall {log_id: toInteger(csvLine.log_id), pid: toInteger(csvLine.pid), syscall: csvLine.syscall, key: csvLine.key, arguments: csvLine.arguments}) " +
"WITH s " +
"MATCH (p:Pid {pid : s.pid}) " +
"CREATE (p)-[:INVOKE]->(s);"
)
# path table
driver.execute_query(
f"LOAD CSV WITH HEADERS FROM \"file://{directory_path}/path.csv\" AS csvLine " +
"CREATE (p:path {log_id: toInteger(csvLine.log_id), filepath: csvLine.filepath}) " +
"WITH p " +
"MATCH (s:Syscall {log_id : p.log_id}) " +
"CREATE (s)-[:ACCESS]->(p);"
)
driver.close()
except Exception as e:
print(e)