source: trollforge/dsp-trollforge/Library/Libflood.py @ 290

Revision 41, 4.7 KB checked in by sam, 8 years ago (diff)
  • DSP's trollforge snapshot.
  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1from httplib import HTTP, HTTPConnection
2from random import choice, randint
3from re import compile, search
4from string import lowercase
5from urllib import urlencode
6
7__version__ = '0.5'
8defaultheaders = {
9        'Accept': 'text/html',
10        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; )'
11}
12_msglist = []
13_proxylist = []
14
15def gemail(domain = ''):
16        """
17        Generate a random email address.
18        """
19
20        if domain != '':
21                return rndchars(2, 9) + '@' + domain
22
23        else:
24                email = rndchars(2, 9) + '@'
25                if randint(1, 3) > 1:
26                        email += 'www.'
27                email += rndchars(2, 13) + choice(['.com', '.com', '.net', '.org'])
28                return email
29
30def get(url, returnptr = 0):
31        """
32        Make a single GET request to the given URL with the given parameters.
33
34        If no second argument is given or if it evaluates to false then the
35        content of the remote page is returned as a string.
36
37        If the second argument evaluates to true then an HTTPConnection instance
38        is returned from which the server's reply can be read (including HTTP
39        headers). This HTTPConnection must be closed manually when finished with.
40        """
41        global defaultheaders
42
43        # prepare HTTP vars
44        proxy = choice(_proxylist)
45
46        con = HTTPConnection(proxy[0], proxy[1])
47
48        try:
49                con.request('GET', url, '', defaultheaders)
50        except:
51                raise "GetError", "couldn't submit GET request"
52
53        if returnptr:
54                return con
55        else:
56                str = con.getresponse().read()
57                con.close()
58                return str
59
60def getcookies(resp):
61        """
62        Given an HTTPResponse instance, returns a list of cookies.
63        Each cookie is represented as a (name, value) tuple.
64
65        If no cookies are set in the HTTPResponse, an empty list is returned.
66        """
67
68        cookies = { }
69
70        headers = str(resp.msg)
71        for header in headers.split('\n'):
72                if header.find('Set-Cookie:') == 0:
73                        cookie = header.split()[1][:-1].split('=')
74                        cookies[cookie[0]] = cookie[1]
75
76        return cookies
77
78def getmsgs(msgfile):
79        """
80        Read a list of messages from a file; each message is separated by
81        a '%' on its own line.
82
83        (i.e., it's assumed the message file is in fortune(6) format.)
84        """
85        global _msglist
86
87        i = 0
88
89        try:
90                f = open(msgfile, 'r')
91        except:
92                raise "OpenError", "couldn't open " + msgfile
93
94        _msglist.append('')
95        for s in f.readlines():
96                if s == "%\n":
97                        _msglist.append('')
98                        i += 1
99                else:
100                        _msglist[i] += s
101        f.close()
102
103def gurl(scheme = 'http'):
104        """
105        Generate a random URL with the scheme 'http://'
106        (or the given scheme, if applicable).
107        """
108        url = rndchars(5, 13) + choice(['.com', '.net', '.org'])
109        if randint(1, 3) == 1:
110                return scheme + '://' + url
111        else:
112                return scheme + '://www.' + url
113
114def post(url, param, return_conn = 0):
115        """
116        Make a single POST request to the given URL with the given
117        parameters.
118
119        If requested, return an HTTPConnection instance from which the
120        server's reply can be read (including HTTP headers). This
121        HTTPConnection must be closed manually when finished with.
122        """
123        global defaultheaders
124        global _proxylist
125
126        param = urlencode(param)
127        proxy = choice(_proxylist)
128
129        # setup the POST headers and merge in defaults
130        headers = {
131                'Content-type': 'application/x-www-form-urlencoded',
132        }
133        headers.update(defaultheaders)
134
135        con = HTTPConnection(proxy[0], proxy[1])
136
137        try:
138                con.request('POST', url, param, headers)
139        except:
140                raise "PostError", "couldn't submit POST request"
141
142        # make sure we close the connection properly if we're aren't returning an
143        # HTTP connection
144
145        if return_conn:
146                return con
147        else:
148                con.close()
149
150def proxies(proxyfile):
151        """
152        Read a list of proxies from a file for libflood to use, one per
153        line, attempting to ignore any extraneous data.
154        """
155        global _proxylist
156
157        proxmatch = compile('(([0-9a-z]{1,14}\.){3,5}[0-9a-z]{1,14}):([0-9]{1,5})')
158
159        try:
160                f = open(proxyfile, 'r')
161        except:
162                raise "OpenError", "couldn't open " + proxyfile
163
164        for s in f.readlines():
165                r = search(proxmatch, s)
166                if r == None:
167                        continue
168                else:
169                        _proxylist.append((r.group(1), int(r.group(3))))
170
171        f.close()
172
173def randline(path, lines = 0):
174        """
175        Return a random line or a series of random lines from a file.
176
177        If no second argument is specified,     returns a random line from
178        the given file as a string.
179
180        If an integer is given as a second argument is given then that
181        many lines are returned in a list.
182        """
183
184        f = open(path)
185
186        if lines:
187                chosen = []
188                s = f.readlines()
189                for i in range(lines):
190                        chosen.append(choice(s).strip())
191        else:
192                chosen = choice(f.readlines()).strip()
193
194        f.close()
195        return chosen
196
197def rndchars(minlen, maxlen = 0):
198        """
199        Generate a string composed of random lowercase characters.
200        """
201
202        if maxlen == 0:
203                len = range(minlen)
204        else:
205                len = range(randint(minlen, maxlen))
206
207        return ''.join([choice(lowercase) for i in len])
Note: See TracBrowser for help on using the repository browser.