Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from py2neo import Graph, Node, Relationship
g = Graph()
tx = g.begin()
a = Node("Person", name="Alice")
tx.create(a)
b = Node("Person", name="Bob")
ab = Relationship(a, "KNOWS", b)
tx.create(ab)
tx.commit()
g.exists(ab)
"""
Sample Query
timelines, detects, detect_cf = adetection(count_set, username_set, starttime, tohours)
# Calculate Hidden Markov Model
print("[+] Calculate Hidden Markov Model.")
detect_hmm = decodehmm(ml_frame, username_set, datetime.datetime(*starttime.timetuple()[:3]))
# Calculate PageRank
print("[+] Calculate PageRank.")
ranks = pagerank(event_set, admins, detect_hmm, detect_cf, ntmlauth)
# Create node
print("[+] Creating a graph data.")
try:
graph_http = "http://" + NEO4J_USER + ":" + NEO4J_PASSWORD + "@" + NEO4J_SERVER + ":" + NEO4J_PORT + "/db/data/"
GRAPH = Graph(graph_http)
except:
sys.exit("[!] Can't connect Neo4j Database.")
tx = GRAPH.begin()
hosts_inv = {v: k for k, v in hosts.items()}
for ipaddress in event_set["ipaddress"].drop_duplicates():
if ipaddress in hosts_inv:
hostname = hosts_inv[ipaddress]
else:
hostname = ipaddress
# add the IPAddress node to neo4j
tx.run(statement_ip.format(**{"IP": ipaddress, "rank": ranks[ipaddress], "hostname": hostname}))
i = 0
for username in username_set:
if username in sids:
options = parser.parse_args()
if options.no_flush:
FLUSH_DB = False
if options.manuf:
MANUF_UPDATE = True
if options.gui:
GUI = True
if options.airodump_csv:
AIRO_FILE = str(options.airodump_csv.name)
if options.parse:
if AIRO_FILE:
user = input('Username: ')
pwd = getpass.getpass(prompt='Password: ', stream=None)
graph = Graph(user=user, password=pwd)
parseAirodump(graph)
print ("Successfully processed %s" % AIRO_FILE)
exit(0)
else:
print ("Please specify a CSV file to parse!\n")
exit(0)
t = threading.Thread(target=start_server)
t.daemon = True
t.start()
url = "http://localhost:58008"
while not url_ok(url):
sleep(1)
if GUI:
#!/usr/bin/env python
import json
from bottle import get, run, request, response, static_file
from py2neo import Graph
graph = Graph("http://username:@localhost:7474")
@get("/")
def get_index():
return static_file("index.html", root="static")
@get("/graph")
def get_graph():
results = graph.cypher.execute(
"MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) "
"RETURN m.title as movie, collect(a.name) as cast "
"LIMIT {limit}", {"limit": 100})
nodes = []
rels = []
i = 0
from py2neo import Graph, Node
import os
from datetime import datetime
pw = os.environ.get('NEO4J_PASS')
g= Graph("http://localhost:7474/browser/",password = pw) ## readme need to document setting environment variable in pycharm
# g.delete_all()
tx = g.begin()
#========================================== Get files ==========================================#
# root = os.getcwd()
# path = os.path.join(root, "data")
# disclosure_1st_path = os.path.join(path, "2013_1stQuarter_XML")
# files = [f for f in os.listdir(disclosure_1st_path) if f.endswith('.xml')]
# files = ['file:///Users/yaqi/Documents/vir_health_graph/health-graph/data/2013_1stQuarter_XML/300545488.xml'] # Return xml files
# file1 = [f for f in os.listdir(dc_1) if f.endswith('.xml')]
# print(file1)
def get_file_path(kind):
root_dir = '/Users/yaqi/Documents/data/' + kind
def fetch_related_videos(video_id, id_type="videoId", result_len=10):
mongo_db = mongo.db
neo4j_db = Graph(user=config.neo4j_user,
password=config.neo4j_pass)
# Find node corresponding to current video
source_node = neo4j_db.find_one("Video", id_type, video_id)
if id_type == "mongoId":
video_id = source_node["videoId"]
# Get all edges from current node
rel_edges = [
rel for rel in
neo4j_db.match(
start_node=source_node
)
]
# Loop through each edge and update score of end node
edge_end_nodes = {}
for x in rel_edges:
if x.type() == "SameChannel":
def toNeo(graphity, mySha1, myFileSize, myBinType):
# GRAPH DB STUFF - NEO4J
# receives the NetworkX graph and accompanying sample data
# pushes the graph to Neo4J
py2neo.authenticate("localhost:7474", "neo4j", "neo4j")
neoGraph = py2neo.Graph("http://localhost:7474/")
# flush of the DB, DEACTIVATE for mass storing of samples
neoGraph.delete_all()
# create node for binary information
sampleNode = py2neo.Node("SAMPLE", sha1=mySha1, fileSize=myFileSize, binType=myBinType)
neoGraph.create(sampleNode)
# parsing of the NetworkX graph - functions, APIs and strings are all Neo4j nodes
for nxNode in graphity.nodes(data=True):
funcAddress = nxNode[0]
funcCalltype = nxNode[1]['calltype']
funcSize = nxNode[1]['size']
functionNode = py2neo.Node("FUNCTION", mySha1, address=funcAddress, callType=funcCalltype, funcSize=funcSize)
db=_mysql.connect(host=host ,user=user, passwd=password, db=db)
db.query("""SELECT * FROM mailing_lists_people""")
result = db.use_result()
# Name of fields in the MySQL database.
fields = [e[0] for e in result.describe()]
# Returns all the rows in the MySQL table.
rows = result.fetch_row(maxrows=0)
# In our case the data has 2 fields.
# (email_address, mailing_list_url)
# Connect to running neo4j graph database.
n4j_graph = Graph("http://localhost:7474/db/data/")
# Creating indexes on fields that would be used frequently for filtering.
n4j_graph.cypher.execute("CREATE INDEX ON :MUser(email)")
n4j_graph.cypher.execute("CREATE INDEX ON :MList(mailing_list_url)")
ctr = 0
for row in rows:
print row
email = row[0]
mailing_list_url = row[1]
s = '''MERGE (u:MUser { %(primary_key_field)s: "%(email)s"})
MERGE (m:MList { mailing_list_url: "%(mailing_list_url)s"})
CREATE UNIQUE u-[:BELONGS_TO]->m'''%{"primary_key_field": fields[0], "email": email, "mailing_list_url": mailing_list_url }
n4j_graph.cypher.execute(s)
def __init__(self, username='neo4j', password='admin', bolt=7687):
self.graph = Graph(user=username, password=password, bolt_port=bolt)
def get_db_connection(args):
uri = "{}://{}:{}/db/data".format(
args.neo_scheme, args.neo_host, args.neo_port)
logger.info("openning connection to neo (%s)", uri)
return Graph(
uri,
user=args.neo_user,
password=args.neo_passwd,
secure=args.neo_secure,
http_port=args.neo_port
)