forked from milo2012/osintstalker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fbstalker1.py
2031 lines (1862 loc) · 72.5 KB
/
fbstalker1.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import division
import httplib2,json
import zlib
import zipfile
import sys
import re
import datetime
import operator
import sqlite3
import os
from datetime import datetime
from datetime import date
import pytz
from tzlocal import get_localzone
import requests
from termcolor import colored, cprint
from pygraphml.GraphMLParser import *
from pygraphml.Graph import *
from pygraphml.Node import *
from pygraphml.Edge import *
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
import time,re,sys
from selenium.webdriver.common.keys import Keys
import datetime
from bs4 import BeautifulSoup
from StringIO import StringIO
requests.adapters.DEFAULT_RETRIES = 10
h = httplib2.Http(".cache")
facebook_username = ""
facebook_password = ""
global uid
uid = ""
username = ""
internetAccess = True
cookies = {}
all_cookies = {}
reportFileName = ""
#For consonlidating all likes across Photos Likes+Post Likes
peopleIDList = []
likesCountList = []
timePostList = []
placesVisitedList = []
#Chrome Options
chromeOptions = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images":2}
chromeOptions.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
def createDatabase():
conn = sqlite3.connect('facebook.db')
c = conn.cursor()
sql = 'create table if not exists photosLiked (sourceUID TEXT, description TEXT, photoURL TEXT unique, pageURL TEXT, username TEXT)'
sql1 = 'create table if not exists photosCommented (sourceUID TEXT, description TEXT, photoURL TEXT unique, pageURL TEXT, username TEXT)'
sql2 = 'create table if not exists friends (sourceUID TEXT, name TEXT, userName TEXT unique, month TEXT, year TEXT)'
sql3 = 'create table if not exists friendsDetails (sourceUID TEXT, userName TEXT unique, userEduWork TEXT, userLivingCity TEXT, userCurrentCity TEXT, userLiveEvents TEXT, userGender TEXT, userStatus TEXT, userGroups TEXT)'
sql4 = 'create table if not exists videosBy (sourceUID TEXT, title TEXT unique, url TEXT)'
sql5 = 'create table if not exists pagesLiked (sourceUID TEXT, name TEXT unique, category TEXT,url TEXT)'
sql6 = 'create table if not exists photosOf (sourceUID TEXT, description TEXT, photoURL TEXT unique, pageURL TEXT, username TEXT)'
sql7 = 'create table if not exists photosBy (sourceUID TEXT, description TEXT, photoURL TEXT unique, pageURL TEXT, username TEXT)'
c.execute(sql)
c.execute(sql1)
c.execute(sql2)
c.execute(sql3)
c.execute(sql4)
c.execute(sql5)
c.execute(sql6)
c.execute(sql7)
conn.commit()
createDatabase()
conn = sqlite3.connect('facebook.db')
def createMaltego(username):
g = Graph()
totalCount = 50
start = 0
nodeList = []
edgeList = []
while(start<totalCount):
nodeList.append("")
edgeList.append("")
start+=1
nodeList[0] = g.add_node('Facebook_'+username)
nodeList[0]['node'] = createNodeFacebook(username,"https://www.facebook.com/"+username,uid)
counter1=1
counter2=0
userList=[]
c = conn.cursor()
c.execute('select userName from friends where sourceUID=?',(uid,))
dataList = c.fetchall()
nodeUid = ""
for i in dataList:
if i[0] not in userList:
userList.append(i[0])
try:
nodeUid = str(convertUser2ID2(driver,str(i[0])))
#nodeUid = str(convertUser2ID(str(i[0])))
nodeList[counter1] = g.add_node("Facebook_"+str(i[0]))
nodeList[counter1]['node'] = createNodeFacebook(i[0],'https://www.facebook.com/'+str(i[0]),nodeUid)
edgeList[counter2] = g.add_edge(nodeList[0], nodeList[counter1])
edgeList[counter2]['link'] = createLink('Facebook')
nodeList.append("")
edgeList.append("")
counter1+=1
counter2+=1
except IndexError:
continue
if len(nodeUid)>0:
parser = GraphMLParser()
if not os.path.exists(os.getcwd()+'/Graphs'):
os.makedirs(os.getcwd()+'/Graphs')
filename = 'Graphs/Graph1.graphml'
parser.write(g, "Graphs/Graph1.graphml")
cleanUpGraph(filename)
filename = username+'_maltego.mtgx'
print 'Creating archive: '+filename
zf = zipfile.ZipFile(filename, mode='w')
print 'Adding Graph1.graphml'
zf.write('Graphs/Graph1.graphml')
print 'Closing'
zf.close()
def createLink(label):
xmlString = '<mtg:MaltegoLink xmlns:mtg="http://maltego.paterva.com/xml/mtgx" type="maltego.link.manual-link">'
xmlString += '<mtg:Properties>'
xmlString += '<mtg:Property displayName="Description" hidden="false" name="maltego.link.manual.description" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Style" hidden="false" name="maltego.link.style" nullable="true" readonly="false" type="int">'
xmlString += '<mtg:Value>0</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Label" hidden="false" name="maltego.link.manual.type" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value>'+label+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Show Label" hidden="false" name="maltego.link.show-label" nullable="true" readonly="false" type="int">'
xmlString += '<mtg:Value>0</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Thickness" hidden="false" name="maltego.link.thickness" nullable="true" readonly="false" type="int">'
xmlString += '<mtg:Value>2</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Color" hidden="false" name="maltego.link.color" nullable="true" readonly="false" type="color">'
xmlString += '<mtg:Value>8421505</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '</mtg:Properties>'
xmlString += '</mtg:MaltegoLink>'
return xmlString
def createNodeImage(name,url):
xmlString = '<mtg:MaltegoEntity xmlns:mtg="http://maltego.paterva.com/xml/mtgx" type="maltego.Image">'
xmlString += '<mtg:Properties>'
xmlString += '<mtg:Property displayName="Description" hidden="false" name="description" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value>'+name+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="URL" hidden="false" name="url" nullable="true" readonly="false" type="url">'
xmlString += '<mtg:Value>'+url+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '</mtg:Properties>'
xmlString += '</mtg:MaltegoEntity>'
return xmlString
def createNodeFacebook(displayName,url,uid):
xmlString = '<mtg:MaltegoEntity xmlns:mtg="http://maltego.paterva.com/xml/mtgx" type="maltego.affiliation.Facebook">'
xmlString += '<mtg:Properties>'
xmlString += '<mtg:Property displayName="Name" hidden="false" name="person.name" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value>'+displayName+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Network" hidden="false" name="affiliation.network" nullable="true" readonly="true" type="string">'
xmlString += '<mtg:Value>Facebook</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="UID" hidden="false" name="affiliation.uid" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value>'+str(uid)+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Profile URL" hidden="false" name="affiliation.profile-url" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value>'+url+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '</mtg:Properties>'
xmlString += '</mtg:MaltegoEntity>'
return xmlString
def createNodeUrl(displayName,url):
xmlString = '<mtg:MaltegoEntity xmlns:mtg="http://maltego.paterva.com/xml/mtgx" type="maltego.URL">'
xmlString += '<mtg:Properties>'
xmlString += '<mtg:Property displayName="'+displayName+'" hidden="false" name="short-title" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value>'+displayName+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="'+displayName+'" hidden="false" name="url" nullable="true" readonly="false" type="url">'
xmlString += '<mtg:Value>'+displayName+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Title" hidden="false" name="title" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '</mtg:Properties>'
xmlString += '</mtg:MaltegoEntity>'
return xmlString
def createNodeLocation(lat,lng):
xmlString = '<mtg:MaltegoEntity xmlns:mtg="http://maltego.paterva.com/xml/mtgx" type="maltego.Location">'
xmlString += '<mtg:Properties>'
xmlString += '<mtg:Property displayName="Name" hidden="false" name="location.name" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value>lat='+str(lat)+' lng='+str(lng)+'</mtg:Value>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Area Code" hidden="false" name="location.areacode" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Area" hidden="false" name="location.area" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Latitude" hidden="false" name="latitude" nullable="true" readonly="false" type="float">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Longitude" hidden="false" name="longitude" nullable="true" readonly="false" type="float">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Country" hidden="false" name="country" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Country Code" hidden="false" name="countrycode" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="City" hidden="false" name="city" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '<mtg:Property displayName="Street Address" hidden="false" name="streetaddress" nullable="true" readonly="false" type="string">'
xmlString += '<mtg:Value/>'
xmlString += '</mtg:Property>'
xmlString += '</mtg:Properties>'
xmlString += '</mtg:MaltegoEntity>'
return xmlString
def cleanUpGraph(filename):
newContent = []
with open(filename) as f:
content = f.readlines()
for i in content:
if '<key attr.name="node" attr.type="string" id="node"/>' in i:
i = i.replace('name="node" attr.type="string"','name="MaltegoEntity" for="node"')
if '<key attr.name="link" attr.type="string" id="link"/>' in i:
i = i.replace('name="link" attr.type="string"','name="MaltegoLink" for="edge"')
i = i.replace("<","<")
i = i.replace(">",">")
i = i.replace(""",'"')
print i.strip()
newContent.append(i.strip())
f = open(filename,'w')
for item in newContent:
f.write("%s\n" % item)
f.close()
def normalize(s):
if type(s) == unicode:
return s.encode('utf8', 'ignore')
else:
return str(s)
def findUser(findName):
stmt = "SELECT uid,current_location,username,name FROM user WHERE contains('"+findName+"')"
stmt = stmt.replace(" ","+")
url="https://graph.facebook.com/fql?q="+stmt+"&access_token="+facebook_access_token
resp, content = h.request(url, "GET")
results = json.loads(content)
count=1
for x in results['data']:
print str(count)+'\thttp://www.facebook.com/'+x['username']
count+=1
def convertUser2ID2(driver,username):
url="http://graph.facebook.com/"+username
resp, content = h.request(url, "GET")
if resp.status==200:
results = json.loads(content)
if len(results['id'])>0:
fbid = results['id']
return fbid
def convertUser2ID(username):
stmt = "SELECT uid,current_location,username,name FROM user WHERE username=('"+username+"')"
stmt = stmt.replace(" ","+")
url="https://graph.facebook.com/fql?q="+stmt+"&access_token="+facebook_access_token
resp, content = h.request(url, "GET")
if resp.status==200:
results = json.loads(content)
if len(results['data'])>0:
return results['data'][0]['uid']
else:
print "[!] Can't convert username 2 uid. Please check username"
sys.exit()
return 0
else:
print "[!] Please check your facebook_access_token before continuing"
sys.exit()
return 0
def convertID2User(uid):
stmt = "SELECT uid,current_location,username,name FROM user WHERE uid=('"+uid+"')"
stmt = stmt.replace(" ","+")
url="https://graph.facebook.com/fql?q="+stmt+"&access_token="+facebook_access_token
resp, content = h.request(url, "GET")
results = json.loads(content)
return results['data'][0]['uid']
def loginFacebook(driver):
driver.implicitly_wait(120)
driver.get("https://www.facebook.com/")
assert "Welcome to Facebook" in driver.title
time.sleep(3)
driver.find_element_by_id('email').send_keys(facebook_username)
driver.find_element_by_id('pass').send_keys(facebook_password)
driver.find_element_by_id("loginbutton").click()
global all_cookies
all_cookies = driver.get_cookies()
html = driver.page_source
if "Incorrect Email/Password Combination" in html:
print "[!] Incorrect Facebook username (email address) or password"
sys.exit()
def write2Database(dbName,dataList):
try:
cprint("[*] Writing "+str(len(dataList))+" record(s) to database table: "+dbName,"white")
#print "[*] Writing "+str(len(dataList))+" record(s) to database table: "+dbName
numOfColumns = len(dataList[0])
c = conn.cursor()
if numOfColumns==3:
for i in dataList:
try:
c.execute('INSERT INTO '+dbName+' VALUES (?,?,?)', i)
conn.commit()
except sqlite3.IntegrityError:
continue
if numOfColumns==4:
for i in dataList:
try:
c.execute('INSERT INTO '+dbName+' VALUES (?,?,?,?)', i)
conn.commit()
except sqlite3.IntegrityError:
continue
if numOfColumns==5:
for i in dataList:
try:
c.execute('INSERT INTO '+dbName+' VALUES (?,?,?,?,?)', i)
conn.commit()
except sqlite3.IntegrityError:
continue
if numOfColumns==9:
for i in dataList:
try:
c.execute('INSERT INTO '+dbName+' VALUES (?,?,?,?,?,?,?,?,?)', i)
conn.commit()
except sqlite3.IntegrityError:
continue
except TypeError as e:
print e
pass
except IndexError as e:
print e
pass
def downloadFile(url):
global cookies
for s_cookie in all_cookies:
cookies[s_cookie["name"]]=s_cookie["value"]
r = requests.get(url,cookies=cookies)
html = r.content
return html
def parsePost(id,username):
filename = 'posts__'+str(id)
if not os.path.lexists(filename):
print "[*] Caching Facebook Post: "+str(id)
url = "https://www.facebook.com/"+username+"/posts/"+str(id)
driver.get(url)
if "Sorry, this page isn't available" in driver.page_source:
print "[!] Cannot access page "+url
return ""
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(1)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
html1 = driver.page_source
text_file = open(filename, "w")
text_file.write(normalize(html1))
text_file.close()
else:
html1 = open(filename, 'r').read()
soup1 = BeautifulSoup(html1)
htmlList = soup1.find("h5",{"class" : "_6nl"})
tlTime = soup1.find("abbr")
if " at " in str(htmlList):
soup2 = BeautifulSoup(str(htmlList))
locationList = soup2.findAll("a",{"class" : "profileLink"})
locUrl = locationList[len(locationList)-1]['href']
locDescription = locationList[len(locationList)-1].text
locTime = tlTime['data-utime']
placesVisitedList.append([locTime,locDescription,locUrl])
def parseLikesPosts(id):
peopleID = []
filename = 'likes_'+str(id)
if not os.path.lexists(filename):
print "[*] Caching Post Likes: "+str(id)
url = "https://www.facebook.com/browse/likes?id="+str(id)
driver.get(url)
if "Sorry, this page isn't available" in driver.page_source:
print "[!] Cannot access page "+url
return ""
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(1)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
html1 = driver.page_source
text_file = open(filename, "w")
text_file.write(normalize(html1))
text_file.close()
else:
html1 = open(filename, 'r').read()
soup1 = BeautifulSoup(html1)
peopleLikeList = soup1.findAll("div",{"class" : "fsl fwb fcb"})
if len(peopleLikeList)>0:
print "[*] Extracting Likes from Post: "+str(id)
for x in peopleLikeList:
soup2 = BeautifulSoup(str(x))
peopleLike = soup2.find("a")
peopleLikeID = peopleLike['href'].split('?')[0].replace('https://www.facebook.com/','')
if peopleLikeID == 'profile.php':
r = re.compile('id=(.*?)&fref')
m = r.search(str(peopleLike['href']))
if m:
peopleLikeID = m.group(1)
print "[*] Liked Post: "+"\t"+peopleLikeID
if peopleLikeID not in peopleID:
peopleID.append(peopleLikeID)
return peopleID
def parseTimeline(html,username):
soup = BeautifulSoup(html)
tlTime = soup.findAll("abbr")
temp123 = soup.findAll("div",{"role" : "article"})
placesCheckin = []
timeOfPostList = []
counter = 0
for y in temp123:
soup1 = BeautifulSoup(str(y))
tlDateTimeLoc = soup1.findAll("a",{"class" : "uiLinkSubtle"})
#Universal Time
try:
soup2 = BeautifulSoup(str(tlDateTimeLoc[0]))
tlDateTime = soup2.find("abbr")
#Facebook Post Link
tlLink = tlDateTimeLoc[0]['href']
try:
tz = get_localzone()
unixTime = str(tlDateTime['data-utime'])
localTime = (datetime.datetime.fromtimestamp(int(unixTime)).strftime('%Y-%m-%d %H:%M:%S'))
timePostList.append(localTime)
timeOfPost = localTime
timeOfPostList.append(localTime)
print "[*] Time of Post: "+localTime
except TypeError:
continue
if "posts" in tlLink:
#print tlLink.strip()
pageID = tlLink.split("/")
parsePost(pageID[3],username)
peopleIDLikes = parseLikesPosts(pageID[3])
try:
for id1 in peopleIDLikes:
global peopleIDList
global likesCountList
if id1 in peopleIDList:
lastCount = 0
position = peopleIDList.index(id1)
likesCountList[position] +=1
else:
peopleIDList.append(id1)
likesCountList.append(1)
except TypeError:
continue
if len(tlDateTimeLoc)>2:
try:
#Device / Location
if len(tlDateTimeLoc[1].text)>0:
print "[*] Location of Post: "+unicode(tlDateTimeLoc[1].text)
if len(tlDateTimeLoc[2].text)>0:
print "[*] Device: "+str(tlDateTimeLoc[2].text)
except IndexError:
continue
else:
try:
#Device / Location
if len(tlDateTimeLoc[1].text)>0:
if "mobile" in tlDateTimeLoc[1].text:
print "[*] Device: "+str(tlDateTimeLoc[1].text)
else:
print "[*] Location of Post: "+unicode(tlDateTimeLoc[1].text)
except IndexError:
continue
#Facebook Posts
tlPosts = soup1.find("span",{"class" : "userContent"})
try:
tlPostSec = soup1.findall("span",{"class" : "userContentSecondary fcg"})
tlPostMsg = ""
#Places Checked In
except TypeError:
continue
soup3 = BeautifulSoup(str(tlPostSec))
hrefLink = soup3.find("a")
"""
if len(str(tlPostSec))>0:
tlPostMsg = str(tlPostSec)
#if " at " in str(tlPostMsg) and " with " not in str(tlPostMsg):
if " at " in str(tlPostMsg):
print str(tlPostSec)
print tlPostMsg
#print hrefLink
#placeUrl = hrefLink['href'].encode('utf8').split('?')[0]
#print "[*] Place: "+placeUrl
#placesCheckin.append([timeOfPost,placeUrl])
"""
try:
if len(tlPosts)>0:
tlPostStr = re.sub('<[^>]*>', '', str(tlPosts))
if tlPostStr!=None:
print "[*] Message: "+str(tlPostStr)
except TypeError as e:
continue
tlPosts = soup1.find("div",{"class" : "translationEligibleUserMessage userContent"})
try:
if len(tlPosts)>0:
tlPostStr = re.sub('<[^>]*>', '', str(tlPosts))
print "[*] Message: "+str(tlPostStr)
except TypeError:
continue
except IndexError as e:
continue
counter+=1
tlDeviceLoc = soup.findAll("a",{"class" : "uiLinkSubtle"})
print '\n'
global reportFileName
if len(reportFileName)<1:
reportFileName = username+"_report.txt"
reportFile = open(reportFileName, "w")
reportFile.write("\n********** Places Visited By "+str(username)+" **********\n")
filename = username+'_placesVisited.htm'
if not os.path.lexists(filename):
html = downloadPlacesVisited(driver,uid)
text_file = open(filename, "w")
text_file.write(html.encode('utf8'))
text_file.close()
else:
html = open(filename, 'r').read()
dataList = parsePlacesVisited(html)
count=1
for i in dataList:
reportFile.write(normalize(i[2])+'\t'+normalize(i[1])+'\t'+normalize(i[3])+'\n')
count+=1
reportFile.write("\n********** Places Liked By "+str(username)+" **********\n")
filename = username+'_placesLiked.htm'
if not os.path.lexists(filename):
html = downloadPlacesLiked(driver,uid)
text_file = open(filename, "w")
text_file.write(html.encode('utf8'))
text_file.close()
else:
html = open(filename, 'r').read()
dataList = parsePlacesLiked(html)
count=1
for i in dataList:
reportFile.write(normalize(i[2])+'\t'+normalize(i[1])+'\t'+normalize(i[3])+'\n')
count+=1
reportFile.write("\n********** Places checked in **********\n")
for places in placesVisitedList:
unixTime = places[0]
localTime = (datetime.datetime.fromtimestamp(int(unixTime)).strftime('%Y-%m-%d %H:%M:%S'))
reportFile.write(localTime+'\t'+normalize(places[1])+'\t'+normalize(places[2])+'\n')
reportFile.write("\n********** Apps used By "+str(username)+" **********\n")
filename = username+'_apps.htm'
if not os.path.lexists(filename):
html = downloadAppsUsed(driver,uid)
text_file = open(filename, "w")
text_file.write(html.encode('utf8'))
text_file.close()
else:
html = open(filename, 'r').read()
data1 = parseAppsUsed(html)
result = ""
for x in data1:
reportFile.write(normalize(x)+'\n')
x = x.lower()
if "blackberry" in x:
result += "[*] User is using a Blackberry device\n"
if "android" in x:
result += "[*] User is using an Android device\n"
if "ios" in x or "ipad" in x or "iphone" in x:
result += "[*] User is using an iOS Apple device\n"
if "samsung" in x:
result += "[*] User is using a Samsung Android device\n"
reportFile.write(result)
reportFile.write("\n********** Videos Posted By "+str(username)+" **********\n")
filename = username+'_videosBy.htm'
if not os.path.lexists(filename):
html = downloadVideosBy(driver,uid)
text_file = open(filename, "w")
text_file.write(html.encode('utf8'))
text_file.close()
else:
html = open(filename, 'r').read()
dataList = parseVideosBy(html)
count=1
for i in dataList:
reportFile.write(normalize(i[2])+'\t'+normalize(i[1])+'\n')
count+=1
reportFile.write("\n********** Pages Liked By "+str(username)+" **********\n")
filename = username+'_pages.htm'
if not os.path.lexists(filename):
print "[*] Caching Pages Liked: "+username
html = downloadPagesLiked(driver,uid)
text_file = open(filename, "w")
text_file.write(html.encode('utf8'))
text_file.close()
else:
html = open(filename, 'r').read()
dataList = parsePagesLiked(html)
for i in dataList:
pageName = normalize(i[0])
tmpStr = normalize(i[3])+'\t'+normalize(i[2])+'\t'+normalize(i[1])+'\n'
reportFile.write(tmpStr)
print "\n"
c = conn.cursor()
reportFile.write("\n********** Friendship History of "+str(username)+" **********\n")
c.execute('select * from friends where sourceUID=?',(uid,))
dataList = c.fetchall()
try:
if len(str(dataList[0][4]))>0:
for i in dataList:
#Date First followed by Username
reportFile.write(normalize(i[4])+'\t'+normalize(i[3])+'\t'+normalize(i[2])+'\t'+normalize(i[1])+'\n')
#Username followed by Date
#reportFile.write(normalize(i[4])+'\t'+normalize(i[3])+'\t'+normalize(i[2])+'\t'+normalize(i[1])+'\n')
print '\n'
except IndexError:
pass
reportFile.write("\n********** Friends of "+str(username)+" **********\n")
reportFile.write("*** Backtracing from Facebook Likes/Comments/Tags ***\n\n")
c = conn.cursor()
c.execute('select userName from friends where sourceUID=?',(uid,))
dataList = c.fetchall()
for i in dataList:
reportFile.write(str(i[0])+'\n')
print '\n'
tempList = []
totalLen = len(timeOfPostList)
timeSlot1 = 0
timeSlot2 = 0
timeSlot3 = 0
timeSlot4 = 0
timeSlot5 = 0
timeSlot6 = 0
timeSlot7 = 0
timeSlot8 = 0
count = 0
if len(peopleIDList)>0:
likesCountList, peopleIDList = zip(*sorted(zip(likesCountList,peopleIDList),reverse=True))
reportFile.write("\n********** Analysis of Facebook Post Likes **********\n")
while count<len(peopleIDList):
testStr = str(likesCountList[count]).encode('utf8')+'\t'+str(peopleIDList[count]).encode('utf8')
reportFile.write(testStr+"\n")
count+=1
reportFile.write("\n********** Analysis of Interactions between "+str(username)+" and Friends **********\n")
c = conn.cursor()
c.execute('select userName from friends where sourceUID=?',(uid,))
dataList = c.fetchall()
photosliked = []
photoscommented = []
userID = []
photosLikedUser = []
photosLikedCount = []
photosCommentedUser = []
photosCommentedCount = []
for i in dataList:
c.execute('select * from photosLiked where sourceUID=? and username=?',(uid,i[0],))
dataList1 = []
dataList1 = c.fetchall()
if len(dataList1)>0:
photosLikedUser.append(normalize(i[0]))
photosLikedCount.append(len(dataList1))
for i in dataList:
c.execute('select * from photosCommented where sourceUID=? and username=?',(uid,i[0],))
dataList1 = []
dataList1 = c.fetchall()
if len(dataList1)>0:
photosCommentedUser.append(normalize(i[0]))
photosCommentedCount.append(len(dataList1))
if(len(photosLikedCount)>1):
reportFile.write("Photo Likes: "+str(username)+" and Friends\n")
photosLikedCount, photosLikedUser = zip(*sorted(zip(photosLikedCount, photosLikedUser),reverse=True))
count=0
while count<len(photosLikedCount):
tmpStr = str(photosLikedCount[count])+'\t'+normalize(photosLikedUser[count])+'\n'
count+=1
reportFile.write(tmpStr)
if(len(photosCommentedCount)>1):
reportFile.write("\n********** Comments on "+str(username)+"'s Photos **********\n")
photosCommentedCount, photosCommentedUser = zip(*sorted(zip(photosCommentedCount, photosCommentedUser),reverse=True))
count=0
while count<len(photosCommentedCount):
tmpStr = str(photosCommentedCount[count])+'\t'+normalize(photosCommentedUser[count])+'\n'
count+=1
reportFile.write(tmpStr)
reportFile.write("\n********** Analysis of Time in Facebook **********\n")
for timePost in timeOfPostList:
tempList.append(timePost.split(" ")[1])
tempTime = (timePost.split(" ")[1]).split(":")[0]
tempTime = int(tempTime)
if tempTime >= 21:
timeSlot8+=1
if tempTime >= 18 and tempTime < 21:
timeSlot7+=1
if tempTime >= 15 and tempTime < 18:
timeSlot6+=1
if tempTime >= 12 and tempTime < 15:
timeSlot5+=1
if tempTime >= 9 and tempTime < 12:
timeSlot4+=1
if tempTime >= 6 and tempTime < 9:
timeSlot3+=1
if tempTime >= 3 and tempTime < 6:
timeSlot2+=1
if tempTime >= 0 and tempTime < 3:
timeSlot1+=1
reportFile.write("Total % (00:00 to 03:00) "+str((timeSlot1/totalLen)*100)+" %\n")
reportFile.write("Total % (03:00 to 06:00) "+str((timeSlot2/totalLen)*100)+" %\n")
reportFile.write("Total % (06:00 to 09:00) "+str((timeSlot3/totalLen)*100)+" %\n")
reportFile.write("Total % (09:00 to 12:00) "+str((timeSlot4/totalLen)*100)+" %\n")
reportFile.write("Total % (12:00 to 15:00) "+str((timeSlot5/totalLen)*100)+" %\n")
reportFile.write("Total % (15:00 to 18:00) "+str((timeSlot6/totalLen)*100)+" %\n")
reportFile.write("Total % (18:00 to 21:00) "+str((timeSlot7/totalLen)*100)+" %\n")
reportFile.write("Total % (21:00 to 24:00) "+str((timeSlot8/totalLen)*100)+" %\n")
"""
reportFile.write("\nDate/Time of Facebook Posts\n")
for timePost in timeOfPostList:
reportFile.write(timePost+'\n')
"""
reportFile.close()
def downloadTimeline(username):
url = 'https://www.facebook.com/'+username.strip()
driver.get(url)
print "[*] Crawling Timeline"
if "Sorry, this page isn't available" in driver.page_source:
print "[!] Cannot access page "+url
return ""
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
lastCount = lenOfPage
time.sleep(3)
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
print "[*] Looking for 'Show Older Stories' Link"
try:
clickLink = WebDriverWait(driver, 1).until(lambda driver : driver.find_element_by_link_text('Show Older Stories'))
if clickLink:
print "[*] Clicked 'Show Older Stories' Link"
driver.find_element_by_link_text('Show Older Stories').click()
else:
print "[*] Indexing Timeline"
break
match=True
except TimeoutException:
match = True
return driver.page_source
def downloadPlacesVisited(driver,userid):
url = 'https://www.facebook.com/search/'+str(userid).strip()+'/places-visited'
driver.get(url)
if "Sorry, this page isn't available" in driver.page_source:
print "[!] Cannot access page "+url
return ""
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadPlacesLiked(driver,userid):
url = 'https://www.facebook.com/search/'+str(userid).strip()+'/places-liked'
driver.get(url)
if "Sorry, this page isn't available" in driver.page_source:
print "[!] Cannot access page "+url
return ""
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadVideosBy(driver,userid):
url = 'https://www.facebook.com/search/'+str(userid).strip()+'/videos-by'
driver.get(url)
if "Sorry, this page isn't available" in driver.page_source:
print "[!] Cannot access page "+url
return ""
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadUserInfo(driver,userid):
url = 'https://www.facebook.com/'+str(userid).strip()+'/info'
driver.get(url)
if "Sorry, this page isn't available" in driver.page_source:
print "[!] Cannot access page "+url
return ""
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadPhotosBy(driver,userid):
driver.get('https://www.facebook.com/search/'+str(userid)+'/photos-by')
if "Sorry, we couldn't find any results for this search." in driver.page_source:
print "Photos commented list is hidden"
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadPhotosOf(driver,userid):
driver.get('https://www.facebook.com/search/'+str(userid)+'/photos-of')
if "Sorry, we couldn't find any results for this search." in driver.page_source:
print "Photos commented list is hidden"
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadPhotosCommented(driver,userid):
driver.get('https://www.facebook.com/search/'+str(userid)+'/photos-commented')
if "Sorry, we couldn't find any results for this search." in driver.page_source:
print "Photos commented list is hidden"
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadPhotosLiked(driver,userid):
driver.get('https://www.facebook.com/search/'+str(userid)+'/photos-liked')
if "Sorry, we couldn't find any results for this search." in driver.page_source:
print "Pages liked list is hidden"
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(2)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadPagesLiked(driver,userid):
driver.get('https://www.facebook.com/search/'+str(userid)+'/pages-liked')
if "Sorry, we couldn't find any results for this search." in driver.page_source:
print "Pages liked list is hidden"
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadFriends(driver,userid):
driver.get('https://www.facebook.com/search/'+str(userid)+'/friends')
if "Sorry, we couldn't find any results for this search." in driver.page_source:
print "Friends list is hidden"
return ""
else:
#assert "Friends of " in driver.title
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
time.sleep(3)
lastCount = lenOfPage
lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
return driver.page_source
def downloadAppsUsed(driver,userid):
driver.get('https://www.facebook.com/search/'+str(userid)+'/apps-used')
if "Sorry, we couldn't find any results for this search." in driver.page_source: