Browsing the blog archives for Сентябрь, 2014


Используем простенький javascript код для защиты от спама

Добрый вечер!

Сегодня хочу рассказать как я эффективно борюсь с регистрационным спамом на своих сайтах/проектах. Методика очень простая, в основе используется тот факт, что спамовый движки в большинстве своем просто парсят форму и не эмулируют работу js-скриптов на сайте и браузер целиком. Поэтому, просто добавляем в форму небольшой и простенький javascript код который меняет значение одного из полей формы при отправке. Тем самым браузеры будут посылать одно значение, правильное, измененное, а спам движки которые тупо парсят форму, будут посылать другое значение. Соответственно, остается только добавить в обработчике формы проверку и тем самым отсеивать весь спам.

Вот пример кода формы:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<form name="addForm" action="/humor/add.php" method="POST">
Название:
<input type="text" style="width: 550px;" name="title" value=""/>

Текст:
<textarea tabindex="1" style="height: 300px; width: 550px;" cols="100" rows="40" name="story"></textarea>

Ваше имя/ник или ссылка на автора (не обязательно):
<input type="text" style="width: 200px;" name="nick" value=""/>

<input type='hidden' id='magic' name='magic' value='5' />
<div align="center"><input type="submit" value=" Добавить " onclick="setStep();" /></div><br />
</form>

<script language="javascript">
function setStep() {
    document.forms["addForm"].magic.value = 10;  
}
</script>

Continue Reading »

Скрипт оставления комментариев любого уровня для ЖЖ

Написал скрипт на Питоне чтобы можно было reply на комментарий любого уровня оставить.

http://pastebin.com/TsZ8FMDY

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
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import sys
import time
import re
import urllib
import urllib2
import cookielib
import httplib


COOKIE_FILE_TMPL = ".cookies/%s/cookie.txt"
COOKIE_DIR_TMPL = ".cookies/"

COMMENTS_DIR = "comments/"

DEBUG = 0
DEBUG_REPLY = 1



def main_login(cj, ljuser, ljpass):

    #
    # load main page
    #

    reqUrl = 'http://www.livejournal.com/'
    f = urllib2.urlopen(reqUrl)
    data = f.read()
    if (DEBUG):
        print "MAIN PAGE"
        #print data

    #
    # request N1 (POST QUERY)
    #

    refererUrl = reqUrl
    reqUrl = 'https://www.livejournal.com/login.bml?ret=1'
    reqData = urllib.urlencode({'mode': 'login',
                                'user': ljuser,
                                'password': ljpass}
                          )
    req = urllib2.Request(url=reqUrl, data=reqData)
    req.add_header('Referer', refererUrl)
    f = urllib2.urlopen(req)
    data = f.read()

    if (DEBUG):
        print "LIVEJOURNAL ANSWER\n"
        f = open("_login.txt", "w")
        f.write(data)
        f.close()

    #re_getbackurl = re.compile(r'livejournal.com/logout.bml\?ret=1&amp;user=')
    re_getbackurl = re.compile(r'livejournal.com/logout.bml')
    m = re.search(re_getbackurl, data)
    if (m):
        print "Login success: " + ljuser
    else:
        print "Login fail, check login and pass"
        return "fail"

    return "ok"


def main_thread_reply_one(cj, ljuser, ljpass, posturl, replytext):

    #
    # Load post
    #

    print posturl

    reqUrl = posturl
    f = urllib2.urlopen(reqUrl)
    data = f.read()
    if (DEBUG):
        print "LOAD POST"
        print data


    f = open("_post.txt", "w")
    f.write(data)
    f.close()


    #
    # Parse lj_form_auth
    #

    lj_form_auth = ""
    re_form_auth = re.compile(r' name=\\?"lj_form_auth\\?" value=\\?"([^"]+)\\?" ')
    m = re.search(re_form_auth, data, re.DOTALL|re.MULTILINE)
    if (m):
        lj_form_auth = m.group(1)
        if (DEBUG_REPLY):
            print "form auth: " + lj_form_auth
    else:
        print "livejournal lj_form_auth parsing error"
        return "fail"


    #
    # Parse chrp1
    #

    chrp1 = ""
    re_form_auth = re.compile(r' name=\\?"chrp1\\?" value=\\?"([^"]+)\\?" ')
    m = re.search(re_form_auth, data)
    if (m):
        chrp1 = m.group(1)
        if (DEBUG_REPLY):
            print "form chrp1: " + chrp1
    else:
        print "livejournal chrp1 parsing error"
        return "fail"


    #
    # Parse chal
    #

    chal = ""
    re_form_auth = re.compile(r" name='chal' id='login_chal' value='([^']+)' ")
    m = re.search(re_form_auth, data)
    if (m):
        chal = m.group(1)
        if (DEBUG_REPLY):
            print "form chal: " + chal
    else:
        #print "livejournal chal parsing error"
        #return "fail"

        # try2        
        chal = ""
        re_form_auth = re.compile(r' name="chal" value="([^"]+)" ')
        m = re.search(re_form_auth, data)
        if (m):
            chal = m.group(1)
            if (DEBUG_REPLY):
                print "form chal: " + chal
        else:
            print "livejournal chal parsing error"
            return "fail"


    #
    # Parse itemid
    #

    itemid = ""
    re_form_auth = re.compile(r' name=\\?"itemid\\?" value=\\?"([^"]+)\\?" ')
    m = re.search(re_form_auth, data)
    if (m):
        itemid = m.group(1)
        if (DEBUG_REPLY):
            print "form itemid: " + itemid
    else:
        print "livejournal itemid parsing error"
        return "fail"


    #
    # Parse journal
    #

    journal = ""
    re_form_auth = re.compile(r' name=\\?"journal\\?" value=\\?"([^"]+)\\?" ')
    m = re.search(re_form_auth, data)
    if (m):
        journal = m.group(1)
        if (DEBUG_REPLY):
            print "form journal: " + journal
    else:
        print "livejournal 'journal' parsing error"
        return "fail"


    #
    # Parse parenttalkid
    #

    parenttalkid = ""
    re_form_auth = re.compile(r' name=\\?"parenttalkid\\?" value=\\?"([^"]+)\\?" ')
    m = re.search(re_form_auth, data)
    if (m):
        parenttalkid = m.group(1)
        if (DEBUG_REPLY):
            print "form parenttalkid: " + parenttalkid
    else:
        print "livejournal 'parenttalkid' parsing error"
        return "fail"

    #
    #
    #

    print "form data parsed"

    #
    # convert ljuser to lowercase and "-" to "_"
    #

    ljuser=ljuser.lower()
    ljuser=ljuser.replace("-", "_");

    #
    # request N2 (POST) replyto
    #

    replyto = parenttalkid

    refererUrl = reqUrl
    reqUrl = 'http://www.livejournal.com/talkpost_do.bml'
    reqData = urllib.urlencode({
                                    'lj_form_auth': lj_form_auth,
                                    'chal': chal,
                                    'response': "",
                                    'replyto': replyto,
                                    'parenttalkid': parenttalkid,
                                    'itemid': itemid,
                                    'journal': journal,
                                    'stylemine': "",
                                    'editid': "0",
                                    'talkpost_do': "0",
                                    'chrp1': chrp1,
                                    'json': "1",
                                    'usertype': "cookieuser",
                                    'cookieuser': ljuser,
                                    'userpost': "",
                                    'password': "",
                                    'do_login': "",
                                    'openid:url': "",
                                    'oiddo_login': "",
                                    'subject': "",
                                    'subjecticon': "none",
                                    'prop_picture_keyword': "",
                                    'body': replytext
                                })

    req = urllib2.Request(url=reqUrl, data=reqData)
    req.add_header('Referer', refererUrl)
    f = urllib2.urlopen(req)
    data = f.read()

    print "form data send"

    f = open("_replyresp.txt", "w")
    f.write(data)
    f.close()

    if (DEBUG):
        print "REPLY POST ANSWER\n"
        print data


    print "Comment post reply:"
    print data.strip()

    #
    # checking return data
    #

    #
    # should be like
    # xdreceiver.html?type=commentator%2Fsubmit&status=redirect
    #

    re_find = re.compile(r'xdreceiver.html\?type=commentator%2Fsubmit&status=redirect')
    m = re.search(re_find, data)
    if (m):
        print "Now comment posted, success!"
    else:
        print "livejournal reply response error"
        return "fail"


    return "ok"



#
# Main process code
#
def main_process(ljuser, ljpass, community, posturl):

    #
    # make ".cookies" dir
    #

    cookies_dir = os.path.join(os.getcwd(), COOKIE_DIR_TMPL)
    if (not(os.path.exists(cookies_dir))):
        os.mkdir(cookies_dir)

    #
    # prepare request cookies
    #

    COOKIE_FILE_PATH = COOKIE_FILE_TMPL % ljuser
    cookie_file = os.path.join(os.getcwd(), COOKIE_FILE_PATH)

    cj = cookielib.CookieJar()
    cj = cookielib.MozillaCookieJar()

    if (not(os.path.exists(cookie_file))):
        if (not(os.path.exists(os.path.dirname(cookie_file)))):
            os.mkdir(os.path.dirname(cookie_file))
        cj.save(cookie_file)

    cj.load(cookie_file)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    urllib2.install_opener(opener)

    #
    # Login
    #

    ret = main_login(cj, ljuser, ljpass)
    if ret == "fail":
        print "Login failed"
        exit(1)
   

    print "Sending comments in community: " + community

    if (1):

        #poster = "test7"
        #data = "some comment7"
        #replytext = "<b>" + poster + "</b>: " + data

        replytext = "Хотя бы газовый баллончик иметь, перцовый."

        #print poster
        print replytext

        ret = main_thread_reply_one(cj, ljuser, ljpass, posturl, replytext)
        if ret == "ok":
            print "Reply successful"
        else:
            print "Reply failed"


    #
    # Saving state for analyze
    #

    print "All done!"

    return


def main():
   
    community = "http://ru-psiholog.livejournal.com/"

    posturl = "http://ru-psiholog.livejournal.com/5486401.html?replyto=290311489"

    ljuser="deniska2014"
    ljpass="XXXXXXXXX"

    main_process(ljuser, ljpass, community, posturl)

    return

if __name__ == "__main__":
    main()