pax_global_header00006660000000000000000000000064135005345620014515gustar00rootroot0000000000000052 comment=a8bfabd4576e40988122757034abaded3e959056 sshoot-1.4.2/000077500000000000000000000000001350053456200130405ustar00rootroot00000000000000sshoot-1.4.2/.coveragerc000066400000000000000000000001611350053456200151570ustar00rootroot00000000000000[run] source = sshoot omit = sshoot/main.py [report] show_missing = True fail_under = 100 skip_covered = True sshoot-1.4.2/.gitignore000066400000000000000000000001311350053456200150230ustar00rootroot00000000000000*.pyc *.pyo /build /html /*.egg-info /.coverage /.mypy_cache /.tox .eggs .pybuild .cache sshoot-1.4.2/.isort.cfg000066400000000000000000000003461350053456200147420ustar00rootroot00000000000000[settings] combine_as_imports = true force_grid_wrap = 2 force_sort_within_sections = true from_first = false include_trailing_comma = true multi_line_output = 3 not_skip = __init__.py order_by_type = false use_parentheses = true sshoot-1.4.2/.style.yapf000066400000000000000000000010271350053456200151370ustar00rootroot00000000000000# -*- mode: conf -*- [style] align_closing_bracket_with_visual_indent = false allow_split_before_dict_value = false allow_multiline_dictionary_keys = true blank_line_before_nested_class_or_def = true coalesce_brackets = false column_limit = 79 continuation_align_style = SPACE space_between_ending_comma_and_closing_bracket = true split_all_comma_separated_values = false split_before_expression_after_opening_paren = true split_before_first_argument = true split_complex_comprehension = false split_penalty_after_opening_bracket= 35 sshoot-1.4.2/.travis.yml000066400000000000000000000005241350053456200151520ustar00rootroot00000000000000language: python python: - "3.6" - "3.7-dev" matrix: fast_finish: true stages: - lint - check - test install: pip install tox codecov jobs: include: - stage: lint script: tox -e lint python: "3.6" - stage: check script: tox -e check python: "3.6" script: tox -e coverage after_success: codecov sshoot-1.4.2/CHANGES.rst000066400000000000000000000037641350053456200146540ustar00rootroot00000000000000v1.4.2 - 2019-06-13 =================== - Rework tests and project setup - Fix yaml warning (Fixes: #6) v1.4.1 - 2018-06-30 =================== - Use pathlib.Path instead of strings. - I8n-related cleanups. v1.4.0 - 2017-10-22 =================== - Add i18n support and it_IT translation. v1.3.2 - 2017-10-15 =================== - Use ``pyxdg`` instead of ``xdg``. v1.3.1 - 2017-10-10 =================== - Specify long description content-type. v1.3.0 - 2017-10-02 =================== - Support profiles listing in different formats (table, CSV, YAML, JSON) (Fixes: #3) - Move configuration path to XDG conventions (Fixes: #1) v1.2.6 - 2017-05-25 =================== - Move project to GitHub, small test cleanups. v1.2.5 - 2016-11-29 =================== - Filter running sessions for start/stop commands autocompletion. v1.2.4 - 2016-11-20 =================== - Fix autocompletion setup again. v1.2.3 - 2016-11-20 =================== - Fix autocompletion. v1.2.2 - 2016-11-20 =================== - Add support for bash-completion. v1.2.1 - 2015-11-04 =================== - Fix error message decoding when profile fails to start. v1.2.0 - 2015-09-04 =================== - Add is-running command to check whether a profile is running. v1.1.0 - 2015-05-27 =================== - Switch to python3. v1.0.3 - 2015-04-15 =================== - Support passing extra options to sshuttle when starting a profile. v1.0.1 - 2014-11-23 =================== - Add get-command subcommand to return the sshuttle command line. v1.0.0 - 2014-10-08 =================== - Separate (optional) configuration and sessions files. - Directory for pidfiles is created in temporary directory, rather than home, to avoid issues if the home is shared. v0.0.3 - 2014-09-01 =================== - Fix dependencies. v0.0.2 - 2014-08-24 =================== - Support for managing sshuttle sessions (add, remove start, stop). v0.0.1 - 2014-08-05 =================== - Initial release. sshoot-1.4.2/LICENSE.txt000066400000000000000000001045131350053456200146670ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . sshoot-1.4.2/MANIFEST.in000066400000000000000000000001621350053456200145750ustar00rootroot00000000000000include LICENSE.txt README.rst CHANGES.rst recursive-include shell-completion * recursive-include sshoot/locale * sshoot-1.4.2/README.rst000066400000000000000000000030131350053456200145240ustar00rootroot00000000000000sshoot - Manage sshuttle VPN sessions ===================================== |Latest Version| |Build Status| |Coverage Status| Command-line interface to manage multiple sshuttle_ VPN sessions. ``sshuttle`` creates a VPN connection from your machine to any remote server that you can connect to via ssh. ``sshoot`` allows to define multiple VPN sessions using ``sshuttle`` and start/stop them as needed. It supports configuration options for most of ``sshuttle``'s features, providing flexible configuration for profiles. Usage ----- Create a profile: .. code:: bash $ sshoot create -r host1.remote -HNd vpn1 10.0.0.0/24 Start it: .. code:: bash $ sshoot start vpn1 Profile started. List existing profiles (active ones are marked): .. code:: bash $ sshoot list Profile Remote host Subnets -------------------------------------------- * vpn1 host1.remote 10.0.0.0/24 vpn2 host2.remote 192.168.0.0/16 Stop the profile: .. code:: bash $ sshoot stop vpn1 Remove it: .. code:: bash $ sshoot delete vpn1 .. _sshuttle: https://github.com/apenwarr/sshuttle .. |Latest Version| image:: https://img.shields.io/pypi/v/sshoot.svg :target: https://pypi.python.org/pypi/sshoot .. |Build Status| image:: https://img.shields.io/travis/albertodonato/sshoot.svg :target: https://travis-ci.org/albertodonato/sshoot .. |Coverage Status| image:: https://img.shields.io/codecov/c/github/albertodonato/sshoot/master.svg :target: https://codecov.io/gh/albertodonato/sshoot sshoot-1.4.2/mypy.ini000066400000000000000000000001531350053456200145360ustar00rootroot00000000000000[mypy] incremental = False warn_return_any = True warn_unused_configs = True ignore_missing_imports = True sshoot-1.4.2/setup.cfg000066400000000000000000000005401350053456200146600ustar00rootroot00000000000000[extract_messages] project = sshoot output-file = sshoot/locale/sshoot.pot sort-by-file = true [init_catalog] domain = sshoot input-file = sshoot/locale/sshoot.pot output-dir = sshoot/locale [update_catalog] domain = sshoot input-file = sshoot/locale/sshoot.pot output-dir = sshoot/locale [compile_catalog] domain = sshoot directory = sshoot/locale sshoot-1.4.2/setup.py000066400000000000000000000030421350053456200145510ustar00rootroot00000000000000from pathlib import Path from setuptools import ( find_packages, setup, ) tests_require = ['fixtures', 'pytest', 'pytest-mock'] config = { 'name': 'sshoot', 'version': '1.4.2', 'license': 'GPLv3+', 'description': 'Manage multiple sshuttle VPN sessions', 'long_description': Path('README.rst').read_text(), 'author': 'Alberto Donato', 'author_email': 'alberto.donato@gmail.com', 'maintainer': 'Alberto Donato', 'maintainer_email': 'alberto.donato@gmail.com', 'url': 'https://github.com/albertodonato/sshoot', 'download_url': 'https://github.com/albertodonato/sshoot/releases', 'packages': find_packages(include=['sshoot', 'sshoot.*']), 'include_package_data': True, 'entry_points': { 'console_scripts': ['sshoot = sshoot.main:sshoot'] }, 'test_suite': 'sshoot', 'setup_requires': ['Babel'], 'install_requires': ['PyYAML', 'prettytable', 'argcomplete', 'pyxdg'], 'tests_require': tests_require, 'extras_require': { 'testing': tests_require }, 'keywords': 'ssh sshuttle vpn', 'classifiers': [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', ( 'License :: OSI Approved :: ' 'GNU General Public License v3 or later (GPLv3+)'), 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: System :: Networking', 'Topic :: Utilities' ] } setup(**config) sshoot-1.4.2/shell-completion/000077500000000000000000000000001350053456200163165ustar00rootroot00000000000000sshoot-1.4.2/shell-completion/sshoot000066400000000000000000000001421350053456200175550ustar00rootroot00000000000000# -*- mode:sh -*- # # Bash-completion for sshoot # eval "$(register-python-argcomplete3 sshoot)" sshoot-1.4.2/sshoot/000077500000000000000000000000001350053456200143575ustar00rootroot00000000000000sshoot-1.4.2/sshoot/__init__.py000066400000000000000000000003221350053456200164650ustar00rootroot00000000000000"""Manage multiple sshuttle VPN sessions.""" from distutils.version import LooseVersion import pkg_resources __all__ = ['__version__'] __version__ = LooseVersion(pkg_resources.require('sshoot')[0].version) sshoot-1.4.2/sshoot/autocomplete.py000066400000000000000000000014441350053456200174350ustar00rootroot00000000000000"""Shell completion helpers.""" from .manager import Manager def complete_argument(argument, completer): """wrapper for setting up argument completer.""" argument.completer = completer return argument def profile_completer(prefix, parsed_args, running=None, **kwargs): """Autocomplete helper for profile names. Parameters: - running: filter profiles that are running or not (by default no filter is applied). """ manager = Manager(config_path=parsed_args.config) manager.load_config() for name in manager.get_profiles(): if not name.startswith(prefix): continue if running is None or manager.is_running(name) == running: # Either no filter is set or it matches the profile status yield name sshoot-1.4.2/sshoot/config.py000066400000000000000000000050471350053456200162040ustar00rootroot00000000000000"""Handle configuration files.""" import yaml from .profile import Profile def yaml_dump(data, fh=None): """Dump data in YAML format with sane defaults for readability.""" return yaml.safe_dump( data, fh, default_flow_style=False, allow_unicode=True) class Config: """Handle configuration file loading/saving.""" CONFIG_KEYS = frozenset(['executable']) def __init__(self, path): self._config_file = path / 'config.yaml' self._profiles_file = path / 'profiles.yaml' self._reset() def load(self): """Load configuration from file.""" self._reset() self._config = self._load_yaml_file(self._config_file) profiles = self._load_yaml_file(self._profiles_file) for name, conf in profiles.items(): self._profiles[name] = Profile.from_dict(self._from_config(conf)) def save(self): """Save profiles configuration to file.""" self._profiles_file.write_text( yaml_dump(self._build_profiles_config())) def add_profile(self, name, profile): """Add a profile to the configuration.""" if name in self._profiles: raise KeyError(name) self._profiles[name] = profile def remove_profile(self, name): """Add the given profile to the configuration.""" del self._profiles[name] @property def profiles(self): """Return a dict with profiles, using names as key.""" return self._profiles.copy() @property def config(self): """Return a dict with the configuration.""" return { key: value for key, value in self._config.items() if key in self.CONFIG_KEYS } def _reset(self): """Reset default empty config.""" self._profiles = {} self._config = {} def _load_yaml_file(self, path): """Load the specified YAML file.""" if not path.exists(): return {} return yaml.safe_load(path.read_text()) or {} def _build_profiles_config(self): """Return the profiles config dict to be saved to file.""" return { name: self._to_config(profile.config()) for name, profile in self._profiles.items() } def _from_config(self, config): """Convert a config to a params dict.""" return {key.replace('-', '_'): value for key, value in config.items()} def _to_config(self, params): """Convert a params dict to a config.""" return {key.replace('_', '-'): value for key, value in params.items()} sshoot-1.4.2/sshoot/conftest.py000066400000000000000000000017061350053456200165620ustar00rootroot00000000000000from pathlib import Path import pytest from .config import Config from .manager import Manager @pytest.fixture def config_dir(tmpdir): """A directory for configuration files. """ path = Path(tmpdir / 'config') path.mkdir() yield path @pytest.fixture def config_file(config_dir): """The configuration file.""" yield config_dir / 'config.yaml' @pytest.fixture def profiles_file(config_dir): """A Path for profiles configuration file.""" yield config_dir / 'profiles.yaml' @pytest.fixture def config(config_dir): """A Config object configured with a temp path.""" yield Config(config_dir) @pytest.fixture def run_dir(tmpdir): path = Path(tmpdir / 'run') path.mkdir() yield path @pytest.fixture def sessions_dir(run_dir): path = run_dir / 'sessions' path.mkdir() yield path @pytest.fixture def profile_manager(config_dir, run_dir): yield Manager(config_path=config_dir, rundir=run_dir) sshoot-1.4.2/sshoot/i18n.py000066400000000000000000000007561350053456200155200ustar00rootroot00000000000000"""Internationalization setup.""" import argparse import gettext import os def _setup_i18n(): """Setup internationalization.""" argparse._ = _get_i18n_func('argparse') return _get_i18n_func('sshoot') # default domain def _get_i18n_func(domain): """Return the internationalization function.""" localedir = os.path.join(os.path.dirname(__file__), 'locale') g = gettext.translation(domain, localedir=localedir, fallback=True) return g.gettext _ = _setup_i18n() sshoot-1.4.2/sshoot/listing.py000066400000000000000000000110171350053456200164020ustar00rootroot00000000000000"""Helpers for listing output.""" from collections import OrderedDict from csv import DictWriter from io import StringIO import json from prettytable import ( HEADER, PrettyTable, ) from .config import yaml_dump from .i18n import _ # Map names to profile fileds _FIELDS_MAP = OrderedDict( [ (_('Remote host'), 'remote'), (_('Subnets'), 'subnets'), (_('Auto hosts'), 'auto_hosts'), (_('Auto nets'), 'auto_nets'), (_('DNS forward'), 'dns'), (_('Exclude subnets'), 'exclude_subnets'), (_('Seed hosts'), 'seed_hosts'), (_('Extra options'), 'extra_opts') ]) NAME_FIELD = _('Name') STATUS_FIELD = _('Status') class InvalidFormat(Exception): def __init__(self, name): super().__init__(_('Invalid output format: {name}').format(name=name)) class ProfileListing: """List details for details in the specified format.""" def __init__(self, manager): self.manager = manager @classmethod def supported_formats(cls): return sorted( attr[8:] for attr in dir(cls) if attr.startswith('_format_')) def get_output(self, _format, verbose=False): """Return a string with listing in the specified format.""" formatter = getattr(self, '_format_{}'.format(_format), None) if formatter is None: raise InvalidFormat(_format) profiles_iter = self.manager.get_profiles().items() return formatter(profiles_iter, verbose=verbose) def _format_table(self, profiles_iter, verbose=False): """Format profiles data as a table.""" titles = ['', NAME_FIELD] titles.extend(_FIELDS_MAP) columns = list(_FIELDS_MAP.values()) if not verbose: # Only basic info titles = titles[:4] columns = columns[:2] table = PrettyTable(titles) table.align = 'l' table.vertical_char = ' ' table.junction_char = table.horizontal_char table.padding_width = 0 table.left_padding_width = 0 table.right_padding_width = 1 table.hrules = HEADER for name, profile in profiles_iter: row = ['*' if self.manager.is_running(name) else '', name] row.extend( _format_value(getattr(profile, column)) for column in columns) table.add_row(row) return table.get_string(sortby=NAME_FIELD) + '\n' def _format_csv(self, profiles_iter, verbose=False): """Format profiles data as CSV.""" titles = [NAME_FIELD, STATUS_FIELD] titles.extend(_FIELDS_MAP) buf = StringIO() writer = DictWriter(buf, fieldnames=titles) writer.writeheader() for name, profile in profiles_iter: row = { NAME_FIELD: name, STATUS_FIELD: _profile_status(self.manager, name) } row.update( { title: getattr(profile, _FIELDS_MAP[title]) for title in titles[2:] }) writer.writerow(row) return buf.getvalue() def _format_json(self, profiles_iter, verbose=False): """Format profiles data as JSON.""" data = {} for name, profile in profiles_iter: config = profile.config() # config['active'] = manager.is_running(name) data[name] = config return json.dumps(data) def _format_yaml(self, profiles_iter, verbose=False): """Format profiles data as YAML.""" data = {name: profile.config() for name, profile in profiles_iter} return yaml_dump(data) def profile_details(manager, name): """Return a string with details about a profile, formatted as a table.""" profile = manager.get_profile(name) table = PrettyTable( field_names=['key', 'value'], header=False, border=False) table.align['key'] = table.align['value'] = 'l' table.add_row(('{}:'.format(NAME_FIELD), name)) table.add_row(('{}:'.format(STATUS_FIELD), _profile_status(manager, name))) for name, field in _FIELDS_MAP.items(): table.add_row( ('{}:'.format(name), _format_value(getattr(profile, field)))) return table.get_string() def _profile_status(manager, name): """Return a string with the status of a profile.""" return _('ACTIVE') if manager.is_running(name) else _('STOPPED') def _format_value(value): """Convert value to string, handling special cases.""" if isinstance(value, (list, tuple)): return ' '.join(value) if value is None: return '' return value sshoot-1.4.2/sshoot/locale/000077500000000000000000000000001350053456200156165ustar00rootroot00000000000000sshoot-1.4.2/sshoot/locale/argparse.pot000066400000000000000000000062071350053456200201530ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR , YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2017-10-21 14:56+CEST\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: pygettext.py 1.5\n" #: /usr/lib/python3.6/argparse.py:304 msgid "usage: " msgstr "" #: /usr/lib/python3.6/argparse.py:835 msgid ".__call__() not defined" msgstr "" #: /usr/lib/python3.6/argparse.py:1132 msgid "unknown parser %(parser_name)r (choices: %(choices)s)" msgstr "" #: /usr/lib/python3.6/argparse.py:1186 msgid "argument \"-\" with mode %r" msgstr "" #: /usr/lib/python3.6/argparse.py:1194 msgid "can't open '%s': %s" msgstr "" #: /usr/lib/python3.6/argparse.py:1398 msgid "cannot merge actions - two groups are named %r" msgstr "" #: /usr/lib/python3.6/argparse.py:1436 msgid "'required' is an invalid argument for positionals" msgstr "" #: /usr/lib/python3.6/argparse.py:1458 msgid "invalid option string %(option)r: must start with a character %(prefix_chars)r" msgstr "" #: /usr/lib/python3.6/argparse.py:1478 msgid "dest= is required for options like %r" msgstr "" #: /usr/lib/python3.6/argparse.py:1495 msgid "invalid conflict_resolution value: %r" msgstr "" #: /usr/lib/python3.6/argparse.py:1579 msgid "mutually exclusive arguments must be optional" msgstr "" #: /usr/lib/python3.6/argparse.py:1642 msgid "positional arguments" msgstr "" #: /usr/lib/python3.6/argparse.py:1643 msgid "optional arguments" msgstr "" #: /usr/lib/python3.6/argparse.py:1658 msgid "show this help message and exit" msgstr "" #: /usr/lib/python3.6/argparse.py:1689 msgid "cannot have multiple subparser arguments" msgstr "" #: /usr/lib/python3.6/argparse.py:1741 msgid "unrecognized arguments: %s" msgstr "" #: /usr/lib/python3.6/argparse.py:1838 msgid "not allowed with argument %s" msgstr "" #: /usr/lib/python3.6/argparse.py:1884 /usr/lib/python3.6/argparse.py:1898 msgid "ignored explicit argument %r" msgstr "" #: /usr/lib/python3.6/argparse.py:2005 msgid "the following arguments are required: %s" msgstr "" #: /usr/lib/python3.6/argparse.py:2020 msgid "one of the arguments %s is required" msgstr "" #: /usr/lib/python3.6/argparse.py:2063 msgid "expected one argument" msgstr "" #: /usr/lib/python3.6/argparse.py:2064 msgid "expected at most one argument" msgstr "" #: /usr/lib/python3.6/argparse.py:2065 msgid "expected at least one argument" msgstr "" #: /usr/lib/python3.6/argparse.py:2127 msgid "ambiguous option: %(option)s could match %(matches)s" msgstr "" #: /usr/lib/python3.6/argparse.py:2190 msgid "unexpected option string: %s" msgstr "" #: /usr/lib/python3.6/argparse.py:2294 msgid "%r is not callable" msgstr "" #: /usr/lib/python3.6/argparse.py:2311 msgid "invalid %(type)s value: %(value)r" msgstr "" #: /usr/lib/python3.6/argparse.py:2322 msgid "invalid choice: %(value)r (choose from %(choices)s)" msgstr "" #: /usr/lib/python3.6/argparse.py:2398 msgid "" "%(prog)s: error: %(message)s\n" msgstr "" sshoot-1.4.2/sshoot/locale/it_IT/000077500000000000000000000000001350053456200166265ustar00rootroot00000000000000sshoot-1.4.2/sshoot/locale/it_IT/LC_MESSAGES/000077500000000000000000000000001350053456200204135ustar00rootroot00000000000000sshoot-1.4.2/sshoot/locale/it_IT/LC_MESSAGES/argparse.mo000066400000000000000000000057221350053456200225620ustar00rootroot00000000000000 1.`4x(.%3Yx!3%NE-#+(Kt55< Jc54) 3 N b & 3 + U 5_  #   ( '* !R 8t  %(prog)s: error: %(message)s %r is not callable'required' is an invalid argument for positionals.__call__() not definedambiguous option: %(option)s could match %(matches)sargument "-" with mode %rcan't open '%s': %scannot have multiple subparser argumentscannot merge actions - two groups are named %rdest= is required for options like %rexpected at least one argumentexpected at most one argumentexpected one argumentignored explicit argument %rinvalid %(type)s value: %(value)rinvalid choice: %(value)r (choose from %(choices)s)invalid conflict_resolution value: %rinvalid option string %(option)r: must start with a character %(prefix_chars)rmutually exclusive arguments must be optionalnot allowed with argument %sone of the arguments %s is requiredoptional argumentspositional argumentsshow this help message and exitthe following arguments are required: %sunexpected option string: %sunknown parser %(parser_name)r (choices: %(choices)s)unrecognized arguments: %susage: Project-Id-Version: sshoot 1.3.2 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 2017-10-21 14:43+0200 PO-Revision-Date: 2017-10-22 12:15+0200 Last-Translator: Alberto Donato Language: it_IT Language-Team: it_IT Plural-Forms: nplurals=2; plural=(n != 1) MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel 2.5.1 %(prog)s: erorre: %(message)s %r non è chiamabile'required' è un argomento non valido per posizionali__call__() non definitoopzione ambigua: %(option)s può corrispondere a %(matches)sargoment "-" con modo %rimpossibile aprire '%s': %simpossibile avere argomenti multipli per un subparserimpossibile unire le azioni - due gruppi con nome %rdest= è obbligatorio per opzioni come %ratteso al massimo un argomentoatteso almeno un argomentoun argomento attesoargomento esplicito %r ignoratovalore di %(type)s invalido: %(value)rscelta invalida: %(value)r (scelta tra %(choices)s)valore invalido per conflict_resolution: %rstringa di opzione %(option)r invalida: deve inziare con un caratter %(prefix_chars)rargomenti mutuamente esclusivi devono esser opzionalinon permesso con argomento %suno degli argomenti %s è richiestoargomenti opzionaliargomenti posizionalimostra questo messaggio di aiuto ed escii seguenti argomenti sono necessari: %sstringa di opzione non attesa: %sparser %(parser_name)r sconosciuto (scelte: %(choices)s)argomento sconosciuto: %sutilizzo: sshoot-1.4.2/sshoot/locale/it_IT/LC_MESSAGES/argparse.po000066400000000000000000000105651350053456200225660ustar00rootroot00000000000000# Italian (Italy) translation for argparse. # Copyright (C) 2017 # This file is distributed under the same license as the sshoot project. # Alberto Donato , 2017. # msgid "" msgstr "" "Project-Id-Version: sshoot 1.3.2\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2017-10-21 14:43+0200\n" "PO-Revision-Date: 2017-10-22 12:15+0200\n" "Last-Translator: Alberto Donato \n" "Language: it_IT\n" "Language-Team: it_IT \n" "Plural-Forms: nplurals=2; plural=(n != 1)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.5.1" #: /usr/lib/python3.6/argparse.py:304 msgid "usage: " msgstr "utilizzo: " #: /usr/lib/python3.6/argparse.py:835 msgid ".__call__() not defined" msgstr "__call__() non definito" #: /usr/lib/python3.6/argparse.py:1132 msgid "unknown parser %(parser_name)r (choices: %(choices)s)" msgstr "parser %(parser_name)r sconosciuto (scelte: %(choices)s)" #: /usr/lib/python3.6/argparse.py:1186 msgid "argument \"-\" with mode %r" msgstr "argoment \"-\" con modo %r" #: /usr/lib/python3.6/argparse.py:1194 msgid "can't open '%s': %s" msgstr "impossibile aprire '%s': %s" #: /usr/lib/python3.6/argparse.py:1398 msgid "cannot merge actions - two groups are named %r" msgstr "impossibile unire le azioni - due gruppi con nome %r" #: /usr/lib/python3.6/argparse.py:1436 msgid "'required' is an invalid argument for positionals" msgstr "'required' è un argomento non valido per posizionali" #: /usr/lib/python3.6/argparse.py:1458 msgid "invalid option string %(option)r: must start with a character %(prefix_chars)r" msgstr "stringa di opzione %(option)r invalida: deve inziare con un caratter %(prefix_chars)r" #: /usr/lib/python3.6/argparse.py:1478 msgid "dest= is required for options like %r" msgstr "dest= è obbligatorio per opzioni come %r" #: /usr/lib/python3.6/argparse.py:1495 msgid "invalid conflict_resolution value: %r" msgstr "valore invalido per conflict_resolution: %r" #: /usr/lib/python3.6/argparse.py:1579 msgid "mutually exclusive arguments must be optional" msgstr "argomenti mutuamente esclusivi devono esser opzionali" #: /usr/lib/python3.6/argparse.py:1642 msgid "positional arguments" msgstr "argomenti posizionali" #: /usr/lib/python3.6/argparse.py:1643 msgid "optional arguments" msgstr "argomenti opzionali" #: /usr/lib/python3.6/argparse.py:1658 msgid "show this help message and exit" msgstr "mostra questo messaggio di aiuto ed esci" #: /usr/lib/python3.6/argparse.py:1689 msgid "cannot have multiple subparser arguments" msgstr "impossibile avere argomenti multipli per un subparser" #: /usr/lib/python3.6/argparse.py:1741 msgid "unrecognized arguments: %s" msgstr "argomento sconosciuto: %s" #: /usr/lib/python3.6/argparse.py:1838 msgid "not allowed with argument %s" msgstr "non permesso con argomento %s" #: /usr/lib/python3.6/argparse.py:1884 /usr/lib/python3.6/argparse.py:1898 msgid "ignored explicit argument %r" msgstr "argomento esplicito %r ignorato" #: /usr/lib/python3.6/argparse.py:2005 msgid "the following arguments are required: %s" msgstr "i seguenti argomenti sono necessari: %s" #: /usr/lib/python3.6/argparse.py:2020 msgid "one of the arguments %s is required" msgstr "uno degli argomenti %s è richiesto" #: /usr/lib/python3.6/argparse.py:2063 msgid "expected one argument" msgstr "un argomento atteso" #: /usr/lib/python3.6/argparse.py:2064 msgid "expected at most one argument" msgstr "atteso almeno un argomento" #: /usr/lib/python3.6/argparse.py:2065 msgid "expected at least one argument" msgstr "atteso al massimo un argomento" #: /usr/lib/python3.6/argparse.py:2127 msgid "ambiguous option: %(option)s could match %(matches)s" msgstr "opzione ambigua: %(option)s può corrispondere a %(matches)s" #: /usr/lib/python3.6/argparse.py:2190 msgid "unexpected option string: %s" msgstr "stringa di opzione non attesa: %s" #: /usr/lib/python3.6/argparse.py:2294 msgid "%r is not callable" msgstr "%r non è chiamabile" #: /usr/lib/python3.6/argparse.py:2311 msgid "invalid %(type)s value: %(value)r" msgstr "valore di %(type)s invalido: %(value)r" #: /usr/lib/python3.6/argparse.py:2322 msgid "invalid choice: %(value)r (choose from %(choices)s)" msgstr "scelta invalida: %(value)r (scelta tra %(choices)s)" #: /usr/lib/python3.6/argparse.py:2398 msgid "" "%(prog)s: error: %(message)s\n" msgstr "%(prog)s: errore: %(message)s\n" sshoot-1.4.2/sshoot/locale/it_IT/LC_MESSAGES/sshoot.mo000066400000000000000000000076551350053456200223040ustar00rootroot000000000000002<= D O Ye u%?' ,Mh#   /3K3. .3#b$- IV)p#!($BR    0 *C "n ' E  ( - G #`        ( 76 Cn 6   (" ?K (  (  &Da *!$0> oACTIVEAuto hostsAuto netsDNS forwardExclude subnetsExtra optionsFailed to stop profile: {error}Invalid output format: {name}Manage multiple sshuttle VPN sessionsNOTICE: configuration tree moved from {old_path} to {new_path} NameProfile failed to start: {error}Profile is already runningProfile is not runningProfile name already in use: {name}Profile startedProfile stoppedRemote hostSTOPPEDSeed hostsStatusSubnetsUnknown profile: {name}action to performautomatically route additional nets from serverautomatically update /etc/hosts with hosts from VPNcomma-separated list of hosts to seed to auto-hostsconfiguration directory (default: %(default)s)define a new profiledelete an existing profileexclude subnets from VPN forwardextra options to pass to sshuttle command lineforward DNS queries through the VPNlist defined profileslisting format (default %(default)s)name of the profilename of the profile to queryname of the profile to removename of the profile to startname of the profile to stopprofile nameremote host to connect toreturn the sshuttle command for a profilereturn whether a profile is runningshow profile configurationstart a VPN session for a profilestop a running VPN session for a profilesubnets to route over the VPNverbose listingProject-Id-Version: sshoot 1.3.2 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 2017-10-22 12:19+0200 PO-Revision-Date: 2017-10-22 11:56+0200 Last-Translator: Alberto Donato Language: it_IT Language-Team: it_IT Plural-Forms: nplurals=2; plural=(n != 1) MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel 2.5.1 ATTIVOAuto hostsAuto netsInvia req. DNSSottoreti escluseOpzioni aggiuntiveDisattivazione del profilo fallita {error}Formato di output invalido: {name}Gestisci sessioni VPN sshuttle multipleNOTA: la configurazione è stata spostata da {old_path} a {new_path} NomeAttivazione del profilo fallita: {error}Il profilo è già attivoIl profilo non è attivoNome di profilo già in uso: {name}Profilo avviatoProfilo disattivatoHost remotoINATTIVOSpecifica hostStatoSottoretiProfilo sconosciuto: {name}azione da effettuareruota automaticamente le reti dal serveraggiorna automaticamente /etc/hosts con hosts dalla VPNlista (separata da virgole) degli host da specificare ad auto-hostsdirectory di configurazione (predefinita: %(default)s)definisci un nuovo profilocancella un profilo esistenteescludi sottoreti dall'invio tramite VPNopzioni aggiuntive da passare alla linea di comando di sshuttleinvia le richieste DNS attraverso la VPNlista profili definitiformato lista (predefinito: %(default)s)nomde del profilonome del profilo da interrogarenome del profilo da rimuoverenome del profilo da attivarenome del profilo da disattivarenome profilohost remoto a cui connettersiritorna il comando sshuttle per un profiloritorna se un profilo è attivovisualizza configurazione profiloavvia la sessione VPN per un profilodisattiva una sessione VPN attiva per un profilosottoreti da ruotare tramite VPNvisualizza maggiori dettaglisshoot-1.4.2/sshoot/locale/it_IT/LC_MESSAGES/sshoot.po000066400000000000000000000126121350053456200222740ustar00rootroot00000000000000# Italian (Italy) translations for sshoot. # Copyright (C) 2017 # This file is distributed under the same license as the sshoot project. # Alberto Donato , 2017. # msgid "" msgstr "" "Project-Id-Version: sshoot 1.3.2\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2017-10-22 12:19+0200\n" "PO-Revision-Date: 2017-10-22 11:56+0200\n" "Last-Translator: Alberto Donato \n" "Language: it_IT\n" "Language-Team: it_IT \n" "Plural-Forms: nplurals=2; plural=(n != 1)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.4.0\n" #: sshoot/listing.py:18 msgid "Remote host" msgstr "Host remoto" #: sshoot/listing.py:19 msgid "Subnets" msgstr "Sottoreti" #: sshoot/listing.py:20 msgid "Auto hosts" msgstr "Auto hosts" #: sshoot/listing.py:21 msgid "Auto nets" msgstr "Auto nets" #: sshoot/listing.py:22 msgid "DNS forward" msgstr "Invia req. DNS" #: sshoot/listing.py:23 msgid "Exclude subnets" msgstr "Sottoreti escluse" #: sshoot/listing.py:24 msgid "Seed hosts" msgstr "Specifica host" #: sshoot/listing.py:25 msgid "Extra options" msgstr "Opzioni aggiuntive" #: sshoot/listing.py:27 msgid "Name" msgstr "Nome" #: sshoot/listing.py:28 msgid "Status" msgstr "Stato" #: sshoot/listing.py:34 msgid "Invalid output format: {name}" msgstr "Formato di output invalido: {name}" #: sshoot/listing.py:134 msgid "ACTIVE" msgstr "ATTIVO" #: sshoot/listing.py:134 msgid "STOPPED" msgstr "INATTIVO" #: sshoot/main.py:65 msgid "Profile started" msgstr "Profilo avviato" #: sshoot/main.py:70 msgid "Profile stopped" msgstr "Profilo disattivato" #: sshoot/main.py:87 msgid "Manage multiple sshuttle VPN sessions" msgstr "Gestisci sessioni VPN sshuttle multiple" #: sshoot/main.py:93 #, python-format msgid "configuration directory (default: %(default)s)" msgstr "directory di configurazione (predefinita: %(default)s)" #: sshoot/main.py:95 msgid "action to perform" msgstr "azione da effettuare" #: sshoot/main.py:100 msgid "list defined profiles" msgstr "lista profili definiti" #: sshoot/main.py:103 msgid "verbose listing" msgstr "visualizza maggiori dettagli" #: sshoot/main.py:107 #, python-format msgid "listing format (default %(default)s)" msgstr "formato lista (predefinito: %(default)s)" #: sshoot/main.py:111 msgid "show profile configuration" msgstr "visualizza configurazione profilo" #: sshoot/main.py:113 sshoot/main.py:119 msgid "profile name" msgstr "nome profilo" #: sshoot/main.py:118 msgid "define a new profile" msgstr "definisci un nuovo profilo" #: sshoot/main.py:121 msgid "subnets to route over the VPN" msgstr "sottoreti da ruotare tramite VPN" #: sshoot/main.py:123 msgid "remote host to connect to" msgstr "host remoto a cui connettersi" #: sshoot/main.py:126 msgid "automatically update /etc/hosts with hosts from VPN" msgstr "aggiorna automaticamente /etc/hosts con hosts dalla VPN" #: sshoot/main.py:129 msgid "automatically route additional nets from server" msgstr "ruota automaticamente le reti dal server" #: sshoot/main.py:132 msgid "forward DNS queries through the VPN" msgstr "invia le richieste DNS attraverso la VPN" #: sshoot/main.py:135 msgid "exclude subnets from VPN forward" msgstr "escludi sottoreti dall'invio tramite VPN" #: sshoot/main.py:138 msgid "comma-separated list of hosts to seed to auto-hosts" msgstr "lista (separata da virgole) degli host da specificare ad auto-hosts" #: sshoot/main.py:141 msgid "extra options to pass to sshuttle command line" msgstr "opzioni aggiuntive da passare alla linea di comando di sshuttle" #: sshoot/main.py:145 msgid "delete an existing profile" msgstr "cancella un profilo esistente" #: sshoot/main.py:148 msgid "name of the profile to remove" msgstr "nome del profilo da rimuovere" #: sshoot/main.py:153 msgid "start a VPN session for a profile" msgstr "avvia la sessione VPN per un profilo" #: sshoot/main.py:156 msgid "name of the profile to start" msgstr "nome del profilo da attivare" #: sshoot/main.py:164 msgid "stop a running VPN session for a profile" msgstr "disattiva una sessione VPN attiva per un profilo" #: sshoot/main.py:167 msgid "name of the profile to stop" msgstr "nome del profilo da disattivare" #: sshoot/main.py:172 msgid "return whether a profile is running" msgstr "ritorna se un profilo è attivo" #: sshoot/main.py:175 msgid "name of the profile to query" msgstr "nome del profilo da interrogare" #: sshoot/main.py:180 msgid "return the sshuttle command for a profile" msgstr "ritorna il comando sshuttle per un profilo" #: sshoot/main.py:183 msgid "name of the profile" msgstr "nomde del profilo" #: sshoot/main.py:202 msgid "NOTICE: configuration tree moved from {old_path} to {new_path}\n" msgstr "NOTA: la configurazione è stata spostata da {old_path} a {new_path}\n" #: sshoot/manager.py:54 msgid "Profile name already in use: {name}" msgstr "Nome di profilo già in uso: {name}" #: sshoot/manager.py:66 sshoot/manager.py:80 msgid "Unknown profile: {name}" msgstr "Profilo sconosciuto: {name}" #: sshoot/manager.py:85 msgid "Profile is already running" msgstr "Il profilo è già attivo" #: sshoot/manager.py:88 msgid "Profile failed to start: {error}" msgstr "Attivazione del profilo fallita: {error}" #: sshoot/manager.py:108 msgid "Profile is not running" msgstr "Il profilo non è attivo" #: sshoot/manager.py:115 msgid "Failed to stop profile: {error}" msgstr "Disattivazione del profilo fallita {error}" sshoot-1.4.2/sshoot/locale/sshoot.pot000066400000000000000000000076631350053456200176750ustar00rootroot00000000000000# Translations template for sshoot. # Copyright (C) 2017 ORGANIZATION # This file is distributed under the same license as the sshoot project. # FIRST AUTHOR , 2017. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: sshoot 1.4.0\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2017-10-22 12:19+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.5.1\n" #: sshoot/listing.py:18 msgid "Remote host" msgstr "" #: sshoot/listing.py:19 msgid "Subnets" msgstr "" #: sshoot/listing.py:20 msgid "Auto hosts" msgstr "" #: sshoot/listing.py:21 msgid "Auto nets" msgstr "" #: sshoot/listing.py:22 msgid "DNS forward" msgstr "" #: sshoot/listing.py:23 msgid "Exclude subnets" msgstr "" #: sshoot/listing.py:24 msgid "Seed hosts" msgstr "" #: sshoot/listing.py:25 msgid "Extra options" msgstr "" #: sshoot/listing.py:27 msgid "Name" msgstr "" #: sshoot/listing.py:28 msgid "Status" msgstr "" #: sshoot/listing.py:34 msgid "Invalid output format: {name}" msgstr "" #: sshoot/listing.py:134 msgid "ACTIVE" msgstr "" #: sshoot/listing.py:134 msgid "STOPPED" msgstr "" #: sshoot/main.py:65 msgid "Profile started" msgstr "" #: sshoot/main.py:70 msgid "Profile stopped" msgstr "" #: sshoot/main.py:87 msgid "Manage multiple sshuttle VPN sessions" msgstr "" #: sshoot/main.py:93 #, python-format msgid "configuration directory (default: %(default)s)" msgstr "" #: sshoot/main.py:95 msgid "action to perform" msgstr "" #: sshoot/main.py:100 msgid "list defined profiles" msgstr "" #: sshoot/main.py:103 msgid "verbose listing" msgstr "" #: sshoot/main.py:107 #, python-format msgid "listing format (default %(default)s)" msgstr "" #: sshoot/main.py:111 msgid "show profile configuration" msgstr "" #: sshoot/main.py:113 sshoot/main.py:119 msgid "profile name" msgstr "" #: sshoot/main.py:118 msgid "define a new profile" msgstr "" #: sshoot/main.py:121 msgid "subnets to route over the VPN" msgstr "" #: sshoot/main.py:123 msgid "remote host to connect to" msgstr "" #: sshoot/main.py:126 msgid "automatically update /etc/hosts with hosts from VPN" msgstr "" #: sshoot/main.py:129 msgid "automatically route additional nets from server" msgstr "" #: sshoot/main.py:132 msgid "forward DNS queries through the VPN" msgstr "" #: sshoot/main.py:135 msgid "exclude subnets from VPN forward" msgstr "" #: sshoot/main.py:138 msgid "comma-separated list of hosts to seed to auto-hosts" msgstr "" #: sshoot/main.py:141 msgid "extra options to pass to sshuttle command line" msgstr "" #: sshoot/main.py:145 msgid "delete an existing profile" msgstr "" #: sshoot/main.py:148 msgid "name of the profile to remove" msgstr "" #: sshoot/main.py:153 msgid "start a VPN session for a profile" msgstr "" #: sshoot/main.py:156 msgid "name of the profile to start" msgstr "" #: sshoot/main.py:164 msgid "stop a running VPN session for a profile" msgstr "" #: sshoot/main.py:167 msgid "name of the profile to stop" msgstr "" #: sshoot/main.py:172 msgid "return whether a profile is running" msgstr "" #: sshoot/main.py:175 msgid "name of the profile to query" msgstr "" #: sshoot/main.py:180 msgid "return the sshuttle command for a profile" msgstr "" #: sshoot/main.py:183 msgid "name of the profile" msgstr "" #: sshoot/main.py:202 msgid "NOTICE: configuration tree moved from {old_path} to {new_path}\n" msgstr "" #: sshoot/manager.py:54 msgid "Profile name already in use: {name}" msgstr "" #: sshoot/manager.py:66 sshoot/manager.py:80 msgid "Unknown profile: {name}" msgstr "" #: sshoot/manager.py:85 msgid "Profile is already running" msgstr "" #: sshoot/manager.py:88 msgid "Profile failed to start: {error}" msgstr "" #: sshoot/manager.py:108 msgid "Profile is not running" msgstr "" #: sshoot/manager.py:115 msgid "Failed to stop profile: {error}" msgstr "" sshoot-1.4.2/sshoot/main.py000066400000000000000000000201571350053456200156620ustar00rootroot00000000000000"""Command-line interface to handle sshuttle VPN sessions.""" from argparse import ArgumentParser from functools import partial import os import shutil import sys from argcomplete import autocomplete from . import __version__ from .autocomplete import ( complete_argument, profile_completer, ) from .i18n import _ from .listing import ( profile_details, ProfileListing, ) from .manager import ( DEFAULT_CONFIG_PATH, Manager, ManagerProfileError, ) class Sshoot: """Manage multiple sshuttle VPN sessions.""" def __call__(self): args = self._get_parser().parse_args() # backwards-compatible config lookup self._check_update_config_path(args.config) try: manager = Manager(config_path=args.config) manager.load_config() except IOError as error: self._exit(message=str(error), code=3) action = args.action.replace('-', '_') method = getattr(self, 'action_' + action) try: return method(manager, args) except ManagerProfileError as error: self._exit(message=str(error), code=2) def action_list(self, manager, args): """Print out the list of profiles as a table.""" listing = ProfileListing(manager) print(listing.get_output(args.format, verbose=args.verbose), end='') def action_show(self, manager, args): """Show details on a profile.""" print(profile_details(manager, args.name)) def action_create(self, manager, args): """Create a new profile.""" manager.create_profile(args.name, args.__dict__) def action_delete(self, manager, args): """Delete profile with the given name.""" manager.remove_profile(args.name) def action_start(self, manager, args): """Start sshuttle for the specified profile.""" manager.start_profile(args.name, extra_args=args.args) print(_('Profile started')) def action_stop(self, manager, args): """Stop sshuttle for the specified profile.""" manager.stop_profile(args.name) print(_('Profile stopped')) def action_is_running(self, manager, args): """Return whether the specified profile is running.""" # raise an error if profile is unknown manager.get_profile(args.name) retval = 0 if manager.is_running(args.name) else 1 self._exit(code=retval) def action_get_command(self, manager, args): """Print the sshuttle command for the specified profile.""" cmdline = manager.get_cmdline(args.name) print(' '.join(cmdline)) def _get_parser(self): """Return a configured argparse.ArgumentParse instance.""" parser = ArgumentParser( description=_('Manage multiple sshuttle VPN sessions')) parser.add_argument( '-V', '--version', action='version', version='%(prog)s {}'.format(__version__)) parser.add_argument( '-C', '--config', default=DEFAULT_CONFIG_PATH, help=_('configuration directory (default: %(default)s)')) subparsers = parser.add_subparsers( metavar='ACTION', dest='action', help=_('action to perform')) subparsers.required = True # List profiles list_parser = subparsers.add_parser( 'list', help=_('list defined profiles')) list_parser.add_argument( '-v', '--verbose', action='store_true', help=_('verbose listing')) list_parser.add_argument( '-f', '--format', choices=ProfileListing.supported_formats(), default='table', help=_('listing format (default %(default)s)')) # Show profile show_parser = subparsers.add_parser( 'show', help=_('show profile configuration')) complete_argument( show_parser.add_argument('name', help=_('profile name')), profile_completer) # Add profile create_parser = subparsers.add_parser( 'create', help=_('define a new profile')) create_parser.add_argument('name', help=_('profile name')) create_parser.add_argument( 'subnets', nargs='+', help=_('subnets to route over the VPN')) create_parser.add_argument( '-r', '--remote', help=_('remote host to connect to')) create_parser.add_argument( '-H', '--auto-hosts', action='store_true', help=_('automatically update /etc/hosts with hosts from VPN')) create_parser.add_argument( '-N', '--auto-nets', action='store_true', help=_('automatically route additional nets from server')) create_parser.add_argument( '-d', '--dns', action='store_true', help=_('forward DNS queries through the VPN')) create_parser.add_argument( '-x', '--exclude-subnets', nargs='+', help=_('exclude subnets from VPN forward')) create_parser.add_argument( '-S', '--seed-hosts', nargs='+', help=_('comma-separated list of hosts to seed to auto-hosts')) create_parser.add_argument( '--extra-opts', type=str.split, help=_('extra options to pass to sshuttle command line')) # Remove profile delete_parser = subparsers.add_parser( 'delete', help=_('delete an existing profile')) complete_argument( delete_parser.add_argument( 'name', help=_('name of the profile to remove')), profile_completer) # Start profile start_parser = subparsers.add_parser( 'start', help=_('start a VPN session for a profile')) complete_argument( start_parser.add_argument( 'name', help=_('name of the profile to start')), partial(profile_completer, running=False)) start_parser.add_argument( 'args', nargs='*', help=('additional arguments passed to sshuttle command line.')) # Stop profile stop_parser = subparsers.add_parser( 'stop', help=_('stop a running VPN session for a profile')) complete_argument( stop_parser.add_argument( 'name', help=_('name of the profile to stop')), partial(profile_completer, running=True)) # Return whether profile is running is_running_parser = subparsers.add_parser( 'is-running', help=_('return whether a profile is running')) complete_argument( is_running_parser.add_argument( 'name', help=_('name of the profile to query')), profile_completer) # Get profile command get_command_parser = subparsers.add_parser( 'get-command', help=_('return the sshuttle command for a profile')) complete_argument( get_command_parser.add_argument( 'name', help=_('name of the profile')), profile_completer) # Setup autocompletion autocomplete(parser) return parser def _check_update_config_path(self, config): """Move config to the new path if the old one is found.""" old_config_path = os.path.expanduser(os.path.join('~', '.sshoot')) if config != DEFAULT_CONFIG_PATH: return need_config_path_update = ( os.path.exists(old_config_path) and not os.path.exists(DEFAULT_CONFIG_PATH)) if need_config_path_update: shutil.move(old_config_path, DEFAULT_CONFIG_PATH) sys.stderr.write( _( 'NOTICE: configuration tree moved from {old_path} to ' '{new_path}\n').format( old_path=old_config_path, new_path=DEFAULT_CONFIG_PATH)) def _exit(self, message=None, code=1): """Terminate with the specified error and code .""" if message: sys.stderr.write('{}\n'.format(message)) sys.exit(code) sshoot = Sshoot() sshoot-1.4.2/sshoot/manager.py000066400000000000000000000116201350053456200163430ustar00rootroot00000000000000"""Handle sshuttle sessions.""" from getpass import getuser import os from pathlib import Path from signal import SIGTERM from subprocess import ( PIPE, Popen, ) from tempfile import gettempdir from xdg.BaseDirectory import xdg_config_home from .config import Config from .i18n import _ from .profile import ( Profile, ProfileError, ) DEFAULT_CONFIG_PATH = Path(xdg_config_home) / 'sshoot' class ManagerProfileError(Exception): """Profile operation failed.""" class Manager: """Profile manager.""" def __init__(self, config_path=None, rundir=None): self.config_path = ( Path(config_path) if config_path else DEFAULT_CONFIG_PATH) self.rundir = Path(rundir) if rundir else get_rundir('sshoot') self.sessions_path = self.rundir / 'sessions' self._config = Config(self.config_path) def load_config(self): """Load configuration from file.""" self.config_path.mkdir(parents=True, exist_ok=True) self.sessions_path.mkdir(parents=True, exist_ok=True) self._config.load() def create_profile(self, name, details): """Create a profile with provided details.""" try: profile = Profile.from_dict(details) self._config.add_profile(name, profile) except KeyError: raise ManagerProfileError( _('Profile name already in use: {name}').format(name=name)) except ProfileError as error: raise ManagerProfileError(str(error)) self._config.save() def remove_profile(self, name): """Remove profile with given name.""" try: self._config.remove_profile(name) except KeyError: raise ManagerProfileError( _('Unknown profile: {name}').format(name=name)) self._config.save() def get_profiles(self): """Return profiles defined in config.""" return self._config.profiles def get_profile(self, name): """Return profile with given name.""" try: return self._config.profiles[name] except KeyError: raise ManagerProfileError( _('Unknown profile: {name}').format(name=name)) def start_profile(self, name, extra_args=None): """Start profile with given name.""" if self.is_running(name): raise ManagerProfileError(_('Profile is already running')) cmdline = self.get_cmdline(name, extra_args=extra_args) message = _('Profile failed to start: {error}') try: process = Popen(cmdline, stderr=PIPE) # Wait until process is started (it daemonizes) process.wait() except OSError as err: # To catch file not found errors raise ManagerProfileError(message.format(error=str(err))) if process.returncode != 0: error = process.stderr.read().decode() process.stderr.close() raise ManagerProfileError(message.format(error=error)) process.stderr.close() def stop_profile(self, name): """Stop profile with given name.""" self.get_profile(name) if not self.is_running(name): raise ManagerProfileError(_('Profile is not running')) try: pid = int(self._get_pidfile(name).read_text()) os.kill(pid, SIGTERM) except (IOError, OSError) as error: raise ManagerProfileError( _('Failed to stop profile: {error}').format(error=error)) def is_running(self, name): """Return whether the specified profile is running.""" pidfile = self._get_pidfile(name) try: pid = int(pidfile.read_text()) except Exception: # If anything fails, a valid PID can't be found, so the profile is # not running return False try: os.kill(pid, 0) except OSError: # Delete stale pidfile pidfile.unlink() return False return True def get_cmdline(self, name, extra_args=None): """Return the command line for the specified profile.""" profile = self.get_profile(name) executable = self._get_executable() extra_opts = ['--daemon', '--pidfile', str(self._get_pidfile(name))] if extra_args: extra_opts.extend(extra_args) return profile.cmdline(executable=executable, extra_opts=extra_opts) def _get_pidfile(self, name): """Return the path of the pidfile for the specified profile.""" return self.sessions_path / '{}.pid'.format(name) def _get_executable(self): """Return the shuttle executable from the config.""" return self._config.config.get('executable', 'sshuttle') def get_rundir(prefix): """Return the directory holding runtime data.""" return Path(gettempdir()) / '{prefix}-{username}'.format( prefix=prefix, username=getuser()) sshoot-1.4.2/sshoot/profile.py000066400000000000000000000045341350053456200163770ustar00rootroot00000000000000"""A sshuttle VPN profile.""" class ProfileError(Exception): """Profile configuration is not correct.""" def __init__(self): super().__init__('Subnets must be specified') class Profile: """Hold information about a sshuttle profile.""" _config_attrs = ( 'remote', 'subnets', 'auto_hosts', 'auto_nets', 'dns', 'exclude_subnets', 'seed_hosts', 'extra_opts') remote = None subnets = None auto_hosts = False auto_nets = False dns = False exclude_subnets = None seed_hosts = None extra_opts = None def __init__(self, subnets): self.subnets = subnets @classmethod def from_dict(cls, config): """Create a profile from a dict holding config attributes.""" config = config.copy() # shallow, only first-level keys are changed try: subnets = config.pop('subnets') except KeyError: raise ProfileError() profile = Profile(subnets=subnets) for attr in cls._config_attrs: value = config.get(attr) if value is not None: setattr(profile, attr, value) return profile def cmdline(self, executable='sshuttle', extra_opts=None): """Return a sshuttle cmdline based on the profile.""" cmd = [executable] + self.subnets if self.remote: cmd.append('--remote={}'.format(self.remote)) if self.auto_hosts: cmd.append('--auto-hosts') if self.auto_nets: cmd.append('--auto-nets') if self.dns: cmd.append('--dns') if self.exclude_subnets: cmd.extend( '--exclude={}'.format(net) for net in self.exclude_subnets) if self.seed_hosts: cmd.append('--seed-hosts={}'.format(','.join(self.seed_hosts))) if self.extra_opts: cmd.extend(self.extra_opts) if extra_opts: cmd.extend(extra_opts) return cmd def config(self): """Return profile configuration as a dict.""" conf = {} for attr in self._config_attrs: value = getattr(self, attr) if value: conf[attr] = value return dict(conf) def __eq__(self, other): return all( getattr(self, attr) == getattr(other, attr) for attr in self._config_attrs) sshoot-1.4.2/sshoot/tests/000077500000000000000000000000001350053456200155215ustar00rootroot00000000000000sshoot-1.4.2/sshoot/tests/__init__.py000066400000000000000000000000001350053456200176200ustar00rootroot00000000000000sshoot-1.4.2/sshoot/tests/test_autocomplete.py000066400000000000000000000033411350053456200216340ustar00rootroot00000000000000from argparse import Namespace import pytest from ..autocomplete import ( complete_argument, profile_completer, ) class TestCompleteArgument: def test_complete(self): """complete_arguments attaches a completer to the argument.""" class FakeArgument: completer = None fake_argument = FakeArgument() fake_completer = object() complete_argument(fake_argument, fake_completer) assert fake_argument.completer is fake_completer @pytest.fixture def profiles(profile_manager): yield [ profile_manager.create_profile('foo', {'subnets': ['10.1.0.0/16']}), profile_manager.create_profile('bar', {'subnets': ['10.2.0.0/16']}), profile_manager.create_profile('baz', {'subnets': ['10.3.0.0/16']}) ] @pytest.fixture def parsed_args(config_dir): yield Namespace(config=config_dir) @pytest.mark.usefixtures('profiles') class TestProfileCompleter: def test_complete_filter_prefix(self, parsed_args): """The autocomplete function returns names that match the prefix.""" assert list(profile_completer('b', parsed_args)) == ['bar', 'baz'] @pytest.mark.parametrize( 'running,completions', [(True, ['baz', 'foo']), (False, ['bar'])]) def test_complete_filter_running( self, running, completions, mocker, profile_manager, parsed_args): """The autocomplete function returns names based on running status.""" mock_manager = mocker.patch('sshoot.autocomplete.Manager') mock_manager.return_value = profile_manager profile_manager.is_running = lambda name: name != 'bar' returned = list(profile_completer('', parsed_args, running=running)) assert returned == completions sshoot-1.4.2/sshoot/tests/test_config.py000066400000000000000000000110521350053456200203760ustar00rootroot00000000000000from io import StringIO from textwrap import dedent import pytest import yaml from ..config import yaml_dump from ..profile import Profile class TestYamlDump: def test_dump_to_string(self): """The method returns YAML data as a string by default.""" data = {'foo': 'bar', 'baz': [1, 2]} result = yaml_dump(data) assert yaml.safe_load(stream=StringIO(result)) == data def test_dump_to_file(self): """The method dumps YAML data to the specified file.""" data = {'foo': 'bar', 'baz': [1, 2]} fh = StringIO() result = yaml_dump(data, fh=fh) fh.seek(0) assert result is None assert yaml.safe_load(stream=fh) == data class TestConfig: def test_add_profile(self, config): """Profiles can be added to the config.""" profiles = { 'profile1': Profile(['10.0.0.0/24']), 'profile2': Profile(['192.168.0.0/16']) } for name, profile in profiles.items(): config.add_profile(name, profile) assert config.profiles == profiles def test_add_profile_name_present(self, config): """An exception is raised if the profile name is already used.""" config.add_profile('profile', Profile(['10.0.0.0/24'])) with pytest.raises(KeyError): config.add_profile('profile', Profile(['192.168.0.0/16'])) def test_remove_profile(self, config): """Profiles can be removed to the config.""" profiles = { 'profile1': Profile(['10.0.0.0/24']), 'profile2': Profile(['192.168.0.0/16']) } for name, profile in profiles.items(): config.add_profile(name, profile) config.remove_profile('profile1') assert list(config.profiles), ['profile2'] def test_remove_profile_not_present(self, config): """An exception is raised if the profile name is not known.""" with pytest.raises(KeyError): config.remove_profile('profile') def test_load_from_file(self, config, profiles_file): """The config is loaded from file.""" profiles = {'profile': {'subnets': ['10.0.0.0/24'], 'auto-nets': True}} profiles_file.write_text(yaml.dump(profiles)) config.load() profile = config.profiles['profile'] assert profile.subnets == ['10.0.0.0/24'] assert profile.auto_nets def test_load_missing_file(self, config): """If no config files are found, config is empty.""" config.load() assert config.profiles == {} assert config.config == {} def test_load_config_options(self, config, config_file): """Only known config options are loaded from config file.""" config_data = {'executable': '/usr/bin/shuttle', 'other-conf': 'no'} config_file.write_text(yaml.dump(config_data)) config.load() assert config.config == {'executable': '/usr/bin/shuttle'} def test_load_profiles(self, config, profiles_file): """The 'profiles' config field is loaded from the config file.""" profiles = { 'profile1': { 'subnets': ['10.0.0.0/24'] }, 'profile2': { 'subnets': ['192.168.0.0/16'] } } profiles_file.write_text(yaml.dump(profiles)) config.load() expected = { name: Profile.from_dict(config) for name, config in profiles.items() } assert config.profiles == expected def test_save_profiles(self, config, profiles_file): """Profiles are saved to file.""" profiles = { 'profile1': { 'subnets': ['10.0.0.0/24'], 'remote': 'hostname1' }, 'profile2': { 'subnets': ['192.168.0.0/16'], 'remote': 'hostname2' } } config.load() for name, conf in profiles.items(): config.add_profile(name, Profile.from_dict(conf)) config.save() config = yaml.safe_load(profiles_file.read_text()) assert config == profiles def test_save_from_file(self, config, profiles_file): """The config is saved to file.""" conf = {'subnets': ['10.0.0.0/24'], 'auto_nets': True} config.add_profile('profile', Profile.from_dict(conf)) config.save() config = dedent( '''\ profile: auto-nets: true subnets: - 10.0.0.0/24 ''') content = profiles_file.read_text() assert content == config sshoot-1.4.2/sshoot/tests/test_listing.py000066400000000000000000000125261350053456200206110ustar00rootroot00000000000000import csv from io import StringIO import json import pytest import yaml from ..listing import ( InvalidFormat, profile_details, ProfileListing, ) @pytest.fixture def active_profiles(profile_manager): active_profiles = [] profile_manager.is_running = lambda name: name in active_profiles yield active_profiles class TestProfileListing: def test_supported_formats(self): """supported_formats returns a list with supported formats.""" assert ProfileListing.supported_formats() == [ 'csv', 'json', 'table', 'yaml' ] def test_get_output_unsupported_format(self, profile_manager): """get_output raises an error if an unsupported format is passed.""" with pytest.raises(InvalidFormat): ProfileListing(profile_manager).get_output('unknown') def test_get_output_table(self, profile_manager, active_profiles): """Profiles can be listed as a table.""" profile_manager.create_profile( 'profile1', {'subnets': ['10.0.0.0/24']}) profile_manager.create_profile( 'profile2', {'subnets': ['192.168.0.0/16']}) active_profiles.append('profile2') output = ProfileListing(profile_manager).get_output('table') assert ' profile1 10.0.0.0/24' in output assert '* profile2 192.168.0.0/16' in output def test_get_output_table_verbose(self, profile_manager, active_profiles): """Tabular output can be verbose.""" profile_manager.create_profile( 'profile1', { 'subnets': ['10.0.0.0/24'], 'auto_hosts': True }) active_profiles.append('profile2') output = ProfileListing(profile_manager).get_output( 'table', verbose=True) assert ( 'Name Remote host Subnets Auto hosts Auto nets' ' DNS forward Exclude subnets Seed hosts Extra options' in output) assert ( 'profile1 10.0.0.0/24 True False False' in output) def test_get_output_csv(self, profile_manager, active_profiles): """Profiles can be listed as CSV.""" profile_manager.create_profile( 'profile1', {'subnets': ['10.0.0.0/24']}) profile_manager.create_profile( 'profile2', {'subnets': ['192.168.0.0/16']}) active_profiles.append('profile2') output = ProfileListing(profile_manager).get_output('csv') reader = csv.reader(StringIO(output)) assert sorted(reader) == [ [ 'Name', 'Status', 'Remote host', 'Subnets', 'Auto hosts', 'Auto nets', 'DNS forward', 'Exclude subnets', 'Seed hosts', 'Extra options' ], [ 'profile1', 'STOPPED', '', "['10.0.0.0/24']", 'False', 'False', 'False', '', '', '' ], [ 'profile2', 'ACTIVE', '', "['192.168.0.0/16']", 'False', 'False', 'False', '', '', '' ] ] def test_get_output_json(self, profile_manager, active_profiles): """Profiles can be listed as JSON.""" profile_manager.create_profile( 'profile1', {'subnets': ['10.0.0.0/24']}) profile_manager.create_profile( 'profile2', { 'subnets': ['192.168.0.0/16'], 'auto_hosts': True }) active_profiles.append('profile2') output = ProfileListing(profile_manager).get_output('json') data = json.loads(output) assert data == { 'profile1': { 'subnets': ['10.0.0.0/24'] }, 'profile2': { 'subnets': ['192.168.0.0/16'], 'auto_hosts': True } } def test_get_output_yaml(self, profile_manager, active_profiles): """Profiles can be listed as YAML.""" profile_manager.create_profile( 'profile1', {'subnets': ['10.0.0.0/24']}) profile_manager.create_profile( 'profile2', { 'subnets': ['192.168.0.0/16'], 'auto_hosts': True }) active_profiles.append('profile2') output = ProfileListing(profile_manager).get_output('yaml') data = yaml.safe_load(output) assert data == { 'profile1': { 'subnets': ['10.0.0.0/24'] }, 'profile2': { 'subnets': ['192.168.0.0/16'], 'auto_hosts': True } } class TestProfileDetails: def test_details(self, profile_manager): """profile_details returns a string with profile details.""" profile_manager.create_profile('profile', {'subnets': ['10.0.0.0/24']}) output = profile_details(profile_manager, 'profile') assert 'Name: profile' in output assert 'Subnets: 10.0.0.0/24' in output assert 'Status: STOPPED' in output def test_active(self, profile_manager, active_profiles): """profile_details shows if the profile is active.""" profile_manager.create_profile('profile', {'subnets': ['10.0.0.0/24']}) active_profiles.append('profile') output = profile_details(profile_manager, 'profile') assert 'Status: ACTIVE' in output sshoot-1.4.2/sshoot/tests/test_manager.py000066400000000000000000000255661350053456200205620ustar00rootroot00000000000000from getpass import getuser import os from pathlib import Path from tempfile import gettempdir import pytest import yaml from ..manager import ( DEFAULT_CONFIG_PATH, get_rundir, Manager, ManagerProfileError, ) from ..profile import Profile def fake_executable(base_path, exit_code): """Create a fake executable logging command line parameters.""" executable = Path(base_path) / 'executable' executable.write_text( ( '#!/bin/sh\n' 'echo $@ > {}/cmdline\n' 'echo -n stderr message >&2\n' 'exit {}\n').format(str(base_path), exit_code)) executable.chmod(0o755) return executable @pytest.fixture def bin_succeed(tmpdir): yield fake_executable(tmpdir, 0) @pytest.fixture def bin_fail(tmpdir): yield fake_executable(tmpdir, 1) @pytest.fixture def profile(profile_manager): yield profile_manager.create_profile( 'profile', {'subnets': ['10.0.0.0/24']}) @pytest.fixture def pid_file(profile, sessions_dir): yield sessions_dir / 'profile.pid' class TestManager: def test_default_paths(self): """A default config path is set if not specified.""" assert Manager().config_path == DEFAULT_CONFIG_PATH def test_paths(self, profile_manager, config_dir, sessions_dir): """The config and sessions are set in the Manager.""" assert profile_manager.config_path == config_dir assert profile_manager.sessions_path == sessions_dir def test_load_config_create_dirs( self, profile_manager, config_dir, sessions_dir): """Manager.load_config creates config directories.""" config_dir.rmdir() sessions_dir.rmdir() profile_manager.load_config() assert config_dir.is_dir() assert sessions_dir.is_dir() def test_load_profiles(self, profile_manager, profiles_file): """Manager.load_config loads the profiles.""" profiles = {'profile': {'subnets': ['10.0.0.0/16']}} profiles_file.write_text(yaml.dump(profiles)) profile_manager.load_config() assert list(profile_manager.get_profiles()) == ['profile'] def test_create_profile(self, profile_manager, profiles_file): """Manager.create_profile adds a profile with specified details.""" profile_manager.create_profile('profile', {'subnets': ['10.0.0.0/24']}) profiles = yaml.safe_load(profiles_file.read_text()) assert profiles == {'profile': {'subnets': ['10.0.0.0/24']}} def test_create_profile_in_use(self, profile_manager): """Manager.create_profile raises an error if profile name is in use.""" profile_manager.create_profile('profile', {'subnets': ['10.0.0.0/24']}) with pytest.raises(ManagerProfileError): profile_manager.create_profile( 'profile', {'subnets': ['10.0.0.0/16']}) def test_create_profile_invalid_details(self, profile_manager): """Manager.create_profile raises an error on invalid profile info.""" with pytest.raises(ManagerProfileError): profile_manager.create_profile('profile', {'wrong': 'data'}) def test_remove_profile(self, profile_manager, profile, profiles_file): """Manager.remove_profile removes the specified profile.""" profile_manager.remove_profile('profile') config = yaml.safe_load(profiles_file.read_text()) assert config == {} def test_remove_profile_unknown(self, profile_manager): """Manager.remove_profile raises an error if name is unknown.""" with pytest.raises(ManagerProfileError): profile_manager.remove_profile('unknown') def test_get_profiles(self, profile_manager): """Manager.get_profiles returns defined profiles.""" profile_manager.create_profile( 'profile1', {'subnets': ['10.0.0.0/24']}) profile_manager.create_profile( 'profile2', {'subnets': ['192.168.0.0/16']}) profile_manager.get_profiles() == { 'profile1': Profile.from_dict({'subnets': ['10.0.0.0/24']}), 'profile2': Profile.from_dict({'subnets': ['192.168.0.0/16']}) } def test_get_profile(self, profile_manager): """Manager.get_profile returns a profile.""" config = {'subnets': ['10.0.0.0/24']} profile_manager.create_profile('profile', config) profile = profile_manager.get_profile('profile') assert profile == Profile.from_dict(config) def test_get_profile_unknown(self, profile_manager): """Manager.get_profile raises an error if the name is unknown.""" with pytest.raises(ManagerProfileError): profile_manager.get_profile('unknown') def test_start_profile( self, profile_manager, profile, sessions_dir, bin_succeed): """Manager.start_profile starts a profile.""" profile_manager._get_executable = lambda: str(bin_succeed) profile_manager.start_profile('profile') cmdline = (bin_succeed.parent / 'cmdline').read_text() assert cmdline == ( '10.0.0.0/24 --daemon --pidfile {}/profile.pid\n'.format( sessions_dir)) def test_start_profile_extra_args( self, profile_manager, profile, sessions_dir, bin_succeed): """Manager.start_profile can add extra arguments to command line.""" profile_manager._get_executable = lambda: str(bin_succeed) profile_manager.start_profile( 'profile', extra_args=['--extra1', '--extra2']) cmdline = (bin_succeed.parent / 'cmdline').read_text() assert cmdline == ( '10.0.0.0/24 --daemon --pidfile {}/profile.pid --extra1 --extra2\n' .format(sessions_dir)) def test_start_profile_fail(self, profile_manager, profile, bin_fail): """An error is raised if starting a profile fails.""" profile_manager._get_executable = lambda: str(bin_fail) with pytest.raises(ManagerProfileError) as err: profile_manager.start_profile('profile') assert str(err.value) == 'Profile failed to start: stderr message' def test_start_profile_executable_not_found( self, profile_manager, profile): """Profile start raises an error if executable is not found.""" profile_manager._get_executable = lambda: '/not/here' with pytest.raises(ManagerProfileError): profile_manager.start_profile('profile') def test_start_profile_unknown(self, profile_manager): """Trying to start an unknown profile raises an error.""" with pytest.raises(ManagerProfileError): profile_manager.start_profile('unknown') def test_start_profile_running(self, profile_manager, profile): """Trying to start a running profile raises an error.""" profile_manager.is_running = lambda name: True with pytest.raises(ManagerProfileError): profile_manager.start_profile('profile') def test_stop_profile(self, mocker, profile_manager, pid_file): """Manager.stop_profile stops a running profile.""" mock_kill = mocker.patch('sshoot.manager.os.kill') pid_file.write_text('100\n') profile_manager.is_running = lambda name: True profile_manager.stop_profile('profile') mock_kill.assert_called_once_with(100, 15) def test_stop_profile_unknown(self, profile_manager): """Trying to stop an unknown profile raises an error.""" with pytest.raises(ManagerProfileError): profile_manager.stop_profile('unknown') def test_stop_profile_invalid_pidfile(self, profile_manager, pid_file): """If pidfile contains invalid data, stopping raises an error.""" pid_file.write_text('garbage') with pytest.raises(ManagerProfileError): profile_manager.stop_profile('profile') def test_stop_profile_process_not_found( self, mocker, profile_manager, pid_file): """If the process fails to stop an error is raised.""" pid_file.write_text('100\n') mock_kill = mocker.patch('sshoot.manager.os.kill') mock_kill.side_effect = IOError profile_manager.is_running = lambda name: True with pytest.raises(ManagerProfileError) as err: profile_manager.stop_profile('profile') assert 'Failed to stop profile' in str(err.value) def test_get_pidfile(self, profile_manager, pid_file): """Manager._get_pidfile returns the pidfile path for a session.""" assert profile_manager._get_pidfile('profile') == pid_file def test_is_running(self, profile_manager, pid_file): """If the process is present, the profile is running.""" pid_file.write_text('{}\n'.format(os.getpid())) assert profile_manager.is_running('profile') def test_is_running_no_pidfile(self, profile_manager): """If the pidfile is not found, the profile is not running.""" assert not profile_manager.is_running('not-here') def test_is_running_pidfile_empty(self, profile_manager, pid_file): """If the pidfile is empty, the profile is not running.""" pid_file.write_text('') assert not profile_manager.is_running('profile') def test_is_running_pidfile_no_integer(self, profile_manager, pid_file): """If the pid is not an integer, the profile is not running.""" pid_file.write_text('foo\n') assert not profile_manager.is_running('profile') def test_is_running_pidfile_no_process(self, profile_manager, pid_file): """If no process is present, the profile is not running.""" pid_file.write_text('-100\n') assert not profile_manager.is_running('profile') # The stale pidfile is deleted. assert not pid_file.exists() def test_get_cmdline(self, profile_manager, pid_file): """Manager.get_cmdline returns the command line for the profile.""" assert profile_manager.get_cmdline('profile') == [ 'sshuttle', '10.0.0.0/24', '--daemon', '--pidfile', str(pid_file) ] def test_get_cmdline_extra_args(self, profile_manager, pid_file): """Manager.get_cmdline adds passed extra arguments to command line.""" cmdline = profile_manager.get_cmdline( 'profile', extra_args=['--extra1', '--extra2']) assert cmdline == [ 'sshuttle', '10.0.0.0/24', '--daemon', '--pidfile', str(pid_file), '--extra1', '--extra2' ] def test_get_cmdline_executable(self, profile_manager, pid_file): """Manager.get_cmdline uses the configured executable.""" profile_manager._get_executable = lambda: '/foo/sshuttle' assert profile_manager.get_cmdline('profile') == [ '/foo/sshuttle', '10.0.0.0/24', '--daemon', '--pidfile', str(pid_file) ] class TestGetRundir: def test_rundir_path(self): """get_rundir returns a user-specific tempdir path.""" rundir_path = Path(gettempdir()) / 'foo-{}'.format(getuser()) assert get_rundir('foo') == rundir_path sshoot-1.4.2/sshoot/tests/test_profile.py000066400000000000000000000100441350053456200205710ustar00rootroot00000000000000import pytest from ..profile import ( Profile, ProfileError, ) @pytest.fixture def profile(): yield Profile(['1.1.1.0/24', '10.10.0.0/16']) class TestProfile: def test_from_dict(self): """A Profile can be created from a dict with its attributes.""" profile = Profile.from_dict( { 'remote': '1.2.3.4', 'subnets': ['1.1.1.0/24', '10.10.0.0/16'], 'dns': True, 'auto_hosts': True }) assert profile.remote == '1.2.3.4' assert profile.subnets == ['1.1.1.0/24', '10.10.0.0/16'] assert profile.dns assert profile.auto_hosts # Other attributes are set to default assert not profile.auto_nets assert profile.exclude_subnets is None assert profile.seed_hosts is None assert profile.extra_opts is None def test_from_dict_raise_error(self): """If the 'subnets' key is missing in config, an error is raised.""" with pytest.raises(ProfileError): Profile.from_dict({'remote': '1.2.3.4'}) def test_cmdline(self, profile): """Profile.cmdline() return the sshuttle cmdline for the config.""" assert profile.cmdline() == ['sshuttle', '1.1.1.0/24', '10.10.0.0/16'] def test_cmdline_with_options(self, profile): """Profile.cmdline() return the sshuttle cmdline for the config.""" profile.remote = '1.2.3.4' profile.auto_hosts = True profile.auto_nets = True profile.dns = True profile.cmdline() == [ 'sshuttle', '1.1.1.0/24', '10.10.0.0/16', '--remote=1.2.3.4', '--auto-hosts', '--auto-nets', '--dns' ] def test_cmdline_exclude_subnets(self, profile): """Profile.cmdline() includes excluded subnets in the cmdline.""" profile.exclude_subnets = ['10.20.0.0/16', '10.30.0.0/16'] profile.cmdline() == [ 'sshuttle', '1.1.1.0/24', '10.10.0.0/16', '--exclude=10.20.0.0/16', '--exclude=10.30.0.0/16' ] def test_cmdline_seed_hosts(self, profile): """Profile.cmdline() includes seeded hosts in the cmdline.""" profile.seed_hosts = ['10.1.2.3', '10.4.5.6'] profile.cmdline(), [ 'sshuttle', '1.1.1.0/24', '10.10.0.0/16', '--seed-hosts=10.1.2.3,10.4.5.6' ] def test_cmdline_with_profile_extra_opts(self, profile): """Profile.cmdline() return the sshuttle cmdline with extra options.""" profile.extra_opts = ['--verbose', '--daemon'] assert profile.cmdline() == [ 'sshuttle', '1.1.1.0/24', '10.10.0.0/16', '--verbose', '--daemon' ] def test_cmdline_with_extra_opts(self, profile): """Profile.cmdline() includes extra options.""" profile.cmdline(extra_opts=['--verbose', '--daemon']), [ 'sshuttle', '1.1.1.0/24', '10.10.0.0/16', '--verbose', '--daemon' ] def test_cmdline_with_executable(self, profile): """Profile.cmdline() uses the specified executable.""" assert profile.cmdline(executable='/bin/foo') == [ '/bin/foo', '1.1.1.0/24', '10.10.0.0/16' ] def test_config(self, profile): """Profile.config() returns a dict with the profile config.""" profile.remote = '1.2.3.4' profile.dns = True assert profile.config() == { 'remote': '1.2.3.4', 'dns': True, 'subnets': ['1.1.1.0/24', '10.10.0.0/16'] } def test_config_rebuild_profiles(self, profile): """Result of Profile.config() can be used build an equal Profile.""" assert Profile.from_dict(profile.config()) == profile def test_eq(self, profile): """Profiles can be tested for equality.""" assert Profile(['1.1.1.0/24', '10.10.0.0/16']) == profile def test_eq_false(self, profile): """Profiles with different config don't evaluate as equal.""" other_profile = Profile(['1.1.1.0/24', '10.10.0.0/16']) other_profile.auto_hosts = True assert other_profile != profile sshoot-1.4.2/tox.ini000066400000000000000000000014001350053456200143460ustar00rootroot00000000000000[tox] skipsdist = True [globals] lint_files = setup.py sshoot [testenv] deps = . .[testing] commands = {envbindir}/pytest {posargs} [testenv:format] deps = isort yapf commands = {envbindir}/yapf --in-place --recursive {[globals]lint_files} {envbindir}/isort --recursive {[globals]lint_files} [testenv:lint] deps = flake8 isort yapf commands = {envbindir}/yapf --diff --recursive {[globals]lint_files} {envbindir}/isort --check-only --diff --recursive {[globals]lint_files} {envbindir}/flake8 {[globals]lint_files} [testenv:check] deps = mypy commands = {envbindir}/mypy -p sshoot {posargs} [testenv:coverage] deps = . .[testing] pytest-cov commands = {envbindir}/pytest --cov {posargs}