├── .gitignore
├── LICENSE
├── README.md
├── adslproxy
├── __init__.py
├── api_server.py
├── db.py
├── hosts_managers.py
└── tasks.py
├── build_images.sh
├── config
├── api_config.py
├── hosts.py
├── requirements.txt
└── supervisor.conf
├── framework_v1.png
├── logs
└── .gitkeep
├── script-sh
└── squid.sh
└── test
├── __init__.py
├── demo.py
├── demo2.py
├── test_api.py
├── test_fabric.py
├── test_jwt.py
├── test_paramiko.py
├── test_proxy.py
└── test_threading.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .idea/
11 | .Python
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .coverage
43 | .coverage.*
44 | .cache
45 | nosetests.xml
46 | coverage.xml
47 | *.cover
48 | .hypothesis/
49 | .pytest_cache/
50 |
51 | # Translations
52 | *.mo
53 | *.pot
54 |
55 | # Django stuff:
56 | *.log
57 | local_settings.py
58 | db.sqlite3
59 |
60 | # Flask stuff:
61 | instance/
62 | .webassets-cache
63 |
64 | # Scrapy stuff:
65 | .scrapy
66 |
67 | # Sphinx documentation
68 | docs/_build/
69 |
70 | # PyBuilder
71 | target/
72 |
73 | # Jupyter Notebook
74 | .ipynb_checkpoints
75 |
76 | # pyenv
77 | .python-version
78 |
79 | # celery beat schedule file
80 | celerybeat-schedule
81 |
82 | # SageMath parsed files
83 | *.sage.py
84 |
85 | # Environments
86 | .env
87 | .venv
88 | env/
89 | venv/
90 | ENV/
91 | env.bak/
92 | venv.bak/
93 |
94 | # Spyder project settings
95 | .spyderproject
96 | .spyproject
97 |
98 | # Rope project settings
99 | .ropeproject
100 |
101 | # mkdocs documentation
102 | /site
103 |
104 | # mypy
105 | .mypy_cache/
106 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # awesome-proxy
2 | 一款基于ADSL拨号主机构建的高可用、高性能、高匿名代理池!
3 |
4 |
5 |
6 | 1. 修改配置(填写你购买的adsl主机ssh信息)
7 | 2. 构建Docker镜像、启动容器(也支持python环境下运行,推荐容器方式运行)
8 | 3. 投入使用
9 |
10 | **一次构建,长久使用,免维护**
11 |
12 | * 已支持功能
13 | 1. 动态配置API账户,多人使用,修改配置后1分钟左右会更新到数据库。
14 | 2. 主机配置会定期检查,配置无误则会自动修正主机并管理。动态增减主机只需要修改配置文件即可。
15 | 3. 重启程序或重启容器重新检测主机,异常主机自修复。
16 | 4. 根据配置文件设置定期更新整个代理池IP
17 | 5. JWT验权,Token 5小时有效。
18 |
19 | ---
20 | * 存在问题
21 | 1. token并没有做过期校验的逻辑,如果有需要可以开发。
22 | 2. 因个服务商环境不同,自动配置ADSL的脚本并没有开发(如果出现问题,可能需要手动处理)。
23 | 3. 日志不是很详细。
24 | 4. 可能会出现Bug,保留了大量注释,交流学习,欢迎吐槽。
25 |
26 | ---
27 | * 开发计划(可能开发的功能)
28 | 1. 客户端可以使用HTTPS连接代理服务器。
29 | 2. 隧道模式,可以控制一台代理主机的使用时间(防止高并发IP被封,充分利用IP)
30 | 3. 管理后台
31 | 4. 欢迎大家补充~
32 |
33 |
34 | ---
35 | # 服务商支持
36 | |服务商|类型|是否支持|备注|
37 | |---|---|---|---|
38 | |说明|所有动态拨号的主机或vps|支持|特征:拨号成功后可以看到一个包含了外网IP的网卡|
39 | |芝麻代理|芝麻VPS|不支持(服务商无动态拨号类的服务)|不是ADSL主机,且为机房IP,可用性低|
40 | |云立方|动态拨号VPS(非VPS主机)|支持|
41 | |91VPS|拨号VPS|支持|
42 | |其他服务商| | |未测试、欢迎补充!|
43 |
44 |
45 | ---
46 | # OS支持
47 | |操作系统|是否支持|
48 | |---|---|
49 | |Mac|是|
50 | |Linux|是(Redhat系、Debian系)|
51 | |Windows|不完全支持(只支持能执行sh脚本的环境cygwin、linux子系统等)|
52 |
53 |
54 | ---
55 | # 架构图
56 | 
57 |
58 |
59 | ---
60 | # 快速开始
61 | ## 部署
62 | ```
63 | # 说明
64 | 可以在本地环境跑容器或者IDE中执行;也可以在云服务器上运行。
65 | 在IDE中运行需要执行api_server.py和tasks.py两个文件
66 |
67 | # 拉取代码
68 | git clone https://github.com/osof/awesome-proxy.git
69 | cd awesome-proxy && chmod +x build_images.sh
70 |
71 | # 修改配置
72 | cd config # 并修改配置
73 | # api_config.py : 接口、数据库等配置,只需修改代理账户、IP切换时间
74 | # hosts.py : 配置您购买的adsl拨号主机
75 | # supervisor.conf 该文件一般不用修改,根据api_config.py中的配置会自动覆盖相关配置。
76 |
77 | # 检查本地环境是否已安装docker,如果没有安装则会自动安装。
78 | ./build_images.sh check
79 |
80 |
81 | # 构建镜像
82 | ./build_images.sh make_images [you_images_tag_name]
83 |
84 |
85 | # 启动容器
86 | # 端口映射有三个:redis端口(可选)、API服务(必须)、Supervisor管理端口(可选)
87 | docker run -idt --name [my_adsl] --restart=always -p xxx:xxx [you_images_tag_name]
88 |
89 | ```
90 |
91 | ---
92 | ## Demo
93 |
94 | ```
95 | # 简版Demo
96 |
97 | import requests
98 |
99 | # 获取Token(返回的token 默认5小时有效)
100 | # 代理池地址(Docker部署的服务器)
101 | api_url = 'http://192.168.2.21:8080'
102 |
103 |
104 | def get_token():
105 | # 获取Token(返回的token 默认5小时有效)
106 | url = f'{api_url}/api/v1/login'
107 | # 修改为自己的账户信息
108 | user_info = {"username": "admin", "password": "12345678"}
109 | token = requests.post(url=url, json=user_info).json().get('access_token')
110 | if token:
111 | return {"token": token}
112 | return None
113 |
114 |
115 | if __name__ == '__main__':
116 | token = get_token() # token是长时间有效的,获取一次就好。
117 | if token:
118 | # 获取一个随机代理
119 | random_proxy = requests.post(url=f'{api_url}/api/v1/random', json=get_token()).json()
120 | if 'http' in random_proxy.keys():
121 | # 代理正常返回
122 | resp = requests.get(url='https://www.baidu.com', proxies=random_proxy, timeout=10)
123 | print(resp.text)
124 |
125 |
126 |
127 |
128 | #######################################
129 | # 复杂一点的Demo
130 |
131 | import requests
132 | from json import JSONDecodeError
133 |
134 |
135 | def get_data_from_post(url, data):
136 | """
137 |
138 | :param url: api
139 | :param data: dict
140 | :return: dict
141 | """
142 | response = requests.post(url, json=data, timeout=10)
143 | if response.status_code == 200:
144 | response_text = resp.json()
145 | return response_text
146 | else:
147 | try:
148 | print(response.json())
149 | return None
150 | except JSONDecodeError:
151 | raise TypeError(f'json 解析错误,可能 {url} 不是 api 列表中的 url')
152 |
153 |
154 | test_url = 'http://www.baidu.com'
155 | host_url = 'http://192.168.2.21:8080'
156 |
157 | # 获取 token
158 | user_info = {
159 | "username": "admin",
160 | "password": "12345678",
161 | }
162 | token_url = f'{host_url}/api/v1/login'
163 | token_dict = get_data_from_post(token_url, user_info)
164 | token = token_dict.get('access_token')
165 |
166 | # 向接口提交 token,验证权限,获取的数据类似{'http': proxy_url, 'https': proxy_url}
167 | data = {'token': token}
168 | random_proxy_url = f'{host_url}/api/v1/random'
169 | random_proxy = get_data_from_post(random_proxy_url, data)
170 |
171 | resp = requests.get(url=test_url, proxies=random_proxy, timeout=10)
172 | if resp.status_code == 200:
173 | print('代理验证成功')
174 | ```
175 |
176 | ---
177 | # API说明
178 |
179 | **说明**
180 | * 为方便用户使用,返回的代理是字典结构,用户只需loads一下即可直接使用,省去拼接字符串环节。
181 | * 操作成功返回对应信息,操作失败返回错误信息(部分接口含状态码)
182 | * 本程序只是为了方便用户,减少代码量!不是特别重要的部分会尽量简化状态信息。
183 |
184 |
185 | ## 验权
186 | ```
187 | POST /api/v1/token
188 | json: { "username": "admin", "password": "123456" }
189 |
190 |
191 | 验证成功返回token(5小时有效)
192 | {"status": "200", "token": "token_str"}
193 |
194 | 验证失败返回错误信息
195 | {"status": "403", 'error': 'Unauthorized access'}
196 |
197 | ```
198 |
199 | ---
200 | ## 查看API列表
201 | ```
202 | POST /api/v1/index
203 | 提交json: { "token": "token_str"}
204 |
205 | ---------------------------------
206 | 操作成功返回: API列表
207 |
208 | 操作失败返回:
209 | Token过期:{"status": "403", 'error': 'Unauthorized access'}
210 | ```
211 |
212 | ---
213 | ## 随机获取一个代理的值
214 | ```
215 | POST /api/v1/random
216 | 提交json: { "token": "token_str"}
217 |
218 | ---------------------------------
219 | 操作成功返回:{ http : "http://123.456.678.789:3100" }
220 |
221 | 操作失败返回:
222 | Token过期:{"status": "403", 'error': 'Unauthorized access'}
223 | 没有代理可用:{"status": "500", 'error': 'No proxy available'}
224 | ```
225 |
226 | ---
227 | ## 获取一个随机代理的详细信息
228 | ```
229 | POST /api/v1/proxies
230 | 提交json: { "token": "token_str", "proxy_name": "myadsl1" }
231 |
232 | ---------------------------------
233 | 操作成功返回:{ "status": "200", "name": "myadsl1", "proxy": "{http : 'http://123.456.678.789:3100'}" }
234 |
235 | 操作失败返回:
236 | Token过期:{"status": "403", 'error': 'Unauthorized access'}
237 | 没有代理可用:{"status": "500", 'error': '找不到代理!'}
238 | ```
239 |
240 | ---
241 | ## 获取所有代理
242 | ```
243 | POST /api/v1/all
244 | 提交json: { "token": "token_str"}
245 |
246 | ---------------------------------
247 | 操作成功返回:{ "data": [{http : 'http://123.456.678.789:3100'}, {http : 'http://321.543.765.987:3100'}] }
248 |
249 | 操作失败返回:
250 | Token过期:{"status": "403", 'error': 'Unauthorized access'}
251 | 没有代理可用:{"status": "500", 'error': 'No proxy available'}
252 |
253 | ```
254 |
255 |
256 | ---
257 | ## 代理数量统计
258 | ```
259 | POST /api/v1/counts
260 | 提交json: { "token": "token_str"}
261 |
262 | ---------------------------------
263 | 操作成功返回:{ "status": "200", "counts": "代理数量(没有代理则为0)" }
264 |
265 | 操作失败返回:
266 | Token过期:{"status": "403", 'error': 'Unauthorized access'}
267 | ```
268 |
269 |
270 | ---
271 | ## 获取机器名称
272 | ```
273 | POST /api/v1/names
274 | 提交json: { "token": "token_str"}
275 |
276 | ---------------------------------
277 | 操作成功返回:{ "myadsl1", "myadsl2", "myadsl3"}
278 |
279 | 操作失败返回:
280 | Token过期:{"status": "403", 'error': 'Unauthorized access'}
281 | 没有代理可用:{"status": "500", 'error': 'No proxy available'}
282 | ```
283 |
284 |
285 | ---
286 | ## 删除一个代理
287 | ```
288 | POST /api/v1/delete
289 | 提交json: { "token": "token_str", "proxy_name": "myadsl1" }
290 |
291 |
292 | ---------------------------------
293 | 操作成功返回:{"status": "200", 'delete': 'Success'}
294 |
295 | 操作失败返回:
296 | Token过期:{"status": "403", 'error': 'Unauthorized access'}
297 | 没有代理可用:{"status": "500", 'delete': 'Fail'}
298 |
299 | ```
300 |
301 |
302 |
303 |
304 | ---
305 | # 其他
306 | 还没想好!
--------------------------------------------------------------------------------
/adslproxy/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | #
5 |
--------------------------------------------------------------------------------
/adslproxy/api_server.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | # API接口服务(每次启动程序都执行本脚本,一直执行)
5 |
6 |
7 | import os
8 | import sys
9 |
10 | # 无效果
11 | # import pathlib
12 | # ROOT_DIR = pathlib.Path.cwd().parent
13 | # sys.path.append(ROOT_DIR)
14 | # sys.path.append(ROOT_DIR / 'adslproxy')
15 | # sys.path.append(ROOT_DIR / 'config')
16 |
17 | # 获取当前文件的上级目录(项目根目录)
18 | WORK_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
19 | sys.path.append(WORK_DIR)
20 | sys.path.append(os.path.join(WORK_DIR, 'adslproxy'))
21 | sys.path.append(os.path.join(WORK_DIR, 'config'))
22 |
23 | import time
24 | import wrapt
25 | from adslproxy.db import RedisClient
26 | from config.api_config import *
27 | from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
28 | from itsdangerous import SignatureExpired, BadSignature, BadData
29 | from flask import Flask, jsonify, request, abort, url_for
30 |
31 | app = Flask(__name__)
32 | redis_cli = RedisClient(list_key='adslproxy')
33 |
34 |
35 | #############################################################
36 |
37 |
38 | def genTokenSeq(user):
39 | """
40 | # 生成token
41 | :param user: 输入用户名
42 | :return: 两个token
43 | """
44 | access_token_gen = Serializer(secret_key=SECRET_KEY, salt=SALT, expires_in=ACCESS_TOKEN_EXPIRES)
45 | refresh_token_gen = Serializer(secret_key=SECRET_KEY, salt=SALT, expires_in=REFRESH_TOKEN_EXPIRES)
46 | timestamp = time.time()
47 | access_token = access_token_gen.dumps({
48 | "userid": user,
49 | "iat": timestamp
50 | })
51 | refresh_token = refresh_token_gen.dumps({
52 | "userid": user,
53 | "iat": timestamp
54 | })
55 |
56 | data = {
57 | "access_token": str(access_token, 'utf-8'),
58 | "access_token_expire_in": ACCESS_TOKEN_EXPIRES,
59 | "refresh_token": str(refresh_token, 'utf-8'),
60 | "refresh_token_expire_in": REFRESH_TOKEN_EXPIRES,
61 | }
62 | return data
63 |
64 |
65 | def validateToken(token):
66 | """
67 | # 解析token
68 | :param token: 输入toke
69 | :return: 解析结果
70 | """
71 | s = Serializer(secret_key=SECRET_KEY, salt=SALT)
72 | try:
73 | data = s.loads(token)
74 | except SignatureExpired:
75 | return {'code': 401, 'message': 'toekn expired'} # token过期
76 | except BadSignature as e:
77 | encoded_payload = e.payload
78 | if encoded_payload is not None:
79 | try:
80 | s.load_payload(encoded_payload)
81 | except BadData:
82 | return {'code': 401, 'message': 'token tampered'} # token篡改
83 | return {'code': 401, 'message': 'badSignature of token'} # 签名有误
84 | except Exception:
85 | return {'code': 401, 'message': 'wrong token with unknown reason'} # 令牌错误
86 | if 'userid' not in data:
87 | return {'code': 401, 'message': 'illegal payload inside'} # 非法载荷
88 | return {'code': 200, 'userid': data['userid'], 'message': f"user({data['userid']}) logged in by token."}
89 |
90 |
91 | def helper_proxy(proxy):
92 | proxyMeta = f"http://{PROXY_USER}:{PROXY_PASSWORD}@{proxy}"
93 | proxy = {
94 | "http": proxyMeta,
95 | "https": proxyMeta,
96 | }
97 | return proxy
98 |
99 |
100 | # def check_login(flag=""):
101 | # """
102 | # 校验token的装饰器
103 | # """
104 | # def check(func):
105 | # def _check_login(*args, **kwargs):
106 | # json_data = request.get_json()
107 | # token = json_data.get('token')
108 | # data = validateToken(token)
109 | # if data['code'] == 200:
110 | # return func()
111 | # else:
112 | # return jsonify({"status": "403", 'error': 'Unauthorized access'})
113 | # return _check_login
114 | # return check
115 |
116 |
117 | def check_login2(flag=""):
118 | """
119 | 校验token的装饰器2
120 | """
121 |
122 | @wrapt.decorator
123 | def check(wrapped, instance, args, kwargs):
124 | # 参数含义:
125 | #
126 | # - wrapped:被装饰的函数或类方法
127 | # - instance:
128 | # - 如果被装饰者为普通类方法,该值为类实例
129 | # - 如果被装饰者为 classmethod 类方法,该值为类
130 | # - 如果被装饰者为类/函数/静态方法,该值为 None
131 | # - args:调用时的位置参数(注意没有 * 符号)
132 | # - kwargs:调用时的关键字参数(注意没有 ** 符号)
133 | json_data = request.get_json()
134 | token = json_data.get('token')
135 | data = validateToken(token)
136 | if data['code'] == 200:
137 | return wrapped()
138 | else:
139 | return jsonify({"status": "403", 'error': 'Unauthorized access'})
140 |
141 | return check
142 |
143 |
144 | @app.route('/api/v1/login', methods=['POST'])
145 | def login():
146 | """
147 | 客户端发送json过来
148 | {
149 | "username":"admin",
150 | "password":"12345678"
151 | }
152 | """
153 | if request.headers['Content-Type'] != 'application/json':
154 | return jsonify({"status": "400", 'error': '请使用 Json 格式传递用户名和密码'}), 500
155 | json_data = request.get_json()
156 | username = json_data.get('username')
157 | password = json_data.get('password')
158 | if username is None or password is None:
159 | abort(400)
160 | # 这里校验账户是否合法,我这里用来redis简单对比;关系型数据库需要自行修改。
161 | # 这里使用了redis做AB数据集切换(账户密码是定时从配置文件读取并更新的),redis方法是自己封装的。
162 | list_key = RedisClient(list_key='ab_set').get('a_or_b')
163 | if RedisClient(list_key=list_key).get(username) == password:
164 | token = genTokenSeq(username)
165 | return jsonify(token)
166 | else:
167 | return jsonify({"status": "500", 'error': '请传递配置文件中正确的用户名和密码'}), 500
168 | # abort(400)
169 |
170 |
171 | # 说明:url后面没有加“/”,用了装饰器之后函数名会被替换,用endpoint来区分。
172 | @app.route('/', methods=['GET'], endpoint='index')
173 | def index():
174 | # 查看API列表
175 | api_url = {}
176 | for api in app.url_map._rules_by_endpoint.keys():
177 | if api != 'static':
178 | api_url[api] = url_for(api, _external=True)
179 | return jsonify(api_url)
180 |
181 |
182 | @app.route('/api/v1/random', methods=['POST'], endpoint='random')
183 | @check_login2()
184 | def random():
185 | # 随机获取一个代理的值
186 | proxy = redis_cli.random()
187 | if proxy:
188 | proxy = helper_proxy(proxy)
189 | return jsonify(proxy), 200
190 | else:
191 | return jsonify({"status": "500", 'error': 'No proxy available'}), 500
192 |
193 |
194 | @app.route('/api/v1/proxies', methods=['POST'], endpoint='proxies')
195 | @check_login2()
196 | def get_proxies():
197 | # 获取一个随机代理的详细信息
198 | proxy_name = ''
199 | proxies = {}
200 | json_data = request.get_json()
201 | if json_data:
202 | proxy_name = json_data.get('proxy_name')
203 | if proxy_name:
204 | proxy = redis_cli.get(proxy_name)
205 | if proxy:
206 | proxies['status'] = "200"
207 | proxies['name'] = proxy_name
208 | proxies['proxy'] = helper_proxy(proxy)
209 | return jsonify(proxies), 200
210 | else:
211 | return jsonify({"status": "500", 'error': '找不到代理!'}), 500
212 |
213 |
214 | @app.route('/api/v1/all', methods=['POST'], endpoint='all')
215 | @check_login2()
216 | def get_all():
217 | # 获取所有代理
218 | result = redis_cli.all()
219 | if result:
220 | proxy_list = [{'http': helper_proxy(values)} for values in result.values()]
221 | return jsonify({"data": proxy_list}), 200
222 | else:
223 | return jsonify({"status": "500", 'error': 'No proxy available'}), 500
224 |
225 |
226 | @app.route('/api/v1/counts', methods=['POST'], endpoint='counts')
227 | @check_login2()
228 | def get_counts():
229 | count = redis_cli.count()
230 | return jsonify({"status": "200", "counts": count}), 200
231 |
232 |
233 | @app.route('/api/v1/names', methods=['POST'], endpoint='names')
234 | @check_login2()
235 | def get_names():
236 | names = redis_cli.names()
237 | if names:
238 | return jsonify({"data": names}), 200
239 | else:
240 | return jsonify({"status": "500", 'error': 'No proxy available'}), 500
241 |
242 |
243 | @app.route('/api/v1/delete', methods=['POST'], endpoint='delete')
244 | @check_login2()
245 | def delete():
246 | proxy_name = ''
247 | json_data = request.get_json()
248 | if json_data:
249 | proxy_name = json_data.get('proxy_name')
250 | if not proxy_name:
251 | return jsonify({"status": "500", 'delete': '请输入代理机器名称'}), 400
252 | try:
253 | result = redis_cli.remove(proxy_name)
254 | except Exception:
255 | return jsonify({"status": "500", 'delete': '删除失败,该代理不存在!'}), 400
256 | if result:
257 | return jsonify({"status": "200", 'delete': 'Success'}), 200
258 | else:
259 | return jsonify({"status": "500", 'delete': 'Fail'}), 400
260 |
261 |
262 | if __name__ == '__main__':
263 | # 启动接口
264 | app.run(host=API_HOST, port=API_PORT, debug=False)
265 | # gunicorn方式启动
266 | # os.system(f'gunicorn -w 4 -b {API_HOST}:{API_PORT} -k gevent api_server:app')
267 |
--------------------------------------------------------------------------------
/adslproxy/db.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | # 数据库函数
5 |
6 | import redis
7 | import random
8 | from config.api_config import *
9 |
10 |
11 | class RedisClient(object):
12 | def __init__(self, host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD, list_key='adslproxy'):
13 | """
14 | 初始化Redis连接proxy_key=PROXY_KEY
15 | :param host: Redis 地址
16 | :param port: Redis 端口
17 | :param password: Redis 密码
18 | :param proxy_key: Redis 哈希表名
19 | """
20 | self.db = redis.StrictRedis(host=host, port=port, password=password, decode_responses=True)
21 | self.list_key = list_key
22 |
23 | def set(self, name, proxy):
24 | """
25 | 设置代理
26 | :param name: 主机名称
27 | :param proxy: 代理
28 | :return: 设置结果
29 | """
30 | return self.db.hset(self.list_key, name, proxy)
31 |
32 | def get(self, name):
33 | """
34 | 获取代理
35 | :param name: 主机名称
36 | :return: 代理
37 | """
38 | return self.db.hget(self.list_key, name)
39 |
40 | def count(self):
41 | """
42 | 获取代理总数
43 | :return: 代理总数
44 | """
45 | return self.db.hlen(self.list_key)
46 |
47 | def remove(self, name):
48 | """
49 | 删除代理
50 | :param name: 主机名称
51 | :return: 删除结果
52 | """
53 | return self.db.hdel(self.list_key, name)
54 |
55 | def delete(self):
56 | """
57 | 删除代理池
58 | :return: None
59 | """
60 | return self.db.delete(self.list_key)
61 |
62 | def names(self):
63 | """
64 | 获取主机名称列表
65 | :return: 获取主机名称列表
66 | """
67 | return self.db.hkeys(self.list_key)
68 |
69 | def proxies(self):
70 | """
71 | 获取代理列表
72 | :return: 代理列表
73 | """
74 | return self.db.hvals(self.list_key)
75 |
76 | def random(self):
77 | """
78 | 随机获取代理
79 | :return:
80 | """
81 | proxies = self.proxies()
82 | if proxies:
83 | return random.choice(proxies)
84 |
85 | def all(self):
86 | """
87 | 获取字典
88 | :return:
89 | """
90 | return self.db.hgetall(self.list_key)
91 |
92 | def random_info(self):
93 | """
94 | 随机获取代理的详细信息
95 | :return:
96 | """
97 | get_name = self.names()
98 | if get_name:
99 | name = random.choice(get_name)
100 | proxy = self.get(name)
101 | return [name, proxy]
102 | # 测试返回
103 | # return ['', '']
104 |
--------------------------------------------------------------------------------
/adslproxy/hosts_managers.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | # 执行初始化、主机管理(每次启动程序都执行本脚本,一次性执行)
5 |
6 |
7 | import os
8 | import re
9 | import time
10 | import json
11 | import threading
12 | import paramiko
13 | from retrying import retry
14 | from config.hosts import *
15 | from config.api_config import *
16 | from adslproxy.db import RedisClient
17 | from adslproxy.api_server import WORK_DIR
18 |
19 | SCRIPT_DIR = os.path.join(WORK_DIR, 'script-sh')
20 | SQUID_SH = os.path.join(SCRIPT_DIR, 'squid.sh')
21 |
22 |
23 | @retry(stop_max_attempt_number=5)
24 | def get_proxy_ip(ssh_cli):
25 | time.sleep(5) # 拨号后要好几秒后才能分配到IP
26 | # 获取代理IP(能请求成功说明代理IP有效),注意stdout只有第一次输出是有效的,再次获取是空的。
27 | stdin, stdout, stderr = ssh_cli.exec_command('curl http://members.3322.org/dyndns/getip')
28 | proxy_ip = stdout.readlines() # 要获取stdout的内容不能先用if判断(第二次读取内容为空),而是先赋值
29 | if proxy_ip:
30 | proxy_ip = proxy_ip[0].strip()
31 | return proxy_ip
32 | else:
33 | raise Exception('获取不到IP,尝试重新获取')
34 |
35 |
36 | @retry(stop_max_attempt_number=5)
37 | def pppoe(ssh_cli, cmd):
38 | # 拨号程序
39 | print('重新拨号中...')
40 | stdin, stdout, stderr = ssh_cli.exec_command(f'{cmd[0]} && sleep 3 && {cmd[1]}')
41 | if stderr.readlines():
42 | raise Exception('拨号出现问题!')
43 | else:
44 | return get_proxy_ip(ssh_cli)
45 |
46 |
47 | def set_sh_config():
48 | # 修改squid.sh中的代理账户配置,便于执行
49 | with open(SQUID_SH, 'r', encoding='utf-8') as f:
50 | m = re.findall('(squid_proxy_.*?)=(.*?)\s', f.read())
51 | for key, values in dict(m).items():
52 | # print(key, values)
53 | if key[12:] == "user":
54 | os.system(f'sed -i "s/{key}={values}/{key}={PROXY_USER}/g" {SQUID_SH}')
55 | elif key[12:] == "passwd":
56 | os.system(f'sed -i "s/{key}={values}/{key}={PROXY_PASSWORD}/g" {SQUID_SH}')
57 | elif key[12:] == "port":
58 | os.system(f'sed -i "s/{key}={values}/{key}={PROXY_PORT}/g" {SQUID_SH}')
59 | return True
60 |
61 |
62 | def clean_sys(ssh_cli):
63 | # 清理系统为重装做准备
64 | # TODO:重装的包括adsl软件,未完成!
65 | try:
66 | _stdin, _stdout, _stderr = ssh_cli.exec_command('/root/squid.sh uninstall')
67 | if _stderr.readlines():
68 | raise Exception('/root/squid.sh脚本不存在!')
69 | except Exception:
70 | # 脚本不存在会报异常,上传后再执行
71 | with ssh_cli.open_sftp() as sftp:
72 | set_sh_config() # 上传文件前要更新脚本的配置信息
73 | sftp.put(SQUID_SH, '/root/squid.sh')
74 | ssh_cli.exec_command('chmod +x /root/squid.sh && /root/squid.sh uninstall')
75 |
76 |
77 | def check_host(ssh_cli):
78 | # exec_command执行命令,正常执行stdout有数据返回;异常时是空列表。stderr可以输出错误信息;同理,正常执行错误信息为空列表。
79 | # 检查主机是否有安装squid,并安装好
80 | stdin, stdout, stderr = ssh_cli.exec_command('squid -v|grep Version')
81 | if stdout.readlines():
82 | try:
83 | print("重启squid !")
84 | # squid是正常的,重启防假死、程序已崩溃
85 | _stdin, _stdout, _stderr = ssh_cli.exec_command('/root/squid.sh restart')
86 | if _stderr.readlines():
87 | raise Exception('/root/squid.sh脚本不存在!')
88 | except Exception:
89 | # 脚本不存在
90 | with ssh_cli.open_sftp() as sftp:
91 | set_sh_config() # 上传文件前要更新脚本的配置信息
92 | sftp.put(SQUID_SH, '/root/squid.sh')
93 | ssh_cli.exec_command('chmod +x /root/squid.sh && /root/squid.sh restart')
94 | else:
95 | # 系统中没有安装squid,尝试安装。
96 | print('安装squid!')
97 | try:
98 | _stdin, _stdout, _stderr = ssh_cli.exec_command('/root/squid.sh install')
99 | if _stderr.readlines():
100 | raise Exception('/root/squid.sh脚本不存在!')
101 | except Exception:
102 | # 脚本不存在,上传后再执行
103 | with ssh_cli.open_sftp() as sftp:
104 | set_sh_config() # 上传文件前要更新脚本的配置信息
105 | sftp.put(SQUID_SH, '/root/squid.sh')
106 | c_stdin, c_stdout, c_stderr = ssh_cli.exec_command('chmod +x /root/squid.sh && /root/squid.sh install')
107 | # print(c_stdout.readlines())
108 |
109 |
110 | def run_task(key, values):
111 | # print(threading.currentThread().getName())
112 | print('初始化主机:', key)
113 | with paramiko.SSHClient() as ssh_cli:
114 | ssh_cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
115 | try:
116 | ssh_cli.connect(hostname=values['host'], username=values['username'],
117 | password=values['password'],
118 | port=values['port'])
119 | except paramiko.ssh_exception.NoValidConnectionsError as e:
120 | logger.error(f'主机:{key},配置有问题,请手动修复并重启程序! {e}')
121 | values['problem'] = 'init_error'
122 | RedisClient(list_key='badhosts').set(key, json.dumps(values))
123 | return False
124 | # 检查squid
125 | check_host(ssh_cli)
126 | # 开始拨号
127 | proxy_ip = pppoe(ssh_cli, values['cmd'])
128 | # 存储到Redis
129 | RedisClient(list_key='adslproxy').set(key, f'{proxy_ip}:{PROXY_PORT}')
130 | RedisClient(list_key='goodhosts').set(key, json.dumps(values))
131 |
132 |
133 |
134 | def hosts_init():
135 | # 一启动先拨号一次号,保存所有主机的代理IP
136 | # 主机管理(启动程序时会检查并配置所有主机)
137 | thread_list = []
138 | for _group in HOSTS_GROUP:
139 | host_list = HOSTS_GROUP.get(_group)
140 | for key, values in host_list.items():
141 | # run_task(key, values)
142 | t = threading.Thread(target=run_task, args=(key, values))
143 | thread_list.append(t)
144 | # 开始执行任务
145 | for t in thread_list:
146 | t.start()
147 |
148 | for t in thread_list:
149 | # 阻塞线程,等待子线程执行完毕。
150 | t.join()
151 |
152 |
153 | if __name__ == '__main__':
154 | # 启动时只执行一次
155 | hosts_init()
156 |
--------------------------------------------------------------------------------
/adslproxy/tasks.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | # 定时任务、拨号(每次启动程序都执行本脚本,一直执行)
5 |
6 |
7 | import os
8 | import sys
9 |
10 | ROOT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
11 | sys.path.append(ROOT_DIR)
12 |
13 | import json
14 | import paramiko
15 | import threading
16 | from config.hosts import *
17 | from config.api_config import *
18 | from adslproxy.hosts_managers import pppoe, hosts_init, clean_sys, check_host
19 | from adslproxy.db import RedisClient
20 |
21 |
22 | def solve_badhosts():
23 | # 处理问题主机,根据问题类型,重装软件或拨号。
24 |
25 | badhosts_info_dict = RedisClient(list_key='badhosts').all()
26 | if badhosts_info_dict:
27 | for key, v in badhosts_info_dict.items():
28 | values = v
29 | # 从配置文件读取(链接信息可能已被修正了)
30 | for _group in HOSTS_GROUP:
31 | if key in HOSTS_GROUP.get(_group).keys():
32 | values = HOSTS_GROUP.get(_group)[key]
33 |
34 | with paramiko.SSHClient() as ssh_cli:
35 | ssh_cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
36 | try:
37 | ssh_cli.connect(hostname=values['host'], username=values['username'],
38 | password=values['password'],
39 | port=values['port'])
40 | except paramiko.ssh_exception.NoValidConnectionsError as e:
41 | # init_error错误是ssh信息配置错误,只要修正了配置文件就能继续下去。
42 | # 如果还是链接不上,还是init_error则更新信息。
43 | logger.error(f'主机:{key},配置有问题,请手动修复并重启程序! {e}')
44 | values['problem'] = 'init_error'
45 | RedisClient(list_key='badhosts').set(key, json.dumps(values))
46 |
47 | # 如果是adsl_error错误,则需要重新安装软件
48 | if values['problem'] == 'adsl_error':
49 | clean_sys(ssh_cli)
50 | check_host(ssh_cli)
51 |
52 | # 开始拨号
53 | try:
54 | proxy_ip = pppoe(ssh_cli, values['cmd'])
55 | except Exception:
56 | # 依然有问题,不做操作
57 | pass
58 | # 如果没问题,加入代理,从问题主机列表移除并添加到正常主机列表
59 | RedisClient(list_key='adslproxy').set(key, f'{proxy_ip}:{PROXY_PORT}')
60 | RedisClient(list_key='badhosts').remove(key)
61 | RedisClient(list_key='goodhosts').set(key, json.dumps(values))
62 | # 间隔300秒 时间再次执行
63 | threading.Timer(300, solve_badhosts).start()
64 |
65 |
66 | def adsl_switch_ip():
67 | # 定时拨号的主机是从正常的主机中获取的。
68 | hosts_info_dict = RedisClient(list_key='goodhosts').all()
69 | # 开始拨号(从拨号到IP可用有一定时间间隔,不要用异步,防止短时间内无IP可用)
70 | for key, values in hosts_info_dict.items():
71 | with paramiko.SSHClient() as ssh_cli:
72 | ssh_cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
73 | # 这里不用捕捉异常,在hosts_init()时即可判断时否异常
74 | ssh_cli.connect(hostname=values['host'], username=values['username'],
75 | password=values['password'],
76 | port=values['port'])
77 | try:
78 | proxy_ip = pppoe(ssh_cli, values['cmd'])
79 | except Exception:
80 | # 重新拨号得不到新IP,则移除旧IP,且从正常主机列表移除并加入问题主机列表
81 | logger.error(f'{key}:拨号失败了!')
82 | RedisClient(list_key='adslproxy').remove(key)
83 | RedisClient(list_key='goodhosts').remove(key)
84 | values['problem'] = 'adsl_error'
85 | RedisClient(list_key='badhosts').set(key, json.dumps(values))
86 | # 存储到Redis
87 | RedisClient(list_key='adslproxy').set(key, f'{proxy_ip}:{PROXY_PORT}')
88 | # 间隔ADSL_SWITCH_TIME 时间再次执行
89 | threading.Timer(ADSL_SWITCH_TIME, adsl_switch_ip).start()
90 |
91 |
92 | def update_user_info():
93 | # 更新API用户信息(AB集切换)
94 | a_or_b = RedisClient(list_key='ab_set').get('a_or_b')
95 | if a_or_b == "userinfo_a":
96 | for group in USER:
97 | for user_info in USER[group].values():
98 | RedisClient(list_key='userinfo_b').set(user_info['username'], user_info['password'])
99 | RedisClient(list_key='ab_set').set('a_or_b', 'userinfo_b')
100 | RedisClient(list_key='userinfo_a').delete()
101 | elif a_or_b == "userinfo_b":
102 | for group in USER:
103 | for user_info in USER[group].values():
104 | RedisClient(list_key='userinfo_a').set(user_info['username'], user_info['password'])
105 | RedisClient(list_key='ab_set').set('a_or_b', 'userinfo_a')
106 | RedisClient(list_key='userinfo_b').delete()
107 | # 间隔60秒 时间再次执行
108 | threading.Timer(60, update_user_info).start()
109 |
110 |
111 | def tasks_main():
112 | # hosts_manages启动时会初始化主机,并把代理写入Redis,此处接着执行定时任务即可。
113 | t2 = threading.Timer(ADSL_SWITCH_TIME, adsl_switch_ip)
114 | t2.start()
115 | # 立刻处理问题主机
116 | # print("处理问题主机!")
117 | t3 = threading.Timer(0, solve_badhosts)
118 | t3.start()
119 |
120 |
121 | if __name__ == "__main__":
122 | # 清空Redis中的数据
123 | RedisClient(list_key='adslproxy').delete()
124 | RedisClient(list_key='goodhosts').delete()
125 | RedisClient(list_key='badhosts').delete()
126 | RedisClient(list_key='userinfo_a').delete()
127 | RedisClient(list_key='userinfo_b').delete()
128 | # 定时更新用户账户
129 | RedisClient(list_key='ab_set').set('a_or_b', 'userinfo_b') # 启动初始化要设置一下,防止key不存在报错。
130 | t1 = threading.Timer(0, update_user_info)
131 | t1.start()
132 | # hosts_init启动时会初始化主机,并把代理写入Redis,此处接着执行定时任务即可。
133 | hosts_init() # join线程阻塞(配置环境需要时间,只花最慢一台机器的时间)
134 | # 开始定时拨号任务,子线程开始等待,不影响下面执行
135 | tasks_main()
136 |
--------------------------------------------------------------------------------
/build_images.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # 构建Docker镜像
4 |
5 | # 安装Docker
6 | check_docker(){
7 | if [ `docker -v|cut -d" " -f1` == 'Docker' ];then
8 | echo "本地已安装了Docker!"
9 | else
10 | echo "现在为您安装Docker!"
11 | curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh
12 | fi
13 | }
14 |
15 |
16 | create_dockerfile(){
17 | api_port=`egrep -r "API_PORT" config/api_config.py |awk {'print $3'}`
18 |
19 | # Redis Config
20 | redis_port=`egrep -r "REDIS_PORT" config/api_config.py |awk {'print $3'}`
21 |
22 | redis_passwd=`egrep -r "REDIS_PASSWORD" config/api_config.py |awk {'print $3'}`
23 |
24 | if [ $redis_passwd != "''" ] ;then
25 | set_redis_passwd="sed -i 's/# requirepass foobared/requirepass ${redis_passwd}/g' /etc/redis/redis.conf"
26 | else
27 | set_redis_passwd="echo "
28 | fi
29 | # Supervisor config
30 | # 下面这句sed是匹配地址并替换端口,在Mac上会报错。
31 | sed -i "s/\(-b 0.0.0.0:\)[0-9]*/\1${api_port}/" config/supervisor.conf
32 |
33 | supervisor_username=`egrep -r "supervisor_username" config/api_config.py |awk -F "'" {'print $2'}`
34 | supervisor_password=`egrep -r "supervisor_password" config/api_config.py |awk -F "'" {'print $2'}`
35 | supervisor_port=`egrep -r "supervisor_port" config/api_config.py |awk {'print $3'}`
36 | sed -i "s/`egrep -r 'username' config/supervisor.conf |head -n1`/username=${supervisor_username}/g" config/supervisor.conf
37 | sed -i "s/`egrep -r 'password' config/supervisor.conf |head -n1`/password=${supervisor_password}/g" config/supervisor.conf
38 |
39 | sed -i "s/`grep 'port=' config/supervisor.conf`/port=:${supervisor_port}/g" config/supervisor.conf
40 | sed -i "s/\(serverurl=http:\/\/0.0.0.0:\)[0-9]*/\1${supervisor_port}/" config/supervisor.conf
41 |
42 | # 生成Dockerfile(直接编写Dockerfile在Mac上无法使用sed操作文件)
43 | cat > Dockerfile </dev/null)" == "Debian" ]; then
19 | OS=Debian
20 | PM=apt
21 | elif [ -n "$(grep 'Deepin' /etc/issue)" -o "$(lsb_release -is 2>/dev/null)" == "Deepin" ]; then
22 | OS=Debian
23 | PM=apt
24 | elif [ -n "$(grep -w 'Kali' /etc/issue)" -o "$(lsb_release -is 2>/dev/null)" == "Kali" ]; then
25 | OS=Debian
26 | PM=apt
27 | elif [ -n "$(grep 'Ubuntu' /etc/issue)" -o "$(lsb_release -is 2>/dev/null)" == "Ubuntu" -o -n "$(grep 'Linux Mint' /etc/issue)" ]; then
28 | OS=Ubuntu
29 | PM=apt
30 | elif [ -n "$(grep 'elementary' /etc/issue)" -o "$(lsb_release -is 2>/dev/null)" == 'elementary' ]; then
31 | OS=Ubuntu
32 | PM=apt
33 | fi
34 | }
35 |
36 |
37 |
38 | init_sys(){
39 | echo 'init system !'
40 | if [ "${PM}" == 'yum' ]; then
41 | # 关闭SELinux
42 | setenforce 0
43 | sed -i "s/^SELINUX=enforcing/SELINUX=disabled/g" /etc/sysconfig/selinux
44 | sed -i "s/^SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
45 | sed -i "s/^SELINUX=permissive/SELINUX=disabled/g" /etc/sysconfig/selinux
46 | sed -i "s/^SELINUX=permissive/SELINUX=disabled/g" /etc/selinux/config
47 | # 开启包转发
48 | echo 1 > /proc/sys/net/ipv4/ip_forward
49 | if [ -e /etc/sysctl.conf ]; then
50 | # 如果值本身就为1,则不会被修改
51 | sed -i "s/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/g" /etc/sysctl.conf
52 | sed -i "s/net.ipv4.tcp_syncookies = 0/net.ipv4.tcp_syncookies = 1/g" /etc/sysctl.conf
53 | sed -i "s/net.ipv4.tcp_tw_reuse = 0/net.ipv4.tcp_tw_reuse = 1/g" /etc/sysctl.conf
54 | sed -i "s/net.ipv4.tcp_tw_recycle = 0/net.ipv4.tcp_tw_recycle = 1/g" /etc/sysctl.conf
55 | sed -i "s/net.ipv4.tcp_fin_timeout = 60/net.ipv4.tcp_fin_timeout = 30/g" /etc/sysctl.conf
56 | else
57 | echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf
58 | echo 'net.ipv4.tcp_syncookies = 1' >> /etc/sysctl.conf
59 | echo 'net.ipv4.tcp_tw_reuse = 1' >> /etc/sysctl.conf
60 | echo 'net.ipv4.tcp_tw_recycle = 1' >> /etc/sysctl.conf
61 | echo 'net.ipv4.tcp_fin_timeout = 30' >> /etc/sysctl.conf
62 | fi
63 | fi
64 | if [ "${PM}" == 'apt' ]; then
65 | # 开启包转发
66 | echo 1 > /proc/sys/net/ipv4/ip_forward
67 | if [ -e /etc/sysctl.conf ]; then
68 | # 如果值本身就为1,则不会被修改
69 | sed -i "s/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/g" /etc/sysctl.conf
70 | sed -i "s/net.ipv4.tcp_syncookies = 0/net.ipv4.tcp_syncookies = 1/g" /etc/sysctl.conf
71 | sed -i "s/net.ipv4.tcp_tw_reuse = 0/net.ipv4.tcp_tw_reuse = 1/g" /etc/sysctl.conf
72 | sed -i "s/net.ipv4.tcp_tw_recycle = 0/net.ipv4.tcp_tw_recycle = 1/g" /etc/sysctl.conf
73 | sed -i "s/net.ipv4.tcp_fin_timeout = 60/net.ipv4.tcp_fin_timeout = 30/g" /etc/sysctl.conf
74 | else
75 | echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf
76 | echo 'net.ipv4.tcp_syncookies = 1' >> /etc/sysctl.conf
77 | echo 'net.ipv4.tcp_tw_reuse = 1' >> /etc/sysctl.conf
78 | echo 'net.ipv4.tcp_tw_recycle = 1' >> /etc/sysctl.conf
79 | echo 'net.ipv4.tcp_fin_timeout = 30' >> /etc/sysctl.conf
80 | fi
81 | fi
82 | /sbin/sysctl -p
83 | }
84 |
85 |
86 | yum_squid(){
87 | echo 'start install squid !'
88 | yum install squid httpd-tools curl -y
89 | # 修改配置
90 | conf_path=/etc/squid
91 | basic_auth=/usr/lib64/squid
92 | echo "auth_param basic program ${basic_auth}/basic_ncsa_auth /etc/squid/passwords" >> ${conf_path}/squid.conf
93 | echo 'auth_param basic realm proxy' >> ${conf_path}/squid.conf
94 | echo 'acl authenticated proxy_auth REQUIRED' >> ${conf_path}/squid.conf
95 | echo 'http_access allow authenticated' >> ${conf_path}/squid.conf # 允许所有认证通过的客户端
96 | sed -i "s/http_port 3128/http_port ${squid_proxy_port}/g" ${conf_path}/squid.conf
97 | sed -i "s/http_access deny all/#http_access deny all/g" ${conf_path}/squid.conf
98 | # 高匿设置
99 | echo 'request_header_access Via deny all' >> ${conf_path}/squid.conf
100 | echo 'request_header_access X-Forwarded-For deny all' >> ${conf_path}/squid.conf
101 | # 生成密钥
102 | htpasswd -bc ${conf_path}/passwords ${squid_proxy_user} ${squid_proxy_passwd}
103 | chmod o+r ${conf_path}/passwords
104 | systemctl enable squid
105 | start_squid
106 | }
107 |
108 |
109 | apt_squid(){
110 | echo 'start install squid !'
111 | apt-get update -y && apt-get install squid apache2-utils curl -y
112 | # 修改配置
113 | if [ "${OS}" == 'Ubuntu' ]; then
114 | conf_path=/etc/squid3
115 | basic_auth=/usr/lib/squid3
116 | start_squid="sed -i '/By default this script does nothing/a\squid3' /etc/rc.local"
117 | elif [ "${OS}" == 'Debian' ]; then
118 | conf_path=/etc/squid
119 | basic_auth=/usr/lib/squid
120 | start_squid="service squid enable"
121 | fi
122 | echo "auth_param basic program ${basic_auth}/basic_ncsa_auth /etc/squid/passwords" >> ${conf_path}/squid.conf
123 | echo 'auth_param basic realm proxy' >> ${conf_path}/squid.conf
124 | echo 'acl authenticated proxy_auth REQUIRED' >> ${conf_path}/squid.conf
125 | echo 'http_access allow authenticated' >> ${conf_path}/squid.conf # 允许所有认证通过的客户端
126 | sed -i "s/http_port 3128/http_port ${squid_proxy_port}/g" ${conf_path}/squid.conf
127 | sed -i "s/http_access deny all/#http_access deny all/g" ${conf_path}/squid.conf
128 | # 高匿设置
129 | echo 'request_header_access Via deny all' >> ${conf_path}/squid.conf
130 | echo 'request_header_access X-Forwarded-For deny all' >> ${conf_path}/squid.conf
131 | # 生成密钥
132 | htpasswd -bc ${conf_path}/passwords ${squid_proxy_user} ${squid_proxy_passwd}
133 | chmod o+r ${conf_path}/passwords
134 | ${start_squid}
135 | start_squid
136 | }
137 |
138 |
139 | # 删除拨号软件,视服务商而定。
140 | clean_sys(){
141 | if [ "${OS}" == 'CentOS' ]; then
142 | yum remove squid -y
143 | rm -rf /etc/squid
144 | elif [ "${OS}" == 'Ubuntu' ]; then
145 | apt-get remove squid3 -y && apt-get autoremove
146 | rm -rf /etc/squid3
147 | elif [ "${OS}" == 'Debian' ]; then
148 | apt-get remove squid -y && apt-get autoremove
149 | rm -rf /etc/squid
150 | fi
151 | }
152 |
153 |
154 | start_squid(){
155 | # 重启Squid
156 | if [ "${OS}" == 'CentOS' ]; then
157 | systemctl restart squid
158 | elif [ "${OS}" == 'Ubuntu' ]; then
159 | pgrep squid3 |xargs kill -9 && sleep 1 && squid3
160 | elif [ "${OS}" == 'Debian' ]; then
161 | service squid restart
162 | fi
163 | }
164 |
165 |
166 |
167 | install_squid(){
168 | if [ "${OS}" == 'CentOS' ]; then
169 | init_sys
170 | yum_squid
171 | elif [ "${OS}" == 'Ubuntu' ]; then
172 | init_sys
173 | apt_squid
174 | elif [ "${OS}" == 'Debian' ]; then
175 | init_sys
176 | apt_squid
177 | fi
178 | }
179 |
180 |
181 |
182 |
183 | case "${1}" in
184 | install)
185 | check_os_type
186 | install_squid
187 | ;;
188 | uninstall)
189 | check_os_type
190 | clean_sys
191 | ;;
192 | restart)
193 | check_os_type
194 | start_squid
195 | ;;
196 | *)
197 | echo "请使用 $0 [install|uninstall|restart] 执行脚本!"
198 | ;;
199 | esac
200 |
201 |
202 | # 内核配置参考资料:https://blog.csdn.net/he_jian1/article/details/40787269
203 | # squid参考资料:https://blog.csdn.net/lucien_cc/article/details/7920510
204 | # http://www.squid-cache.org/Versions/v3/3.5/cfgman/
205 |
206 |
--------------------------------------------------------------------------------
/test/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Autuor : LeoLan mail:842632422@qq.com
4 | # @Version: Python 3
5 | #
6 |
--------------------------------------------------------------------------------
/test/demo.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from json import JSONDecodeError
3 |
4 |
5 | def get_data_from_post(url, data):
6 | """
7 |
8 | :param url: api
9 | :param data: dict
10 | :return: dict
11 | """
12 | response = requests.post(url, json=data, timeout=10)
13 | if response.status_code == 200:
14 | response_text = response.json()
15 | return response_text
16 | else:
17 | try:
18 | print(response.json())
19 | return None
20 | except JSONDecodeError:
21 | raise TypeError(f'json 解析错误,可能 {url} 不是 api 列表中的 url')
22 |
23 |
24 | test_url = 'http://www.baidu.com'
25 | host_url = 'http://192.168.2.21:8080'
26 |
27 | # 获取 token
28 | user_info = {
29 | "username": "admin",
30 | "password": "12345678",
31 | }
32 | token_url = f'{host_url}/api/v1/login'
33 | token_dict = get_data_from_post(token_url, user_info)
34 | token = token_dict.get('access_token')
35 |
36 | # 向接口提交 token,验证权限,获取的数据类似{'http': proxy_url, 'https': proxy_url}
37 | data = {'token': token}
38 | random_proxy_url = f'{host_url}/api/v1/random'
39 | random_proxy = get_data_from_post(random_proxy_url, data)
40 |
41 | resp = requests.get(url=test_url, proxies=random_proxy, timeout=10)
42 | if resp.status_code == 200:
43 | print(resp.text)
44 |
--------------------------------------------------------------------------------
/test/demo2.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | # 获取Token(返回的token 默认5小时有效)
4 | # 代理池地址(Docker部署的服务器)
5 | api_url = 'http://192.168.2.21:8080'
6 |
7 |
8 | def get_token():
9 | # 获取Token(返回的token 默认5小时有效)
10 | url = f'{api_url}/api/v1/login'
11 | # 修改为自己的账户信息
12 | user_info = {"username": "admin", "password": "12345678"}
13 | token = requests.post(url=url, json=user_info).json().get('access_token')
14 | if token:
15 | return {"token": token}
16 | return None
17 |
18 |
19 | if __name__ == '__main__':
20 | token = get_token() # token是长时间有效的,获取一次就好。
21 | if token:
22 | # 获取一个随机代理
23 | random_proxy = requests.post(url=f'{api_url}/api/v1/random', json=get_token()).json()
24 | if 'http' in random_proxy.keys():
25 | # 代理正常返回
26 | resp = requests.get(url='https://www.baidu.com', proxies=random_proxy, timeout=10)
27 | print(resp.text)
28 |
--------------------------------------------------------------------------------
/test/test_api.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from json import JSONDecodeError
3 |
4 | test_url = 'http://www.baidu.com'
5 | host_url = 'http://192.168.2.21:8080'
6 |
7 |
8 | def get_data_from_post(url, data):
9 | response = requests.post(url, json=data, timeout=10)
10 | if response.status_code == 200:
11 | response_json = resp.json()
12 | return response_json
13 | else:
14 | try:
15 | print(response.json())
16 | return None
17 | except JSONDecodeError:
18 | raise TypeError(f'json 解析错误,可能 {url} 不是 api 列表中的 url')
19 |
20 |
21 | # 测试 /
22 | resp = requests.get(host_url)
23 | index = resp.json()
24 | print('index:', index, end='\n\n')
25 |
26 | # 测试 /api/v1/login
27 | user_info = {
28 | "username": "admin",
29 | "password": "12345678",
30 | }
31 | token_url = f'{host_url}/api/v1/login'
32 | resp_json = get_data_from_post(token_url, user_info)
33 | token = resp_json.get('access_token')
34 | print('token:', token, end='\n\n')
35 |
36 | # 测试 /api/v1/random
37 | data = {'token': token}
38 | random_proxy_url = f'{host_url}/api/v1/random'
39 | random_proxy = get_data_from_post(random_proxy_url, data)
40 | print('random_proxy:', random_proxy, end='\n\n')
41 |
42 | # 测试 /api/v1/proxies
43 | proxies_data = data.update(proxy_name='myadsl1')
44 | name_proxy_url = f'{host_url}/api/v1/proxies'
45 | name_proxy = get_data_from_post(name_proxy_url, data)
46 | print('name_proxy:', name_proxy, end='\n\n')
47 |
48 | # 测试 /api/v1/names
49 | client_names_url = f'{host_url}/api/v1/names'
50 | client_names = get_data_from_post(client_names_url, data)
51 | print('client_names:', client_names, end='\n\n')
52 |
53 | # 测试 /api/v1/all
54 | all_proxies_url = f'{host_url}/api/v1/all'
55 | all_proxies = get_data_from_post(all_proxies_url, data)
56 | print('all_proxies:', all_proxies, end='\n\n')
57 |
58 | # 测试 /api/v1/delete
59 | delete_data = data.update(proxy_name='myadsl1')
60 | del_proxy_url = f'{host_url}/api/v1/delete'
61 | del_proxy = get_data_from_post(del_proxy_url, data)
62 | print('del_proxy:', del_proxy, end='\n\n')
63 |
64 | # proxy = all_proxies['']
65 | # resp = requests.get(url=test_url, proxies=random_proxy, timeout=10)
66 | # print(resp.text)
67 |
--------------------------------------------------------------------------------
/test/test_fabric.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Autuor : LeoLan mail:842632422@qq.com
4 | # @Version: Python 3
5 | #
6 |
7 |
8 | from config.hosts import *
9 | from fabric import Connection
10 |
11 |
12 | def check_host(ssh_cli):
13 | # redis_cli.get(nickname)
14 | try:
15 | ssh_cli.run('squid -v|grep Version')
16 | try:
17 | # squid是正常的,重启防假死、程序已崩溃
18 | ssh_cli.run('./squid.sh restart')
19 | except Exception:
20 | # 脚本不存在
21 | ssh_cli.put('../script-sh/squid.sh && chmod +x squid.sh') # 覆盖目标文件
22 | ssh_cli.run('chmod +x squid.sh && ./squid.sh restart')
23 | except Exception:
24 | # 系统中没有安装squid
25 | ssh_cli.put('../script-sh/squid.sh && chmod +x squid.sh') # 覆盖目标文件
26 | ssh_cli.run('chmod +x squid.sh && ./squid.sh install')
27 |
28 |
29 |
30 | def task_main():
31 | for _group in HOSTS_GROUP:
32 | host_list = HOSTS_GROUP.get(_group)
33 | for key, values in host_list.items():
34 | # print(key, values)
35 | ssh_cli = Connection(f"{values['username']}@{values['host']}", port=values['port'],
36 | connect_kwargs={"password": values['password']})
37 | with ssh_cli.cd('/root'):
38 | #check_host(ssh_cli)
39 | # 获取外网地址
40 | proxy_ip = ssh_cli.run('curl http://members.3322.org/dyndns/getip')
41 | print(proxy_ip)
42 |
43 |
44 |
45 | # from fabric.group import Group, SerialGroup
46 | # def task2():
47 | # task_list = []
48 | # for _group in HOSTS_GROUP:
49 | # host_list = HOSTS_GROUP.get(_group)
50 | # for key, values in host_list.items():
51 | # # print(key, values)
52 | # key = Connection(f"{values['username']}@{values['host']}", port=values['port'],
53 | # connect_kwargs={"password": values['password']})
54 | # task_list.append(key)
55 | # print("task_list", task_list)
56 | # group = SerialGroup(task_list)
57 | # results = group.run("pwd")
58 | # print(results)
59 |
60 |
61 |
62 | if __name__ == '__main__':
63 | task_main()
64 | # task2()
65 | # import sys
66 | # os.system('cat ../script-sh/squid.sh')
67 | # print(f'{os.getcwd()}/../script-sh')
--------------------------------------------------------------------------------
/test/test_jwt.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | # Flask JWT 验证
5 |
6 | import time
7 | from adslproxy.db import RedisClient
8 | from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
9 | from itsdangerous import SignatureExpired, BadSignature, BadData
10 | from flask import Flask, jsonify, request, abort
11 |
12 | app = Flask(__name__)
13 |
14 | # 用于存储已经保存的账户信息
15 | redis_cli = RedisClient()
16 |
17 | #############################################################
18 | secret_key = 'PMF9IAnk16KVbUel'
19 | salt = 'jR9kK3KjYDN79t6s'
20 | access_token_expires_in = 60 * 60 * 5
21 | refresh_token_expires_in = 60 * 60 * 6
22 |
23 |
24 | def genTokenSeq(user):
25 | """
26 | # 生成token
27 | :param user: 输入用户名
28 | :return: 两个token
29 | """
30 | access_token_gen = Serializer(secret_key=secret_key, salt=salt, expires_in=access_token_expires_in)
31 | refresh_token_gen = Serializer(secret_key=secret_key, salt=salt, expires_in=refresh_token_expires_in)
32 | timestamp = time.time()
33 | access_token = access_token_gen.dumps({
34 | "userid": user,
35 | "iat": timestamp
36 | })
37 | refresh_token = refresh_token_gen.dumps({
38 | "userid": user,
39 | "iat": timestamp
40 | })
41 |
42 | data = {
43 | "access_token": str(access_token, 'utf-8'),
44 | "access_token_expire_in": access_token_expires_in,
45 | "refresh_token": str(refresh_token, 'utf-8'),
46 | "refresh_token_expire_in": refresh_token_expires_in,
47 | }
48 | return data
49 |
50 |
51 | def validateToken(token):
52 | """
53 | # 解析token
54 | :param token: 输入toke
55 | :return: 解析结果
56 | """
57 | s = Serializer(secret_key=secret_key, salt=salt)
58 | try:
59 | data = s.loads(token)
60 | except SignatureExpired:
61 | return jsonify({'code': 401, 'message': 'toekn expired'}) # token过期
62 | except BadSignature as e:
63 | encoded_payload = e.payload
64 | if encoded_payload is not None:
65 | try:
66 | s.load_payload(encoded_payload)
67 | except BadData:
68 | return jsonify({'code': 401, 'message': 'token tampered'}) # token篡改
69 | return jsonify({'code': 401, 'message': 'badSignature of token'}) # 签名有误
70 | except Exception:
71 | return jsonify({'code': 401, 'message': 'wrong token with unknown reason'}) # 令牌错误
72 |
73 | if 'userid' not in data:
74 | return jsonify({'code': 401, 'message': 'illegal payload inside'}) # 非法载荷
75 | return jsonify({'code': 200, 'userid': data['userid'], 'message': f"user({data['userid']}) logged in by token."})
76 |
77 |
78 | ###############################################################
79 | # API
80 | @app.route('/login', methods=['POST'])
81 | def login():
82 | """
83 | 客户端发送json过来
84 | {
85 | "username":"admin",
86 | "password":"12345678"
87 | }
88 | """
89 | json_data = request.get_json()
90 | username = json_data.get('username')
91 | password = json_data.get('password')
92 | if username is None or password is None:
93 | abort(400)
94 | # 这里校验账户是否合法,我这里用来redis简单对比;关系型数据库需要自行修改。
95 | # 这里使用了redis做AB数据集切换(账户密码是定时从配置文件读取并更新的),redis方法是自己封装的。
96 | list_key = RedisClient(list_key='ab_set').get('a_or_b')
97 | if RedisClient(list_key=list_key).get(username) == password:
98 | return genTokenSeq(username)
99 | else:
100 | abort(400)
101 |
102 |
103 | @app.route('/', methods=['POST'])
104 | def index():
105 | """
106 | 客户端发送json过来
107 | {
108 | "token":"token-str",
109 | }
110 | """
111 | json_data = request.get_json()
112 | print(json_data)
113 | token = ''
114 | if json_data:
115 | token = json_data.get('token')
116 | else:
117 | abort(400)
118 | if token:
119 | data = validateToken(token)
120 | return data, 200
121 | else:
122 | abort(400)
123 |
124 |
125 | if __name__ == '__main__':
126 | app.run(host='0.0.0.0', port=5000, debug=True)
127 |
--------------------------------------------------------------------------------
/test/test_paramiko.py:
--------------------------------------------------------------------------------
1 | # -*-coding:utf8-*-
2 | # @Time : 2019/7/29
3 | # @Version: Python 3
4 | #
5 |
6 |
7 | import paramiko
8 | from config.hosts import *
9 |
10 | """
11 | 参考资料:
12 | https://zhuanlan.zhihu.com/p/25031447
13 | https://blog.csdn.net/a_gorilla/article/details/82151541
14 |
15 | https://www.fabfile.org/installing.html
16 | """
17 | import os
18 | from adslproxy.api_server import WORK_DIR
19 |
20 | SCRIPT_DIR = os.path.join(WORK_DIR, 'script-sh')
21 | SQUID_SH = os.path.join(SCRIPT_DIR, 'squid.sh')
22 |
23 |
24 | def depoly_monitor(host_info):
25 | with paramiko.SSHClient() as client:
26 | client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
27 | # print(host_info['password'])
28 | client.connect(hostname=host_info['host'], username=host_info['username'], password=host_info['password'],
29 | port=host_info['port'])
30 |
31 | stdin, stdout, stderr = client.exec_command('docker -v')
32 | print(stdout.readlines())
33 | print(stderr.readlines())
34 |
35 | # with client.open_sftp() as sftp:
36 | # sftp.put(SQUID_SH, '/home/123.sh')
37 | # sftp.chmod('123.sh', 0o755)
38 |
39 | # stdin, stdout, stderr = client.exec_command('curl http://members.3322.org/dyndns/getip')
40 | # print(stdout.readlines())
41 |
42 |
43 | def main():
44 | for i in HOSTS_GROUP['group1'].values():
45 | print(type(i), i)
46 | depoly_monitor(i)
47 |
48 |
49 | if __name__ == '__main__':
50 | main()
51 |
--------------------------------------------------------------------------------
/test/test_proxy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | #
5 |
6 | import os
7 | from urllib import request
8 |
9 | # 代理服务器账户
10 | proxy_host = '114.115.166.201'
11 | proxy_user = 'myproxy'
12 | proxy_passwd = 'N2PYOnRDk5gKInqQ'
13 | proxy_port = 3100
14 |
15 | # 这是代理IP
16 | # proxy = {'http': f'http://{proxy_user}:{proxy_passwd}@{proxy_host}:{proxy_port}'}
17 |
18 |
19 | proxy = {'http': f'http://{proxy_user}:{proxy_passwd}@127.0.0.1:3100' }
20 |
21 |
22 | url1 = 'http://members.3322.org/dyndns/getip'
23 | url2 = 'http://test.heroflower.top/'
24 | url3 = 'https://weixin.sogou.com/weixin?type=2&ie=utf8&s_from=hotnews&query=%E6%9C%80%E6%83%A8%E8%88%AA%E7%8F%AD'
25 |
26 |
27 | def test_porxy():
28 | # 访问网址
29 | # 创建ProxyHandler
30 | proxy_support = request.ProxyHandler(proxy)
31 | # 创建Opener
32 | opener = request.build_opener(proxy_support)
33 | # 添加User Angent
34 | opener.addheaders = [('User-Agent',
35 | 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')]
36 | # 安装OPener
37 | request.install_opener(opener)
38 | # 使用自己安装好的Opener
39 | response = request.urlopen(url1, timeout=5)
40 | # 读取相应信息并解码
41 | html = response.read().decode("utf-8")
42 | # 打印信息
43 | print("代理IP为:", html)
44 | # 打印本机IP
45 | print('本机外网IP为:', os.popen('curl http://members.3322.org/dyndns/getip').read())
46 |
47 |
48 | if __name__ == '__main__':
49 | test_porxy()
50 |
51 | ######################################
52 |
53 | import socket
54 | import struct
55 | import random
56 | import requests
57 |
58 |
59 | def createHeader():
60 | ip = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
61 | headers = {
62 | 'Content-Type': 'application/x-www-form-urlencoded',
63 | 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
64 | 'CLIENT-IP': ip,
65 | 'X-FORWARDED-FOR': ip
66 | }
67 | return headers
68 |
69 |
70 | # if __name__ == '__main__':
71 | # headers = createHeader()
72 | # html = requests.get(url3, headers=headers, proxies=proxy)
73 | # print(html.text)
74 | # import re
75 | #
76 | # sss = re.findall('clientIp = "(.*?)";', html.text)
77 | # print(sss)
78 |
--------------------------------------------------------------------------------
/test/test_threading.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*-coding:utf-8-*-
3 | # @Version: Python 3
4 | #
5 |
6 | import time
7 | import threading
8 |
9 |
10 | # https://www.cnblogs.com/cnkai/p/7504980.html
11 |
12 | def run():
13 | time.sleep(2)
14 | print('当前线程的名字是: ', threading.current_thread().name)
15 | time.sleep(3)
16 | t = threading.Thread(target=run)
17 | t.start()
18 |
19 |
20 |
21 | def task():
22 | # time.sleep(1)
23 | print('任务二')
24 | # time.sleep(2)
25 |
26 |
27 | if __name__ == '__main__':
28 | start_time = time.time()
29 |
30 | print('这是主线程:', threading.current_thread().name)
31 | thread_list = []
32 | for i in range(5):
33 | t = threading.Thread(target=run)
34 | thread_list.append(t)
35 |
36 | for t in thread_list:
37 | t.start()
38 |
39 | for t in thread_list:
40 | t.join()
41 |
42 | print('主线程结束!', threading.current_thread().name)
43 | print('一共用时:', time.time() - start_time)
44 |
--------------------------------------------------------------------------------