forked from Greenwolf/social_mapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
social_mapper.py
1433 lines (1332 loc) · 66.1 KB
/
social_mapper.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
from __future__ import print_function
from modules import facebookfinder
from modules import twitterfinder
from modules import instagramfinder
from modules import linkedinfinder
from modules import vkontaktefinder
from modules import weibofinder
from modules import doubanfinder
from shutil import copyfile
import facebook
import requests
import sys
import csv
import face_recognition
import urllib
import os
import codecs
import argparse
import shutil
import http.cookiejar
import json
from datetime import datetime
from bs4 import BeautifulSoup
from django.utils import encoding
import traceback
import math
assert sys.version_info >= (3,), "Only Python 3 is currently supported."
global linkedin_username
global linkedin_password
linkedin_username = ""
linkedin_password = ""
global facebook_username
global facebook_password
facebook_username = ""
facebook_password = ""
global twitter_username
global twitter_password
twitter_username = ""
twitter_password = ""
global instagram_username
global instagram_password
instagram_username = ""
instagram_password = ""
global vk_username
global vk_password
vk_username = "" # Can be mobile or email
vk_password = ""
global weibo_username
global weibo_password
weibo_username = "" # Can be mobile
weibo_password = ""
global douban_username
global douban_password
douban_username = ""
douban_password = ""
startTime = datetime.now()
class Person(object):
first_name = ""
last_name = ""
full_name = ""
person_image = ""
person_imagelink = ""
linkedin = ""
linkedinimage = ""
facebook = ""
facebookimage = "" # higher quality but needs authentication to access
facebookcdnimage = "" # lower quality but no authentication, used for HTML output
twitter = ""
twitterimage = ""
instagram = ""
instagramimage = ""
vk = ""
vkimage = ""
weibo = ""
weiboimage = ""
douban = ""
doubanimage = ""
def __init__(self, first_name, last_name, full_name, person_image):
self.first_name = first_name
self.last_name = last_name
self.full_name = full_name
self.person_image = person_image
class PotentialPerson(object):
full_name = ""
profile_link = ""
image_link = ""
def __init__(self, full_name, profile_link, image_link):
self.full_name = full_name
self.profile_link = profile_link
self.image_link = image_link
def fill_facebook(peoplelist):
FacebookfinderObject = facebookfinder.Facebookfinder(showbrowser)
FacebookfinderObject.doLogin(facebook_username,facebook_password)
count=1
ammount=len(peoplelist)
for person in peoplelist:
if args.vv == True:
print("Facebook Check %i/%i : %s" % (count,ammount,person.full_name))
else:
sys.stdout.write("\rFacebook Check %i/%i : %s " % (count,ammount,person.full_name))
sys.stdout.flush()
count = count + 1
# Testcode to mimic a session timeout
#if count == 3:
# print "triggered delete"
# FacebookfinderObject.testdeletecookies()
if person.person_image:
try:
target_image = face_recognition.load_image_file(person.person_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
profilelist = FacebookfinderObject.getFacebookProfiles(person.first_name, person.last_name,facebook_username,facebook_password)
except:
continue
else:
continue
early_break = False
updatedlist = []
#for profilelink,distance in profilelist:
for profilelink,profilepic,distance,cdnpicture in profilelist:
try:
os.remove("potential_target_image.jpg")
except:
pass
if early_break:
break
#image_link = FacebookfinderObject.getProfilePicture(profilelink)
image_link = profilepic
#print profilelink
#print image_link
#print "----"
cookies = FacebookfinderObject.getCookies()
if image_link:
try:
# Set fake user agent as Facebook blocks Python requests default user agent
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14'}
# Get target image using requests, providing Selenium cookies, and fake user agent
response = requests.get(image_link, cookies=cookies,headers=headers,stream=True)
with open('potential_target_image.jpg', 'wb') as out_file:
# Facebook images are sent content encoded so need to decode them
response.raw.decode_content = True
shutil.copyfileobj(response.raw, out_file)
del response
potential_target_image = face_recognition.load_image_file("potential_target_image.jpg")
try: # try block for when an image has no faces
potential_target_encoding = face_recognition.face_encodings(potential_target_image)[0]
except:
continue
results = face_recognition.face_distance([target_encoding], potential_target_encoding)
for result in results:
#print profilelink + " + " + cdnpicture + " + " + image_link
#print result
#print ""
# check here to do early break if using fast mode, otherwise if accurate set highest distance in array then do a check for highest afterwards
if args.mode == "fast":
if result < threshold:
person.facebook = encoding.smart_str(profilelink, encoding='ascii', errors='ignore')
person.facebookimage = encoding.smart_str(image_link, encoding='ascii', errors='ignore')
person.facebookcdnimage = encoding.smart_str(cdnpicture, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tFacebook: " + person.facebook)
early_break = True
break
elif args.mode == "accurate":
# code for accurate mode here, check if result is higher than current distance (best match in photo with multiple people) and store highest for later comparison
if result < threshold:
#print "Adding to updated list"
#print distance
#print "Match over threshold: \n" + profilelink + "\n" + result
updatedlist.append([profilelink,image_link,result,cdnpicture])
except Exception as e:
print(e)
#print(e)
#print "Error getting image link, retrying login and getting fresh cookies"
#FacebookfinderObject.doLogin(facebook_username,facebook_password)
#cookies = FacebookfinderObject.getCookies()
continue
# For accurate mode pull out largest distance and if it's bigger than the threshold then it's the most accurate result
if args.mode == "accurate":
highestdistance=1.0
bestprofilelink=""
bestimagelink=""
for profilelink,image_link,distance,cdnpicture in updatedlist:
if distance < highestdistance:
highestdistance = distance
bestprofilelink = profilelink
bestimagelink = image_link
bestcdnpicture = cdnpicture
if highestdistance < threshold:
person.facebook = encoding.smart_str(bestprofilelink, encoding='ascii', errors='ignore')
person.facebookimage = encoding.smart_str(bestimagelink, encoding='ascii', errors='ignore')
person.facebookcdnimage = encoding.smart_str(bestcdnpicture, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tFacebook: " + person.facebook)
try:
FacebookfinderObject.kill()
except:
print("Error Killing Facebook Selenium instance")
return peoplelist
def fill_twitter(peoplelist):
TwitterfinderObject = twitterfinder.Twitterfinder(showbrowser)
TwitterfinderObject.doLogin(twitter_username,twitter_password)
count=1
ammount=len(peoplelist)
for person in peoplelist:
if args.vv == True:
print("Twitter Check %i/%i : %s" % (count,ammount,person.full_name))
else:
sys.stdout.write("\rTwitter Check %i/%i : %s " % (count,ammount,person.full_name))
sys.stdout.flush()
count = count + 1
if person.person_image:
try:
target_image = face_recognition.load_image_file(person.person_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
profilelist = TwitterfinderObject.getTwitterProfiles(person.first_name, person.last_name)
except:
continue
else:
continue
early_break = False
updatedlist = []
for profilelink,profilepic,distance in profilelist:
try:
os.remove("potential_target_image.jpg")
except:
pass
if early_break:
break
image_link = profilepic
if image_link:
try:
urllib.request.urlretrieve(image_link, "potential_target_image.jpg")
potential_target_image = face_recognition.load_image_file("potential_target_image.jpg")
try: # try block for when an image has no faces
potential_target_encoding = face_recognition.face_encodings(potential_target_image)[0]
except:
continue
results = face_recognition.face_distance([target_encoding], potential_target_encoding)
for result in results:
if args.mode == "fast":
if result < threshold:
person.twitter = encoding.smart_str(profilelink, encoding='ascii', errors='ignore')
person.twitterimage = encoding.smart_str(image_link, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tTwitter: " + person.twitter)
early_break = True
break
elif args.mode == "accurate":
if result < threshold:
updatedlist.append([profilelink,image_link,result])
except:
continue
if args.mode == "accurate":
highestdistance=1.0
bestprofilelink=""
bestimagelink=""
for profilelink,image_link,distance in updatedlist:
if distance < highestdistance:
highestdistance = distance
bestprofilelink = profilelink
bestimagelink = image_link
if highestdistance < threshold:
person.twitter = encoding.smart_str(bestprofilelink, encoding='ascii', errors='ignore')
person.twitterimage = encoding.smart_str(bestimagelink, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tTwitter: " + person.twitter)
try:
TwitterfinderObject.kill()
except:
print("Error Killing Twitter Selenium instance")
return peoplelist
def fill_instagram(peoplelist):
InstagramfinderObject = instagramfinder.Instagramfinder(showbrowser)
InstagramfinderObject.doLogin(instagram_username,instagram_password)
count=1
ammount=len(peoplelist)
for person in peoplelist:
if args.vv == True:
print("Instagram Check %i/%i : %s" % (count,ammount,person.full_name))
else:
sys.stdout.write("\rInstagram Check %i/%i : %s " % (count,ammount,person.full_name))
sys.stdout.flush()
count = count + 1
#if count == 3:
# print "triggered delete"
# InstagramfinderObject.testdeletecookies()
if person.person_image:
try:
target_image = face_recognition.load_image_file(person.person_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
profilelist = InstagramfinderObject.getInstagramProfiles(person.first_name, person.last_name,instagram_username,instagram_password)
#print "DEBUG"
#print profilelist
#print ""
except:
continue
else:
continue
early_break = False
#print "DEBUG: " + person.full_name
updatedlist = []
for profilelink,profilepic,distance in profilelist:
try:
os.remove("potential_target_image.jpg")
except:
pass
if early_break:
break
image_link = profilepic
if image_link:
try:
urllib.request.urlretrieve(image_link, "potential_target_image.jpg")
potential_target_image = face_recognition.load_image_file("potential_target_image.jpg")
try: # try block for when an image has no faces
potential_target_encoding = face_recognition.face_encodings(potential_target_image)[0]
except:
continue
results = face_recognition.face_distance([target_encoding], potential_target_encoding)
for result in results:
if args.mode == "fast":
if result < threshold:
person.instagram = encoding.smart_str(profilelink, encoding='ascii', errors='ignore')
person.instagramimage = encoding.smart_str(image_link, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tInstagram: " + person.instagram)
early_break = True
break
elif args.mode == "accurate":
if result < threshold:
#distance=result
updatedlist.append([profilelink,image_link,result])
except Exception as e:
print("ERROR")
print(e)
if args.mode == "accurate":
highestdistance=1.0
bestprofilelink=""
bestimagelink=""
for profilelink,image_link,distance in updatedlist:
if distance < highestdistance:
highestdistance = distance
bestprofilelink = profilelink
bestimagelink = image_link
if highestdistance < threshold:
person.instagram = encoding.smart_str(bestprofilelink, encoding='ascii', errors='ignore')
person.instagramimage = encoding.smart_str(bestimagelink, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tInstagram: " + person.instagram)
try:
InstagramfinderObject.kill()
except:
print("Error Killing Instagram Selenium instance")
return peoplelist
def fill_linkedin(peoplelist):
LinkedinfinderObject = linkedinfinder.Linkedinfinder(showbrowser)
LinkedinfinderObject.doLogin(linkedin_username,linkedin_password)
count=1
ammount=len(peoplelist)
for person in peoplelist:
if args.vv == True:
print("LinkedIn Check %i/%i : %s" % (count,ammount,person.full_name))
else:
sys.stdout.write("\rLinkedIn Check %i/%i : %s " % (count,ammount,person.full_name))
sys.stdout.flush()
count = count + 1
#if count == 3:
#print "triggered delete"
# LinkedinfinderObject.testdeletecookies()
if person.person_image:
try:
target_image = face_recognition.load_image_file(person.person_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
profilelist = LinkedinfinderObject.getLinkedinProfiles(person.first_name, person.last_name,linkedin_username,linkedin_password)
except:
continue
else:
continue
early_break = False
#print "DEBUG: " + person.full_name
updatedlist = []
for profilelink,profilepic,distance in profilelist:
try:
os.remove("potential_target_image.jpg")
except:
pass
if early_break:
break
image_link = profilepic
if image_link:
try:
urllib.request.urlretrieve(image_link, "potential_target_image.jpg")
potential_target_image = face_recognition.load_image_file("potential_target_image.jpg")
try: # try block for when an image has no faces
potential_target_encoding = face_recognition.face_encodings(potential_target_image)[0]
except:
continue
results = face_recognition.face_distance([target_encoding], potential_target_encoding)
for result in results:
if args.mode == "fast":
if result < threshold:
person.linkedin = encoding.smart_str(profilelink, encoding='ascii', errors='ignore')
person.linkedinimage = encoding.smart_str(image_link, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tLinkedIn: " + person.linkedin)
early_break = True
break
elif args.mode == "accurate":
if result < threshold:
#distance=result
updatedlist.append([profilelink,image_link,result])
except Exception as e:
print(e)
if args.mode == "accurate":
highestdistance=1.0
bestprofilelink=""
bestimagelink=""
for profilelink,image_link,distance in updatedlist:
if distance < highestdistance:
highestdistance = distance
bestprofilelink = profilelink
bestimagelink = image_link
if highestdistance < threshold:
person.linkedin = encoding.smart_str(bestprofilelink, encoding='ascii', errors='ignore')
person.linkedinimage = encoding.smart_str(bestimagelink, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tLinkedIn: " + person.linkedin)
try:
LinkedinfinderObject.kill()
except:
print("Error Killing LinkedIn Selenium instance")
return peoplelist
def fill_vkontakte(peoplelist):
VkontaktefinderObject = vkontaktefinder.Vkontaktefinder(showbrowser)
VkontaktefinderObject.doLogin(vk_username,vk_password)
count=1
ammount=len(peoplelist)
for person in peoplelist:
if args.vv == True:
print("VKontakte Check %i/%i : %s" % (count,ammount,person.full_name))
else:
sys.stdout.write("\rVKontakte Check %i/%i : %s " % (count,ammount,person.full_name))
sys.stdout.flush()
count = count + 1
if person.person_image:
try:
target_image = face_recognition.load_image_file(person.person_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
profilelist = VkontaktefinderObject.getVkontakteProfiles(person.first_name, person.last_name)
except:
continue
else:
continue
early_break = False
#print "DEBUG: " + person.full_name
updatedlist = []
for profilelink,profilepic,distance in profilelist:
try:
os.remove("potential_target_image.jpg")
except:
pass
if early_break:
break
image_link = profilepic
if image_link:
try:
urllib.request.urlretrieve(image_link, "potential_target_image.jpg")
potential_target_image = face_recognition.load_image_file("potential_target_image.jpg")
try: # try block for when an image has no faces
potential_target_encoding = face_recognition.face_encodings(potential_target_image)[0]
except:
continue
results = face_recognition.face_distance([target_encoding], potential_target_encoding)
for result in results:
if args.mode == "fast":
if result < threshold:
person.vk = encoding.smart_str(profilelink, encoding='ascii', errors='ignore')
person.vkimage = encoding.smart_str(image_link, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tVkontakte: " + person.vk)
early_break = True
break
elif args.mode == "accurate":
if result < threshold:
#distance=result
updatedlist.append([profilelink,image_link,result])
except Exception as e:
print(e)
if args.mode == "accurate":
highestdistance=1.0
bestprofilelink=""
bestimagelink=""
for profilelink,image_link,distance in updatedlist:
if distance < highestdistance:
highestdistance = distance
bestprofilelink = profilelink
bestimagelink = image_link
if highestdistance < threshold:
person.vk = encoding.smart_str(bestprofilelink, encoding='ascii', errors='ignore')
person.vkimage = encoding.smart_str(bestimagelink, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tVkontakte: " + person.vk)
try:
VkontaktefinderObject.kill()
except:
print("Error Killing VKontakte Selenium instance")
return peoplelist
def fill_weibo(peoplelist):
WeibofinderObject = weibofinder.Weibofinder(showbrowser)
WeibofinderObject.doLogin(weibo_username,weibo_password)
count=1
ammount=len(peoplelist)
for person in peoplelist:
if args.vv == True:
print("Weibo Check %i/%i : %s" % (count,ammount,person.full_name))
else:
sys.stdout.write("\rWeibo Check %i/%i : %s " % (count,ammount,person.full_name))
sys.stdout.flush()
count = count + 1
if person.person_image:
try:
target_image = face_recognition.load_image_file(person.person_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
profilelist = WeibofinderObject.getWeiboProfiles(person.first_name, person.last_name)
except:
continue
else:
continue
early_break = False
#print "DEBUG: " + person.full_name
updatedlist = []
for profilelink,profilepic,distance in profilelist:
try:
os.remove("potential_target_image.jpg")
except:
pass
if early_break:
break
image_link = profilepic
if image_link:
try:
urllib.request.urlretrieve(image_link, "potential_target_image.jpg")
potential_target_image = face_recognition.load_image_file("potential_target_image.jpg")
try: # try block for when an image has no faces
potential_target_encoding = face_recognition.face_encodings(potential_target_image)[0]
except:
continue
results = face_recognition.face_distance([target_encoding], potential_target_encoding)
for result in results:
if args.mode == "fast":
if result < threshold:
person.weibo = encoding.smart_str(profilelink, encoding='ascii', errors='ignore')
person.weiboimage = encoding.smart_str(image_link, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tWeibo: " + person.weibo)
early_break = True
break
elif args.mode == "accurate":
if result < threshold:
#distance=result
updatedlist.append([profilelink,image_link,result])
except Exception as e:
print(e)
if args.mode == "accurate":
highestdistance=1.0
bestprofilelink=""
bestimagelink=""
for profilelink,image_link,distance in updatedlist:
if distance < highestdistance:
highestdistance = distance
bestprofilelink = profilelink
bestimagelink = image_link
if highestdistance < threshold:
person.weibo = encoding.smart_str(bestprofilelink, encoding='ascii', errors='ignore')
person.weiboimage = encoding.smart_str(bestimagelink, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tWeibo: " + person.weibo)
try:
WeibofinderObject.kill()
except:
print("Error Killing Weibo Selenium instance")
return peoplelist
def fill_douban(peoplelist):
DoubanfinderObject = doubanfinder.Doubanfinder(showbrowser)
DoubanfinderObject.doLogin(douban_username,douban_password)
count=1
ammount=len(peoplelist)
for person in peoplelist:
if args.vv == True:
print("Douban Check %i/%i : %s" % (count,ammount,person.full_name))
else:
sys.stdout.write("\rDouban Check %i/%i : %s " % (count,ammount,person.full_name))
sys.stdout.flush()
count = count + 1
if person.person_image:
try:
target_image = face_recognition.load_image_file(person.person_image)
target_encoding = face_recognition.face_encodings(target_image)[0]
profilelist = DoubanfinderObject.getDoubanProfiles(person.first_name, person.last_name)
except:
continue
else:
continue
early_break = False
#print "DEBUG: " + person.full_name
updatedlist = []
for profilelink,profilepic,distance in profilelist:
try:
os.remove("potential_target_image.jpg")
except:
pass
if early_break:
break
image_link = profilepic
if image_link:
try:
urllib.request.urlretrieve(image_link, "potential_target_image.jpg")
potential_target_image = face_recognition.load_image_file("potential_target_image.jpg")
try: # try block for when an image has no faces
potential_target_encoding = face_recognition.face_encodings(potential_target_image)[0]
except:
continue
results = face_recognition.face_distance([target_encoding], potential_target_encoding)
for result in results:
if args.mode == "fast":
if result < threshold:
person.douban = encoding.smart_str(profilelink, encoding='ascii', errors='ignore')
person.doubanimage = encoding.smart_str(image_link, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tDouban: " + person.douban)
early_break = True
break
elif args.mode == "accurate":
if result < threshold:
#distance=result
updatedlist.append([profilelink,image_link,result])
except Exception as e:
print(e)
if args.mode == "accurate":
highestdistance=1.0
bestprofilelink=""
bestimagelink=""
for profilelink,image_link,distance in updatedlist:
if distance < highestdistance:
highestdistance = distance
bestprofilelink = profilelink
bestimagelink = image_link
if highestdistance < threshold:
person.douban = encoding.smart_str(bestprofilelink, encoding='ascii', errors='ignore')
person.doubanimage = encoding.smart_str(bestimagelink, encoding='ascii', errors='ignore')
if args.vv == True:
print("\tMatch found: " + person.full_name)
print("\tDouban: " + person.douban)
try:
DoubanfinderObject.kill()
except:
print("Error Killing Douban Selenium instance")
return peoplelist
# Login function for LinkedIn for company browsing (Credits to LinkedInt from MDSec)
def login():
cookie_filename = "cookies.txt"
cookiejar = http.cookiejar.MozillaCookieJar(cookie_filename)
opener = urllib.request.build_opener(urllib.request.HTTPRedirectHandler(),urllib.request.HTTPHandler(debuglevel=0),urllib.request.HTTPSHandler(debuglevel=0),urllib.request.HTTPCookieProcessor(cookiejar))
page = loadPage(opener, "https://www.linkedin.com/uas/login")
parse = BeautifulSoup(page, "html.parser")
csrf = ""
for link in parse.find_all('input'):
name = link.get('name')
if name == 'loginCsrfParam':
csrf = link.get('value')
login_data = urllib.parse.urlencode({'session_key': linkedin_username, 'session_password': linkedin_password, 'loginCsrfParam': csrf})
page = loadPage(opener,"https://www.linkedin.com/checkpoint/lg/login-submit", login_data)
parse = BeautifulSoup(page, "html.parser")
cookie = ""
try:
cookie = cookiejar._cookies['.www.linkedin.com']['/']['li_at'].value
except:
print("cookie debug")
sys.exit(0)
cookiejar.save()
os.remove(cookie_filename)
return cookie
def authenticate():
try:
a = login()
print(a)
session = a
if len(session) == 0:
sys.exit("[!] Unable to login to LinkedIn.com")
print(("[*] Obtained new session: %s" % session))
cookies = dict(li_at=session)
except Exception as e:
sys.exit("[!] Could not authenticate to LinkedIn. %s" % e)
return cookies
def loadPage(client, url, data=None):
try:
response = client.open(url)
except:
print("[!] Cannot load main LinkedIn page")
try:
if data is not None:
response = client.open(url, data.encode("utf-8"))
else:
response = client.open(url)
emptybyte = bytearray()
return emptybyte.join(response.readlines())
except:
print("loadpage debug")
traceback.print_exc()
sys.exit(0)
#Setup Argument parser to print help and lock down options
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='Social Mapper by Jacob Wilkin (Greenwolf)',
usage='%(prog)s -f <format> -i <input> -m <mode> -t <threshold> <options>')
parser.add_argument('-v', '--version', action='version',
version='%(prog)s 0.1.0 : Social Mapper by Greenwolf (Github Link Here)')
parser.add_argument('-vv', '--verbose', action='store_true',dest='vv',help='Verbose Mode')
parser.add_argument('-f', '--format',action='store', dest='format',required=True,choices=set(("csv","imagefolder","company","socialmapper")),
help='Specify if the input file is either a \'company\',a \'CSV\',a \'imagefolder\' or a Social Mapper HTML file to resume')
parser.add_argument('-i', '--input',action='store', dest='input',required=True,
help='The name of the CSV file, input folder or company name to use as input')
parser.add_argument('-m', '--mode',action='store', dest='mode',required=True,choices=set(("accurate","fast")),
help='Selects the mode either accurate or fast, fast will report the first match over the threshold while accurate will check for the highest match over the threshold')
parser.add_argument('-t', '--threshold',action='store', dest='thresholdinput',required=False,choices=set(("loose","standard","strict","superstrict")),
help='The strictness level for image matching, default is standard but can be specified to loose, standard, strict or superstrict')
parser.add_argument('-e', '--email',action='store', dest='email',required=False,
help='Provide an email format to trigger phishing list generation output, should follow a convention such as "<first><last><f><l>@domain.com"')
parser.add_argument('-cid', '--companyid',action='store', dest='companyid',required=False,
help='Provide an optional company id, for use with \'-f company\' only')
parser.add_argument('-s', '--showbrowser',action='store_true',dest='showbrowser',help='If flag is set then browser will be visible')
parser.add_argument('-a', '--all',action='store_true',dest='a',help='Flag to check all social media sites')
parser.add_argument('-fb', '--facebook',action='store_true',dest='fb',help='Flag to check Facebook')
parser.add_argument('-tw', '--twitter',action='store_true',dest='tw',help='Flag to check Twitter')
parser.add_argument('-ig', '--instagram',action='store_true',dest='ig',help='Flag to check Instagram')
parser.add_argument('-li', '--linkedin',action='store_true',dest='li',help='Flag to check LinkedIn - Automatic with \'company\' input type')
parser.add_argument('-vk', '--vkontakte',action='store_true',dest='vk',help='Flag to check the Russian VK VKontakte Site')
parser.add_argument('-wb', '--weibo',action='store_true',dest='wb',help='Flag to check the Chinese Weibo Site')
parser.add_argument('-db', '--douban',action='store_true',dest='db',help='Flag to check the Chinese Douban Site')
args = parser.parse_args()
if not (args.a or args.fb or args.tw or args.ig or args.li or args.vk or args.wb or args.db):
parser.error('No sites specified requested, add -a for all, or a combination of the sites you want to check using a mix of -fb -tw -ig -li -vk -db -wb')
# Set up face matching threshold
threshold = 0.6
try:
if args.thresholdinput == "superstrict":
threshold = 0.4
if args.thresholdinput == "strict":
threshold = 0.5
if args.thresholdinput == "standard":
threshold = 0.6
if args.thresholdinput == "loose":
threshold = 0.7
except:
pass
if args.showbrowser:
showbrowser=True
else:
showbrowser=False
exit=True
# remove targets dir for remaking
if os.path.exists('temp-targets'):
shutil.rmtree('temp-targets')
# people list to hold people in memory
peoplelist = []
# Fill people list from document with just name + image link
if args.format == "csv":
exit=False
file = open(args.input, 'rb')
data = file.read()
file.close()
try:
os.remove('temp.csv')
except OSError:
pass
tempcsv = open('temp.csv', 'w')
tempcsv.write(data.replace('\x00',''))
tempcsv.close()
if not os.path.exists('temp-targets'):
os.makedirs('temp-targets')
filereader = csv.reader(open('temp.csv', 'rb'), delimiter=",")
for full_name, person_image in filereader:
try:
full_name = encoding.smart_str(full_name, encoding='ascii', errors='ignore')
person_image = encoding.smart_str(person_image, encoding='ascii', errors='ignore')
#print person_image
urllib.request.urlretrieve(person_image, "temp-targets/" + full_name + ".jpg")
first_name = full_name.split(" ")[0]
last_name = full_name.split(" ",1)[1]
person = Person(first_name, last_name, full_name, "temp-targets/" + full_name + ".jpg")
person.person_imagelink = person_image
peoplelist.append(person)
except Exception as e:
print("Error getting image or creating person structure, skipping:" + full_name)
#remove this when fixed downloading
#sys.exit(1)
# Parse image folder full of images and names into social_mapper
if args.format == "imagefolder":
if not args.input.endswith("/"):
args.input = args.input + "/"
exit=False
for filename in os.listdir(args.input):
if filename.endswith(".jpg") or filename.endswith(".png")or filename.endswith(".jpeg"):
full_name = filename.split(".")[0]
first_name = full_name.split(" ")[0]
try:
last_name = full_name.split(" ")[1]
except:
last_name = ""
first_name = encoding.smart_str(first_name, encoding='ascii', errors='ignore')
last_name = encoding.smart_str(last_name, encoding='ascii', errors='ignore')
full_name = encoding.smart_str(full_name, encoding='ascii', errors='ignore')
person = Person(first_name, last_name, full_name, args.input + filename)
person.person_imagelink = args.input + filename
peoplelist.append(person)
# Get targets from LinkedIn company search
if args.format == "company":
exit=False
if not os.path.exists('temp-targets'):
os.makedirs('temp-targets')
cookies = authenticate() # perform authentication
companyid = 0
if args.companyid is not None: # Don't find company id, use provided id from -cid or --companyid flag
print("Using supplied company Id: %s" % args.companyid)
companyid = args.companyid
else:
# code to get company ID based on name
companyid = 0
url = "https://www.linkedin.com/voyager/api/typeahead/hits?q=blended&query=%s" % args.input
headers = {'Csrf-Token':'ajax:0397788525211216808', 'X-RestLi-Protocol-Version':'2.0.0'}
cookies['JSESSIONID'] = 'ajax:0397788525211216808'
r = requests.get(url, cookies=cookies, headers=headers)
content = json.loads(r.text)
firstID = 0
for i in range(0,len(content['elements'])):
try:
companyid = content['elements'][i]['hitInfo']['com.linkedin.voyager.typeahead.TypeaheadCompany']['id']
if firstID == 0:
firstID = companyid
print("[Notice] Found company ID: %s" % companyid)
except:
continue
companyid = firstID
if companyid == 0:
print("[WARNING] No valid company ID found in auto, please restart and find your own")
sys.exit(1)
print("[*] Using company ID: %s" % companyid)
url = "https://www.linkedin.com/voyager/api/search/cluster?count=40&guides=List(v->PEOPLE,facetCurrentCompany->%s)&origin=OTHER&q=guided&start=0" % (companyid)
headers = {'Csrf-Token':'ajax:0397788525211216808', 'X-RestLi-Protocol-Version':'2.0.0'}
cookies['JSESSIONID'] = 'ajax:0397788525211216808'
r = requests.get(url, cookies=cookies, headers=headers)
content = json.loads(r.text)
data_total = content['elements'][0]['total']
# Calculate pages off final results at 40 results/page
pages = math.ceil(data_total / 40)
if pages == 0:
pages = 1
if data_total % 40 == 0:
# Because we count 0... Subtract a page if there are no left over results on the last page
pages = pages - 1
if pages == 0:
print("[!] Try to use quotes in the search name")
sys.exit(0)
print("[*] %i Results Found" % data_total)
if data_total > 1000:
pages = 25
print("[*] LinkedIn only allows 1000 results. Refine keywords to capture all data")
print("[*] Fetching %i Pages" % pages)
print()
companyname = args.input.strip("\"")
for p in range(pages):
url = "https://www.linkedin.com/voyager/api/search/cluster?count=40&guides=List(v->PEOPLE,facetCurrentCompany->%s)&origin=OTHER&q=guided&start=%i" % (companyid, p*40)
r = requests.get(url, cookies=cookies, headers=headers)
content = r.text.encode('UTF-8')
content = json.loads(content)
#print "[*] Fetching page %i with %i results for %s" % ((p),len(content['elements'][0]['elements']),companyname)
sys.stdout.write("\r[*] Fetching page %i/%i with %i results for %s" % ((p),pages,len(content['elements'][0]['elements']),companyname))
sys.stdout.flush()
# code to get users, for each user with a picture create a person
for c in content['elements'][0]['elements']:
if 'com.linkedin.voyager.search.SearchProfile' in c['hitInfo'] and c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['headless'] == False:
try:
# get the link to profile pic, link to LinkedIn profile page, and their full name
#person_image = "https://media.licdn.com/mpr/mpr/shrinknp_400_400%s" % c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['picture']['com.linkedin.voyager.common.MediaProcessorImage']['id']
first_name = c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['firstName']
first_name = encoding.smart_str(first_name, encoding='ascii', errors='ignore')
first_name = first_name.lower()
last_name = c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['lastName']
last_name = encoding.smart_str(last_name, encoding='ascii', errors='ignore')
last_name = last_name.lower()
# Around 30% of people keep putting Certs in last name, so strip these out.
last_name = last_name.split(' ',1)[0]
full_name = first_name + " " + last_name
#full_name = re.sub("[^a-zA-Z ]+", "", full_name)
rooturl = c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['picture']['com.linkedin.common.VectorImage']['rootUrl']
artifact = c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['picture']['com.linkedin.common.VectorImage']['artifacts'][3]['fileIdentifyingUrlPathSegment']
person_image = rooturl + artifact
person_image = encoding.smart_str(person_image, encoding='ascii', errors='ignore')
linkedin = "https://www.linkedin.com/in/%s" % c['hitInfo']['com.linkedin.voyager.search.SearchProfile']['miniProfile']['publicIdentifier']
linkedin = encoding.smart_str(linkedin, encoding='ascii', errors='ignore')
urllib.request.urlretrieve(person_image, "temp-targets/" + full_name + ".jpg")
person = Person(first_name, last_name, full_name, "temp-targets/" + full_name + ".jpg")
person.person_imagelink = person_image
person.linkedin = linkedin
person.linkedinimage = person_image
peoplelist.append(person)
#print person.linkedin
#print person_image
except Exception as e:
# This triggers when a profile doesn't have an image associated with it
continue
# To continue a Social Mapper run for additional sites.
if args.format == "socialmapper":
if args.a == True:
print("This option is for adding additional sites to a Social Mapper report\nFeed in a Social Mapper HTML file that's only been partially run, for example:\nFirst run (LinkedIn, Facebook, Twitter): python social_mapper -f company -i \"SpiderLabs\" -m fast -t standard -li -fb -tw\n Second run (adding Instagram): python social_mapper -f socialmapper -i SpiderLabs-social-mapper.html -m fast -t standard -ig")
sys.exit(1)
exit=False
try:
os.remove('backup.html')
except OSError:
pass
if not os.path.exists('temp-targets'):
os.makedirs('temp-targets')
copyfile(args.input,'SM-Results/backup.html')
print("Backup of original report created: 'SM-Results/backup.html'")
f = open(args.input)
soup = BeautifulSoup(f, 'html.parser')
f.close()
tbodylist = soup.findAll("tbody")
for personhtml in tbodylist:
person_image = encoding.smart_str(personhtml.findAll("td")[0].string, encoding='ascii', errors='ignore').replace(";","")
full_name = encoding.smart_str(personhtml.findAll("td")[1].string, encoding='ascii', errors='ignore')
first_name = full_name.split(" ")[0]