├── .bump.cfg.nt
├── .gitignore
├── .readthedocs.yml
├── LICENSE
├── README.rst
├── clean
├── doc
├── Makefile
├── commands.rst
├── conf.py
├── configuring.rst
├── examples.rst
├── figures
│ ├── makeall
│ ├── network-map.py
│ ├── network-map.svg
│ ├── proxy1.py
│ ├── proxy1.svg
│ ├── proxy2.py
│ ├── proxy2.svg
│ ├── proxy3.py
│ └── proxy3.svg
├── index.rst
├── network-map.py
├── network-map.svg
├── releases.rst
├── requirements.txt
└── spell
├── examples
└── unlock-peets
├── install
├── setup.py
└── sshconfig
├── __init__.py
├── command.py
├── core.py
├── help.py
├── main.py
├── preferences.py
├── python.py
├── settings.py
├── sshconfig.py
└── utilities.py
/.bump.cfg.nt:
--------------------------------------------------------------------------------
1 | major: 2
2 | minor: 2
3 | patch: 1
4 | revision: 0
5 | type: release
6 | files:
7 | setup.py:
8 | version: version
9 | sshconfig/__init__.py:
10 | version: __version__
11 | date: __released__
12 | README.rst:
13 | version: Version
14 | date: Released
15 | doc/index.rst:
16 | version: Version
17 | date: Released
18 | doc/releases.rst:
19 | version: Version
20 | date: Released
21 | doc/conf.py:
22 | version: release
23 | style: python
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # sshconfig
2 | sshconfig.out
3 |
4 | # vim
5 | .*.swp
6 |
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 |
11 | # C extensions
12 | *.so
13 |
14 | # Distribution / packaging
15 | .Python
16 | env/
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | lib/
23 | lib64/
24 | parts/
25 | sdist/
26 | var/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 |
31 | # PyInstaller
32 | # Usually these files are written by a python script from a template
33 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
34 | *.manifest
35 | *.spec
36 |
37 | # Installer logs
38 | pip-log.txt
39 | pip-delete-this-directory.txt
40 |
41 | # Unit test / coverage reports
42 | htmlcov/
43 | .tox/
44 | .coverage
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 |
56 | # Sphinx documentation
57 | docs/_build/
58 |
59 | # PyBuilder
60 | target/
61 |
--------------------------------------------------------------------------------
/.readthedocs.yml:
--------------------------------------------------------------------------------
1 | # .readthedocs.yml
2 | # Read the Docs configuration file
3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
4 |
5 | # Required
6 | version: 2
7 |
8 | build:
9 | os: ubuntu-22.04
10 | tools:
11 | python: "3.11"
12 |
13 | # Build documentation in the doc/ directory with Sphinx
14 | sphinx:
15 | configuration: doc/conf.py
16 |
17 | # Optionally build your docs in additional formats such as PDF and ePub
18 | formats: all
19 |
20 | # Optionally set the version of Python and requirements required to build your docs
21 | python:
22 | install:
23 | - requirements: doc/requirements.txt
24 | - method: pip
25 | path: .
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | SSH Config — SSH Adapts to Your Current Network
2 | ===============================================
3 |
4 | .. image:: https://pepy.tech/badge/sshconfig/month
5 | :target: https://pepy.tech/project/sshconfig
6 |
7 | .. image:: https://img.shields.io/readthedocs/sshconfig.svg
8 | :target: https://sshconfig.readthedocs.io/en/latest/?badge=latest
9 |
10 | .. image:: https://img.shields.io/pypi/v/sshconfig.svg
11 | :target: https://pypi.python.org/pypi/sshconfig
12 |
13 | .. image:: https://img.shields.io/pypi/pyversions/sshconfig.svg
14 | :target: https://pypi.python.org/pypi/sshconfig/
15 |
16 |
17 | :Author: Ken Kundert
18 | :Version: 2.2.1
19 | :Released: 2023-11-08
20 |
21 |
22 | Installation
23 | ------------
24 |
25 | Requires Python3.6 or newer.
26 |
27 | You can download and install the latest
28 | stable version of the code from `PyPI `_ using::
29 |
30 | pip3 install --user sshconfig
31 |
32 | You can find the latest development version of the source code on
33 | `Github `_.
34 |
35 |
36 | Introduction
37 | ------------
38 |
39 | SSH Config generates an SSH config file adapted to the network you are currently
40 | using. In this way, you always use the fastest paths available for your SSH
41 | related activities (sshfs, email, vnc, mercurial, etc.). You can also easily
42 | reconfigure SSH to make use of proxies as needed or select certain servers or
43 | ports based on your location or restrictions with the network.
44 |
45 | The following situations are supported:
46 |
47 | #. You may give the mac address or addresses for your router or routers and your
48 | network will automatically be recognized.
49 | #. You can configure which hostname or IP address is used for a particular host
50 | depending on which network you are on. In this way you always use the fastest
51 | connection available for each host.
52 | #. You can specify that certain hosts are hidden behind other hosts, so that
53 | a SSH proxy should be used to access them.
54 | #. You can specify port forwarding information for each host. Then, two SSH
55 | configurations will be created for those hosts, one that includes port
56 | forwarding and one that does not. That way, once the port forwards are
57 | established, you can open additional shells on that host without SSH trying
58 | to create conflicting port forwards.
59 | #. You can enter multiple hostnames or IP addresses and give their locations.
60 | Then, if you specify your location, the closest server will be used
61 | automatically.
62 | #. You can specify proxy configurations and specify that one should be used for
63 | all hosts not on your current network.
64 | #. You can specify port restrictions and have SSH work around them if possible
65 | (if your server supports alternative ports).
66 | #. You can configure a default location, proxy, or set of port restrictions for
67 | each of your known networks.
68 | #. Once host names are defined, they do not change even though you are using
69 | different configurations (different networks, locations, proxies, and port
70 | restrictions). In this way you can hard code your host names in applications
71 | such as Mercurial or Git, and they automatically adapt to your existing
72 | network.
73 | #. The entire application, including the configuration files, are Python code,
74 | so you have considerable freedom to change the configuration based on things
75 | like the name of the machine or the user when generating the SSH config file.
76 |
77 | Documentation
78 | -------------
79 |
80 | You can find documentation at `ReadTheDocs `_.
81 |
82 |
83 | Issues
84 | ------
85 |
86 | Please ask questions or report problems on
87 | `Github Issues `_.
88 |
89 |
90 | Contributions
91 | -------------
92 |
93 | Contributions in the form of pull requests are welcome.
94 |
--------------------------------------------------------------------------------
/clean:
--------------------------------------------------------------------------------
1 | #!/bin/csh -f
2 |
3 | set nonomatch
4 |
5 | rm -f README.pdf
6 |
7 | # the rest is common to all python directories
8 | rm -f *.pyc *.pyo .test*.sum expected result install.out
9 | rm -rf build *.egg-info dist __pycache__ .coverage .coverage-html
10 | rm -f resp*.html
11 |
12 | foreach i (*/clean)
13 | if ($i == "*/clean") break
14 | #echo $i
15 | (cd $i:h; ./clean)
16 | end
17 | foreach i (*/Makefile)
18 | if ($i == "*/Makefile") break
19 | #echo $i
20 | (cd $i:h; make clean)
21 | end
22 |
--------------------------------------------------------------------------------
/doc/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = .build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
16 |
17 | .PHONY: help clean show html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | default: html
20 |
21 | help:
22 | @echo "Please use \`make ' where is one of"
23 | @echo " html to make standalone HTML files"
24 | @echo " dirhtml to make HTML files named index.html in directories"
25 | @echo " singlehtml to make a single large HTML file"
26 | @echo " pickle to make pickle files"
27 | @echo " json to make JSON files"
28 | @echo " htmlhelp to make HTML files and a HTML help project"
29 | @echo " qthelp to make HTML files and a qthelp project"
30 | @echo " devhelp to make HTML files and a Devhelp project"
31 | @echo " epub to make an epub"
32 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
33 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
34 | @echo " text to make text files"
35 | @echo " man to make manual pages"
36 | @echo " texinfo to make Texinfo files"
37 | @echo " info to make Texinfo files and run them through makeinfo"
38 | @echo " gettext to make PO message catalogs"
39 | @echo " changes to make an overview of all changed/added/deprecated items"
40 | @echo " linkcheck to check all external links for integrity"
41 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
42 |
43 | clean:
44 | -rm -rf $(BUILDDIR)/*
45 |
46 | html:
47 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
48 | @echo
49 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
50 |
51 | show: html
52 | firefox .build/html/index.html
53 |
54 | dirhtml:
55 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
56 | @echo
57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
58 |
59 | singlehtml:
60 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
61 | @echo
62 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
63 |
64 | pickle:
65 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
66 | @echo
67 | @echo "Build finished; now you can process the pickle files."
68 |
69 | json:
70 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
71 | @echo
72 | @echo "Build finished; now you can process the JSON files."
73 |
74 | htmlhelp:
75 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
76 | @echo
77 | @echo "Build finished; now you can run HTML Help Workshop with the" \
78 | ".hhp project file in $(BUILDDIR)/htmlhelp."
79 |
80 | qthelp:
81 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
82 | @echo
83 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
84 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
85 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/avendesora.qhcp"
86 | @echo "To view the help file:"
87 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/avendesora.qhc"
88 |
89 | devhelp:
90 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
91 | @echo
92 | @echo "Build finished."
93 | @echo "To view the help file:"
94 | @echo "# mkdir -p $$HOME/.local/share/devhelp/avendesora"
95 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/avendesora"
96 | @echo "# devhelp"
97 |
98 | epub:
99 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
100 | @echo
101 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
102 |
103 | latex:
104 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
105 | @echo
106 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
107 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
108 | "(use \`make latexpdf' here to do that automatically)."
109 |
110 | latexpdf:
111 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
112 | @echo "Running LaTeX files through pdflatex..."
113 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
114 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
115 |
116 | text:
117 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
118 | @echo
119 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
120 |
121 | man:
122 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
123 | @echo
124 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
125 |
126 | texinfo:
127 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
128 | @echo
129 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
130 | @echo "Run \`make' in that directory to run these through makeinfo" \
131 | "(use \`make info' here to do that automatically)."
132 |
133 | info:
134 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
135 | @echo "Running Texinfo files through makeinfo..."
136 | make -C $(BUILDDIR)/texinfo info
137 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
138 |
139 | gettext:
140 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
141 | @echo
142 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
143 |
144 | changes:
145 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
146 | @echo
147 | @echo "The overview file is in $(BUILDDIR)/changes."
148 |
149 | linkcheck:
150 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
151 | @echo
152 | @echo "Link check complete; look for any errors in the above output " \
153 | "or in $(BUILDDIR)/linkcheck/output.txt."
154 |
155 | doctest:
156 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
157 | @echo "Testing of doctests in the sources finished, look at the " \
158 | "results in $(BUILDDIR)/doctest/output.txt."
159 |
--------------------------------------------------------------------------------
/doc/commands.rst:
--------------------------------------------------------------------------------
1 | Command Reference
2 | =================
3 |
4 | .. _sshconfig command line options:
5 |
6 | Common Command Line Arguments
7 | -----------------------------
8 |
9 | ::
10 |
11 | Usage:
12 |
13 | sshconfig [options] [ [...]]
14 |
15 | Options:
16 |
17 | -l LOCATION, --location LOCATION specifies location
18 | -n NETWORK, --network NETWORK specifies the network
19 | -p PORTS, --ports PORTS specifies list of available ports
20 | -P NAME, --proxy NAME specifies the global proxy
21 | -q, --quiet suppress optional output
22 |
23 | Specify the list of available ports as a comma separated list (no spaces). For
24 | example, --ports=80,443.
25 |
26 | Normally the network is determined automatically and need not be specified.
27 |
28 | Run ``sshconfig help `` for information on a specific command.
29 |
30 | Run ``sshconfig help`` for list of available help topics.
31 |
32 | Run ``sshconfig available`` to see available choices for proxies, locations, and
33 | networks.
34 |
35 |
36 | .. _sshconfig available command:
37 |
38 | **available** -- Show Available Option Choices
39 | ----------------------------------------------
40 |
41 | Usage::
42 |
43 | sshconfig available
44 |
45 | The ``--location``, ``--network``, and ``--proxies`` options all take values as
46 | arguments that were specified in your configuration files. The *available*
47 | command can be used to refresh your memory on what is available. It simply lists
48 | out all available choices for each of the three categories. Specifically, it
49 | lists the names and descriptions for all configured locations, networks and
50 | proxies.
51 |
52 |
53 | .. _sshconfig create command:
54 |
55 | **create** -- Create the SSH config file
56 | ----------------------------------------
57 |
58 | Create an SSH config file.
59 |
60 | Usage::
61 |
62 | sshconfig [options]
63 | sshconfig [options] create
64 |
65 | Normally you can create your SSH config file using ``sshconfig create`` or
66 | simply ``sshconfig``. However, special circumstances may require that you
67 | specify command line options so as to modify the generated config file to meet
68 | your needs. For example, if you find yourself in a coffee shop that blocks port
69 | 22, you might create your SSH config file using::
70 |
71 | sshconfig -p 443,80
72 |
73 | This tells *sshconfig* to use port 443 or port 80 if available when generating
74 | the SSH host entries.
75 |
76 | Or perhaps you are traveling to the far east, you might want to use your server
77 | in Tokyo rather than the ones back home::
78 |
79 | sshconfig -l tokyo
80 |
81 |
82 | .. _sshconfig find command:
83 |
84 | **find** -- Find an SSH host configuration
85 | ------------------------------------------
86 |
87 | Find SSH host configurations whose names contains a substring.
88 |
89 | Usage::
90 |
91 | sshconfig find
92 |
93 |
94 | .. _sshconfig help command:
95 |
96 | **help** -- Show Helpful Information
97 | ------------------------------------
98 |
99 | Shows helpful information for each a command or a topic.
100 |
101 | Usage::
102 |
103 | sshconfig help
104 | sshconfig help
105 | sshconfig help
106 |
107 | Run ``sshconfig help`` for a list of available commands and topics.
108 |
109 |
110 | .. _sshconfig show command:
111 |
112 | **show** -- Show a SSH Host Configuration
113 | -----------------------------------------
114 |
115 | Usage::
116 |
117 | sshconfig [options] show
118 |
119 | Shows the SSH host entry to be generated given a host name. This can be used to
120 | show you how the host entry changes based on various options such as
121 | ``--ports``. This command does not affect your SSH config file.
122 |
123 |
124 | .. _sshconfig version command:
125 |
126 | **version** -- Show SSHConfig Version
127 | -------------------------------------
128 |
129 | Usage::
130 |
131 | sshconfig version
132 |
--------------------------------------------------------------------------------
/doc/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # SSHConfig documentation build configuration file, created by
4 | # sphinx-quickstart on Mon Jun 12 12:01:56 2017.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('.'))
20 |
21 | # -- General configuration -----------------------------------------------------
22 |
23 | # If your documentation needs a minimal Sphinx version, state it here.
24 | #needs_sphinx = '1.0'
25 |
26 | # Add any Sphinx extension module names here, as strings. They can be extensions
27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28 | extensions = '''
29 | sphinx.ext.autodoc
30 | sphinx.ext.coverage
31 | sphinx.ext.doctest
32 | sphinx.ext.napoleon
33 | sphinx.ext.todo
34 | sphinx.ext.viewcode
35 | '''.split()
36 |
37 | # Add any paths that contain templates here, relative to this directory.
38 | templates_path = ['.templates']
39 |
40 | # The suffix of source filenames.
41 | source_suffix = '.rst'
42 |
43 | # The encoding of source files.
44 | #source_encoding = 'utf-8-sig'
45 |
46 | # The master toctree document.
47 | master_doc = 'index'
48 |
49 | # General information about the project.
50 | project = u'sshconfig'
51 | copyright = u'2017-2023, Ken Kundert'
52 |
53 | # The version info for the project you're documenting, acts as replacement for
54 | # |version| and |release|, also used in various other places throughout the
55 | # built documents.
56 | #
57 | # The full version, including alpha/beta/rc tags.
58 | release = '2.2.1'
59 | # The short X.Y version.
60 | version = '.'.join(release.split('.')[0:2])
61 |
62 | # The language for content autogenerated by Sphinx. Refer to documentation
63 | # for a list of supported languages.
64 | #language = None
65 |
66 | # There are two options for replacing |today|: either, you set today to some
67 | # non-false value, then it is used:
68 | #today = ''
69 | # Else, today_fmt is used as the format for a strftime call.
70 | #today_fmt = '%B %d, %Y'
71 |
72 | # List of patterns, relative to source directory, that match files and
73 | # directories to ignore when looking for source files.
74 | exclude_patterns = ['.build']
75 |
76 | # The reST default role (used for this markup: `text`) to use for all documents.
77 | #default_role = None
78 |
79 | # If true, '()' will be appended to :func: etc. cross-reference text.
80 | #add_function_parentheses = True
81 |
82 | # If true, the current module name will be prepended to all description
83 | # unit titles (such as .. function::).
84 | #add_module_names = True
85 |
86 | # If true, sectionauthor and moduleauthor directives will be shown in the
87 | # output. They are ignored by default.
88 | #show_authors = False
89 |
90 | # The name of the Pygments (syntax highlighting) style to use.
91 | pygments_style = 'sphinx'
92 |
93 | # A list of ignored prefixes for module index sorting.
94 | #modindex_common_prefix = []
95 |
96 |
97 | # -- Options for HTML output ---------------------------------------------------
98 |
99 | # The theme to use for HTML and HTML Help pages. See the documentation for
100 | # a list of builtin themes.
101 | # html_theme = 'nature'
102 | # Use default rather than my normal nature so we get the read-the-docs style on
103 | # that website.
104 | html_theme = 'sphinx_rtd_theme'
105 |
106 | # Theme options are theme-specific and customize the look and feel of a theme
107 | # further. For a list of options available for each theme, see the
108 | # documentation.
109 | #html_theme_options = {}
110 |
111 | # Add any paths that contain custom themes here, relative to this directory.
112 | #html_theme_path = []
113 |
114 | # The name for this set of Sphinx documents. If None, it defaults to
115 | # " v documentation".
116 | #html_title = None
117 |
118 | # A shorter title for the navigation bar. Default is the same as html_title.
119 | #html_short_title = None
120 |
121 | # The name of an image file (relative to this directory) to place at the top
122 | # of the sidebar.
123 | #html_logo = None
124 |
125 | # The name of an image file (within the static path) to use as favicon of the
126 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
127 | # pixels large.
128 | #html_favicon = None
129 |
130 | # Add any paths that contain custom static files (such as style sheets) here,
131 | # relative to this directory. They are copied after the builtin static files,
132 | # so a file named "default.css" will overwrite the builtin "default.css".
133 | #html_static_path = ['.static']
134 |
135 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
136 | # using the given strftime format.
137 | #html_last_updated_fmt = '%b %d, %Y'
138 |
139 | # If true, SmartyPants will be used to convert quotes and dashes to
140 | # typographically correct entities.
141 | #html_use_smartypants = True
142 |
143 | # Custom sidebar templates, maps document names to template names.
144 | #html_sidebars = {}
145 |
146 | # Additional templates that should be rendered to pages, maps page names to
147 | # template names.
148 | #html_additional_pages = {}
149 |
150 | # If false, no module index is generated.
151 | #html_domain_indices = True
152 |
153 | # If false, no index is generated.
154 | #html_use_index = True
155 |
156 | # If true, the index is split into individual pages for each letter.
157 | #html_split_index = False
158 |
159 | # If true, links to the reST sources are added to the pages.
160 | #html_show_sourcelink = True
161 |
162 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
163 | #html_show_sphinx = True
164 |
165 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
166 | #html_show_copyright = True
167 |
168 | # If true, an OpenSearch description file will be output, and all pages will
169 | # contain a tag referring to it. The value of this option must be the
170 | # base URL from which the finished HTML is served.
171 | #html_use_opensearch = ''
172 |
173 | # This is the file name suffix for HTML files (e.g. ".xhtml").
174 | #html_file_suffix = None
175 |
176 | # Output file base name for HTML help builder.
177 | htmlhelp_basename = 'sshconfigdoc'
178 |
179 |
180 | # -- Options for LaTeX output --------------------------------------------------
181 |
182 | latex_elements = {
183 | # The paper size ('letterpaper' or 'a4paper').
184 | #'papersize': 'letterpaper',
185 |
186 | # The font size ('10pt', '11pt' or '12pt').
187 | #'pointsize': '10pt',
188 |
189 | # Additional stuff for the LaTeX preamble.
190 | #'preamble': '',
191 | }
192 |
193 | # Grouping the document tree into LaTeX files. List of tuples
194 | # (source start file, target name, title, author, documentclass [howto/manual]).
195 | latex_documents = [
196 | ('index', 'sshconfig.tex', u'SSHConfig Documentation',
197 | u'Ken Kundert', 'manual'),
198 | ]
199 |
200 | # The name of an image file (relative to this directory) to place at the top of
201 | # the title page.
202 | #latex_logo = None
203 |
204 | # For "manual" documents, if this is true, then toplevel headings are parts,
205 | # not chapters.
206 | #latex_use_parts = False
207 |
208 | # If true, show page references after internal links.
209 | #latex_show_pagerefs = False
210 |
211 | # If true, show URL addresses after external links.
212 | #latex_show_urls = False
213 |
214 | # Documents to append as an appendix to all manuals.
215 | #latex_appendices = []
216 |
217 | # If false, no module index is generated.
218 | #latex_domain_indices = True
219 |
220 |
221 | # -- Options for manual page output --------------------------------------------
222 |
223 | # One entry per manual page. List of tuples
224 | # (source start file, name, description, authors, manual section).
225 | man_pages = [
226 | ('index', 'sshconfig', u'SSHConfig Documentation',
227 | [u'Ken Kundert'], 1)
228 | ]
229 |
230 | # If true, show URL addresses after external links.
231 | #man_show_urls = False
232 |
233 |
234 | # -- Options for Texinfo output ------------------------------------------------
235 |
236 | # Grouping the document tree into Texinfo files. List of tuples
237 | # (source start file, target name, title, author,
238 | # dir menu entry, description, category)
239 | texinfo_documents = [
240 | ('index', 'SSHConfig', u'SSHConfig Documentation',
241 | u'Ken Kundert', 'SSHConfig', 'One line description of project.',
242 | 'Miscellaneous'),
243 | ]
244 |
245 | # Documents to append as an appendix to all manuals.
246 | #texinfo_appendices = []
247 |
248 | # If false, no module index is generated.
249 | #texinfo_domain_indices = True
250 |
251 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
252 | #texinfo_show_urls = 'footnote'
253 |
254 | #KSK: add custom css code if present
255 | def setup(app):
256 | import os
257 | if os.path.exists('.static/css/custom.css'):
258 | app.add_stylesheet('css/custom.css')
259 |
260 | # KSK: the following is needed by read-the-docs because they do not install
261 | # gobject-introspection-1.0
262 | #
263 | #autodoc_mock_inports = ['pygobject']
264 | #
265 | #used doc/requirements.txt instead
266 |
--------------------------------------------------------------------------------
/doc/examples.rst:
--------------------------------------------------------------------------------
1 | Examples
2 | --------
3 |
4 | Multiple Clients, Multiple Servers, One Set of Config Files
5 | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""
6 |
7 | Imagine having several machines that you log in to directly, call them cyan,
8 | magenta, and yellow, and imagine that each has its own SSH key, cyan_rsa,
9 | magenta_rsa, and yellow_rsa. Further imagine that you also have several servers
10 | that you want to access, mantis, honeybee, and butterfly. Finally, assume that
11 | you would like to have one set of *sshconfig* files that are shared between all
12 | of them.
13 |
14 | Call cyan, magenta, and yellow the clients, and call mantis, honeybee, and
15 | butterfly the servers. Finally, the clients do not have fixed IP addresses and
16 | so will not have entries, meaning that from any client you can get to any
17 | server, but you cannot access another client.
18 |
19 | Then, a *hosts.conf* file for this situation might appear like the following:
20 |
21 | .. code-block:: python
22 |
23 | from sshconfig import HostEntry
24 |
25 | identities = ['cyan_rsa.pub', 'magenta_rsa.pub', 'yellow_rsa.pub']
26 |
27 | class Mantis(HostEntry):
28 | hostname = 'mantis'
29 | identityFile = identities
30 | trusted = True
31 |
32 | class HoneyBee(HostEntry):
33 | hostname = 'honeybee'
34 | identityFile = identities
35 | trusted = True
36 |
37 | class ButterFly(HostEntry):
38 | hostname = 'butterfly'
39 | identityFile = identities
40 | trusted = True
41 |
42 | From this *sshconfig* creates the following host entries for ~/.ssh/config:
43 |
44 | .. code-block:: python
45 |
46 | host butterfly
47 | hostname butterfly
48 | identityFile cyan_rsa.pub
49 | identityFile magenta_rsa.pub
50 | identityFile yellow_rsa.pub
51 | identitiesOnly yes
52 | pubkeyAuthentication yes
53 | forwardAgent yes
54 |
55 | host honeybee
56 | hostname honeybee
57 | identityFile cyan_rsa.pub
58 | identityFile magenta_rsa.pub
59 | identityFile yellow_rsa.pub
60 | identitiesOnly yes
61 | pubkeyAuthentication yes
62 | forwardAgent yes
63 |
64 | host mantis
65 | hostname mantis
66 | identityFile cyan_rsa.pub
67 | identityFile magenta_rsa.pub
68 | identityFile yellow_rsa.pub
69 | identitiesOnly yes
70 | pubkeyAuthentication yes
71 | forwardAgent yes
72 |
73 | The private keys are only present on the respective clients. In this way if one
74 | of the clients is lost or compromised, you can simply remove the corresponding
75 | public keys from the authorized hosts files on the servers to re-secure your
76 | hosts.
77 |
78 | Each host is trusted and the key is loaded into the SSH agent on the client.
79 | Access to the key as you move from host to host is provided by agent forwarding.
80 | Use of the *identityFile* allows you to limit the keys to be considered for each
81 | host but requires that the specified files exist on each host. Specifying the
82 | public keys means that you can keep your private key on the client; you do not
83 | need to copy it to all the hosts that you use.
84 |
85 |
86 | One Set of Config Files for a Heterogeneous Environment
87 | """""""""""""""""""""""""""""""""""""""""""""""""""""""
88 |
89 | The previous example was simplified because there is a constant address for all
90 | the servers. Now consider a collection of machines where how you access
91 | a machine differs on where you are in the network. Here is a diagram of the
92 | network. *Host* entries are created for each of the machines that are drawn with
93 | a solid outline. Those machines that are connected to the internet have public
94 | IP addresses, those that are not connected to the internet have private
95 | addresses on a network provided by the enclosing box. Thus, *work* has a network
96 | that contains *bastion*, *dump* and *my_laptop*. *bastion* contains *www* and
97 | *mail*, and connects to both *work* and the internet. *my laptop* shows up in
98 | three places and switches between them as I move around. Generally the IP
99 | address of *my laptop* is assigned dynamically (if you want to access
100 | *my_laptop* from your servers, see :ref:`accessing client` and :ref:`tor`
101 | below).
102 |
103 | .. image:: figures/network-map.svg
104 | :width: 50%
105 | :align: center
106 |
107 | The following *hosts.conf* file can be used to access these hosts, using optimal
108 | path in each case:
109 |
110 | .. code-block:: python
111 |
112 | from sshconfig import HostEntry, gethostname
113 |
114 | local_host_name = gethostname()
115 |
116 | class Bastion(HostEntry):
117 | description = 'Work bastion server',
118 | if local_host_name == 'bastion':
119 | hostname = '127.0.0.1'
120 | else:
121 | hostname = dict(
122 | bastion = '192.168.122.1',
123 | work = '10.25.13.4',
124 | default = '181.78.165.55'
125 | )
126 | trusted = True
127 |
128 | class WWW(HostEntry):
129 | description = 'Web server',
130 | hostname = '192.168.122.172'
131 | if local_host_name == 'www':
132 | hostname = '127.0.0.1'
133 | elif get_network_name() != 'bastion':
134 | ProxyJump = 'bastion'
135 | trusted = True
136 |
137 | class Mail(HostEntry):
138 | description = 'Mail server',
139 | hostname = '192.168.122.173'
140 | if local_host_name == 'mail':
141 | hostname = '127.0.0.1'
142 | elif get_network_name() != 'bastion':
143 | ProxyJump = 'bastion'
144 | trusted = True
145 |
146 | class Dump(HostEntry):
147 | description = 'Backups server',
148 | hostname = '10.25.13.27',
149 | if local_host_name == 'dump':
150 | hostname = '127.0.0.1'
151 | elif get_network_name() != 'work':
152 | ProxyJump = 'bastion'
153 | trusted = True
154 |
155 | class Media(HostEntry):
156 | description = 'Home media server',
157 | if local_host_name == 'media':
158 | hostname = '127.0.0.1'
159 | else:
160 | hostname = dict(
161 | home = '192.168.0.2',
162 | default = '101.218.138.141'
163 | )
164 | trusted = True
165 |
166 | class GitHub(HostEntry):
167 | description = 'GitHub',
168 | hostname = 'github.com'
169 | trusted = False
170 |
171 | class VirtualPrivateServer(HostEntry):
172 | description = 'my virtual private server',
173 | alias = 'vps'
174 | hostname = '129.173.134.181'
175 | trusted = True
176 |
177 | class Backups(HostEntry):
178 | description = 'home backups',
179 | hostname = '109.142.233.168'
180 | trusted = False
181 |
182 | First a few words about *bastion*. If *sshconfig* is run with this file on
183 | *bastion*, then *local_host_name* will be ``bastion`` and the IP address for
184 | *bastion* will be set to 127.0.0.1, which is the address a machine assigns to
185 | itself. Otherwise, if *sshconfig* is run on one of *bastion*'s virtual machines,
186 | then *hostname* becomes 192.168.122.1, the address of *bastion* on its internal
187 | virtual network. If it run on a machine on the *work* network outside of
188 | *bastion*, it gets the address of *bastion* on *work* network: 10.25.13.4.
189 | Finally, for all other machines, the public address is used: 181.78.165.55.
190 | Thus, in all cases the optimal IP address is used.
191 |
192 | Now some words about *www* and *mail*, the *bastion* virtual machines. Consider
193 | *www*. If *sshconfig* is run on *www*, then the hostname is set to 127.0.0.1.
194 | If it is run on a machine on the *bastion* virtual network, such as *mail*, then
195 | hostname is set to its address on that network, 192.168.122.172. On any other
196 | machine *bastion* is used as a jump host. Normally *www* would be described
197 | using a subclass of *Bastion*, which routes all connections to *www* through
198 | *bastion*. However, that is not as efficient when on machines that are on the
199 | *bastion* virtual network. Thus this approach is a bit more verbose but
200 | represent an optimal solution from a performance perspective.
201 |
202 | Specifying *trusted* as True on a host results in agent forwarding to be enabled
203 | for that host. If you start on the laptop and visit a trusted host, then your
204 | SSH agent goes with you, and you can move from a trusted host to any other host
205 | without typing a passphrase as long as that host accepts a key held in the
206 | laptop's agent. Never declare a host as trusted if you do not trust root on
207 | that host.
208 |
209 |
210 | .. _accessing client:
211 |
212 | Accessing the Client
213 | """"""""""""""""""""
214 |
215 | Assume that you have logged into your laptop, the client, and used it to access
216 | a server. On the server you may need an SSH host entry that gets you back to
217 | the client. For example, you may have Git or Mercurial repositories on you
218 | laptop that you need to pull from. To address this you need two things. First,
219 | you need to set up a reverse tunnel that allows you to access the SSH server on
220 | your laptop from the server, and two you need a SSH host entry on the server
221 | that uses that tunnel to reach your laptop. The first is provided by the
222 | *remoteForward* on this example of the *sshconfig* host entry for the server:
223 |
224 | .. code-block:: python
225 |
226 | class Dev(HostEntry):
227 | description = "Development server"
228 | hostname = '192.168.122.17'
229 | remoteForward = [
230 | ('2222 localhost:22', "Reverse SSH tunnel used by Mercurial"),
231 | ]
232 |
233 | The second is provided by adding a *sshconfig* host entry for the client machine
234 | as seen from the server:
235 |
236 | .. code-block:: python
237 |
238 | class Client(HostEntry):
239 | description = "used for reverse tunnels back to the client host"
240 | hostname = 'localhost'
241 | port = 2222
242 | StrictHostKeyChecking = False
243 |
244 | Now your Git and Mercurial repositories use *client* as the name for the
245 | repository host. The *StrictHostKeyChecking* is only needed if their might be
246 | multiple clients
247 |
248 |
249 | .. _proxies:
250 |
251 | Access Restrictions
252 | """""""""""""""""""
253 |
254 | In some situations you may be sitting behind firewalls that prevent direct
255 | access to your SSH server. Generally, firewalls allow use of common ports, such
256 | as 80 (http), 443 (https), and perhaps 53 (dns). In this case, you simply
257 | configure your SSH server to listen on these ports. This situation is
258 | illustrated here:
259 |
260 | .. image:: figures/proxy1.svg
261 | :width: 50%
262 | :align: center
263 |
264 | In this case you simply list the available ports on your host entry and specify
265 | the desired port when you run *SSHconfig*:
266 |
267 | .. code-block:: python
268 |
269 | class SSH_Server(HostEntry):
270 | hostname = 'NNN.NNN.NNN.NNN'
271 | port = ports.choose([22, 53, 80, 443])
272 |
273 | However, it may be that those ports are already in use. For example, you may
274 | have a webserver that is using ports 80 and 443. In this case it is possible to
275 | insert a proxy that allows these ports to be used for web both and SSH traffic.
276 |
277 | .. image:: figures/proxy2.svg
278 | :width: 80%
279 | :align: center
280 |
281 | If you use Apache for your webserver, it naturally provides the *CONNECT*
282 | feature that allows it to act as its own proxy. See `SSH via HTTP
283 | `_ for instructions.
284 | It is also possible to use `sslh
285 | `_ or `HAproxy
286 | `_.
287 |
288 | In this case you would specify the proxy using *proxyCommand*. You can either
289 | add it directly to your host configuration or you can create a named proxy and
290 | specify it when you run *SSHconfig*. For example, specifying the proxy on your
291 | host entry can be done as follows:
292 |
293 | .. code-block:: python
294 |
295 | class SSH_Server(HostEntry):
296 | hostname = 'NNN.NNN.NNN.NNN'
297 | port = ports.choose([22, 53, 80, 443])
298 | if port in [80, 443]:
299 | proxyCommand = 'corkscrew %h %p localhost 22'
300 |
301 | SSH replaces %h with the hostname and %p with the port number. In this case
302 | %h becomes *NNN.NNN.NNN.NNN* and %p becomes the chosen port (either 80 or 443).
303 |
304 | In this situation, there are a wide variety of programs that can be used to
305 | interface with the proxy server. For example:
306 |
307 | .. code-block:: python
308 |
309 | proxyCommand = 'proxytunnel -q -p %h:%p -d localhost:22'
310 | proxyCommand = 'socat - PROXY:%h:localhost:22,proxyport=%p'
311 | proxyCommand = 'corkscrew %h %p localhost 22'
312 | proxyCommand = 'ncat --proxy %h:%p --proxy-type http localhost 22'
313 |
314 | Those commands all assume you are using an HTTP proxy. If you are using a SOCKS
315 | proxy, you can use:
316 |
317 | .. code-block:: python
318 |
319 | proxyCommand = 'ncat --proxy MMM.MMM.MMM.MMM:PPPP --proxy-type socks5 %h %p'
320 |
321 | where *MMM.MMM.MMM.MMM* is the host name or IP address of you proxy, and *PPPP*
322 | is the proxy's port number (in this case I am not assuming that your SSH sever
323 | is on the same host as the proxy server.
324 |
325 | If you are using a HTTPS proxy that expects the incoming traffic to be wrapped
326 | in an SSL/TLS tunnel, you can use `ProxyTunnel
327 | `_:
328 |
329 | .. code-block:: python
330 |
331 | class SSH_Server(HostEntry):
332 | hostname = 'NNN.NNN.NNN.NNN'
333 | port = ports.choose([22, 53, 80, 443])
334 | if port == 80:
335 | proxyCommand = 'proxytunnel -q -p %h:%p -d localhost:22'
336 | elif port == 443:
337 | proxyCommand = 'proxytunnel -q -E -p %h:%p -d localhost:22'
338 |
339 | Another common situation is that your are behind an oppressive corporate
340 | firewall that blocks all traffic except that which passes through a specific
341 | pass-through proxy server. In this case they often perform deep packet
342 | inspection on the traffic passing through the proxy in order to discover and
343 | block traffic they find undesirable. SSH traffic is often one of their targets.
344 | In this case you can often get through by embedding your SSH traffic in an
345 | SSL/TLS tunnel. Doing so encrypts the traffic and makes it look like normal web
346 | traffic, making it impossible to filter out without also risking filtering out
347 | normal web traffic. In this case, a remote proxy is required at the destination
348 | to extract the SSH traffic from the SSL/TLS tunnel:
349 |
350 | .. image:: figures/proxy3.svg
351 | :width: 100%
352 | :align: center
353 |
354 | There are variety of ways of embedding your SSH traffic in an SSL/TLS tunnel.
355 | For example, `stunnel `_ and `HTTP tunnel
356 | `_. One simple way, if your
357 | server already has Apache running, is to use `SSH via HTTP
358 | `_ on port 443 with
359 | SSL/TLS enabled. Having an active website at the same address and port you are
360 | using for SSH is particularly desirable as it makes it seem like you are just
361 | accessing the website normally. `ProxyTunnel
362 | `_ is used as the interface to the
363 | proxy servers, as it can form the SSL/TLS tunnel:
364 |
365 | .. code-block:: python
366 |
367 | from sshconfig import get_network_name
368 |
369 | class SSH_Server(HostEntry):
370 | hostname = 'NNN.NNN.NNN.NNN'
371 | if get_network_name() == 'work':
372 | proxyCommand = 'proxytunnel -E -q -p MMM.MMM.MMM.MMM:LPP -r %h:RPP -d localhost:%p'
373 |
374 | In this example, the pass-through proxy is only used if you are on the *work*
375 | network and the remote proxy port, *RPP*, is generally chosen to be 443 to
376 | complete the ruse.
377 |
378 | In some cases, it may be that the corporate proxy is decrypting, in which case
379 | it would be possible for it to use deep packet inspection to determine that you
380 | are using SSH and block the connection. At this point, I believe you are out of
381 | luck.
382 |
383 | Once you have established one SSH connection through the firewall, you can
384 | exploit it to get other connections through. For example:
385 |
386 | .. code-block:: python
387 |
388 | class RemoteProxy:
389 | hostname = 'MMM.MMM.MMM.MMM'
390 | port = PPP
391 |
392 | class SSH_Server:
393 | hostname = 'NNN.NNN.NNN.NNN'
394 | proxyJump = 'remoteproxy'
395 |
396 | In this case, *remoteproxy* is the established SSH connection that pierces the
397 | firewall, and *ssh_server* uses *proxyJump* to piggy-back on that connection as
398 | its way to pierce the firewall.
399 |
400 | Older versions of SSH do not support *proxyJump*, so the *SSH_Server* host can
401 | be described using:
402 |
403 | .. code-block:: python
404 |
405 | class SSH_Server:
406 | hostname = 'NNN.NNN.NNN.NNN'
407 | proxyCommand = 'ssh remoteproxy -W %h:%p'
408 |
409 | In this case, SSH replaces %h with the specified hostname, *NNN.NNN.NNN.NNN*,
410 | and %p with the specified port (22 is used if no port is given).
411 |
412 |
413 | .. _tor:
414 |
415 | SSH via Tor
416 | """""""""""
417 |
418 | A convenient way to access machines that have no fixed IP address is to
419 | configure SSH as a Tor hidden service on that machine as described `here
420 | `_. This is helpful
421 | because, as long as Tor is running on both machines and can reach the internet,
422 | it should be possible to establish a connection regardless of how deeply either
423 | is buried in private networks. Here is a host entry for accessing such
424 | a machine:
425 |
426 | .. code-block:: python
427 |
428 | class HiddenLaptop(HostEntry):
429 | description = "Laptop as Tor hidden service"
430 | aliases = 'hl'.split()
431 | hostname = '8owgthc4izjjke9sb4qi5dquhbnug4elcnlbv6pkszybvghylryrodad.onion'
432 | proxyCommand = 'ncat --proxy localhost:9050 --proxy-type socks5 %h %p'
433 |
434 | This assumes that you have Tor running on your client machine and it is
435 | providing a SOCKS proxy on port 9050, and that SSH is configured as a hidden
436 | service and Tor is running on the machine you are trying to access.
437 |
438 |
439 | Supporting Hosts with Old Versions of SSH
440 | """""""""""""""""""""""""""""""""""""""""
441 |
442 | When a host has an older version of SSH and you are using the SSH algorithm
443 | settings to harden your connections, then you may run into the situation where
444 | one or more of your choices is not supported by the dated version of SSH.
445 |
446 | There are two situations that must be addressed. First, when run from a machine
447 | with a newer version of of SSH and connecting to a machine with an older version
448 | fo SSH, an algorithm must not be required that the older version does not
449 | support. In this case one simply specifies the algorithms suitable for
450 | a particular host in the host entry for that host. For example:
451 |
452 | .. code-block:: python
453 |
454 | class Github(HostEntry):
455 | aliases = ['github.com', '*.github.com']
456 | # github.com is needed because repositories refer to github.com, not github
457 | hostname = 'github.com'
458 | hostKeyAlias = 'github-server-pool.github.com'
459 | user = 'git'
460 | # when pushing to my repositories I must use the git user
461 | identityFile = 'github.pub'
462 | trusted = False
463 | kexAlgorithms = ','.join([
464 | 'curve25519-sha256@libssh.org',
465 | 'diffie-hellman-group-exchange-sha256',
466 | 'diffie-hellman-group-exchange-sha1',
467 | 'diffie-hellman-group14-sha1'
468 | ])
469 |
470 | Second, when running on the machine with the older version of SSH, modern
471 | algorithms that are not supported by the older version must not be included in
472 | the generated SSH config file. The following *ssh.conf* file shows how to
473 | accomplish this:
474 |
475 | .. code-block:: python
476 |
477 | from sshconfig import gethostname
478 | from textwrap import dedent
479 |
480 | # Desired Algorithms
481 | ciphers = ','.join('''
482 | chacha20-poly1305@openssh.com aes256-gcm@openssh.com
483 | aes128-gcm@openssh.com aes256-ctr aes192-ctr aes128-ctr
484 | '''.split())
485 | macs = ','.join('''
486 | mac-sha2-512-etm@openssh.com hmac-sha2-256-etm@openssh.com
487 | umac-128-etm@openssh.com hmac-sha2-512 hmac-sha2-256 umac-128@openssh.com
488 | '''.split())
489 | host_key_algorithms = ','.join('''
490 | ssh-ed25519-cert-v01@openssh.com ssh-rsa-cert-v01@openssh.com
491 | ssh-ed25519,ssh-rsa
492 | '''.split())
493 | kex_algorithms = ','.join('''
494 | curve25519-sha256@libssh.org diffie-hellman-group-exchange-sha256
495 | '''.split())
496 |
497 | # Filter Algorithms
498 | if local_host_name in ['www', 'mail']:
499 | AVAILABLE_CIPHERS = '''
500 | 3des-cbc aes128-cbc aes192-cbc aes256-cbc aes128-ctr aes192-ctr
501 | aes256-ctr arcfour128 arcfour256 arcfour blowfish-cbc cast128-cbc
502 | '''.split()
503 | AVAILABLE_MACS = '''
504 | hmac-sha1 umac-64@openssh.com hmac-ripemd160 hmac-sha1-96
505 | hmac-sha2-256 hmac-sha2-512
506 | '''.split()
507 | AVAILABLE_HOST_KEY_ALGORITHMS = '''
508 | ssh-rsa-cert-v01@openssh.com ssh-dss-cert-v01@openssh.com
509 | ssh-rsa-cert-v00@openssh.com ssh-dss-cert-v00@openssh.com ssh-rsa
510 | ssh-ds
511 | '''.split()
512 | AVAILABLE_KEX_ALGORITHMS = '''
513 | diffie-hellman-group-exchange-sha256
514 | diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1
515 | diffie-hellman-group1-sha1
516 | '''.split()
517 |
518 | def filter_algorithms(desired, available):
519 | if available is None:
520 | return desired
521 | return [d for d in desired.split(',') if d in available]
522 |
523 | ciphers = ','.join(
524 | filter_algorithms(ciphers, AVAILABLE_CIPHERS)
525 | )
526 | macs = ','.join(
527 | filter_algorithms(macs, AVAILABLE_MACS)
528 | )
529 | host_key_algorithms = ','.join(
530 | filter_algorithms(host_key_algorithms, AVAILABLE_HOST_KEY_ALGORITHMS)
531 | )
532 | kex_algorithms = ','.join(
533 | filter_algorithms(kex_algorithms, AVAILABLE_KEX_ALGORITHMS)
534 | )
535 |
536 | DEFAULTS = dedent("""
537 | host *
538 | # Use stronger algorithms
539 | ciphers {ciphers}
540 | MACs {macs}
541 | hostKeyAlgorithms {host_key_algorithms}
542 | kexAlgorithms {kex_algorithms}
543 | """.format(**locals()))
544 |
545 | In this example, the desired algorithms are given first. Then, the algorithms
546 | supported by the older SSH server are given. These can be found by using ``sss
547 | -Q``, or if you version of SSH is too old to support the ``-Q`` option, they can
548 | be found by scouring the *ssh_config* man page. The variable used for the
549 | available algorithms (those in all caps) are interpreted by *sshconfig*. Any
550 | algorithm that is not specified as being available is stripped from a host entry
551 | when generating the SSH config file. If you do not specify from these variables,
552 | or if they are empty, then no filtering is performed. The available algorithms
553 | are only defined on the older hosts. That is why this section is embedded in
554 | a conditional that is only executed when if local_host_name is either ``www`` or
555 | ``mail``. These are the hosts with the old version of SSH.
556 |
557 | One more thing to look out for when using older versions of SSH; they may not
558 | support the *proxyJump* setting. You can generally use ``ProxyCommand "ssh
559 | -W %h:%p"`` instead.
560 |
561 |
562 |
--------------------------------------------------------------------------------
/doc/figures/makeall:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from shlib import lsf, Run, set_prefs
4 | from inform import Error
5 | set_prefs(use_inform=True)
6 |
7 | for py_file in lsf(select='*.py'):
8 | print(str(py_file))
9 | cmd = ['python3', py_file]
10 | try:
11 | Run(cmd, 'soEW')
12 | except Error as e:
13 | e.report()
14 |
--------------------------------------------------------------------------------
/doc/figures/network-map.py:
--------------------------------------------------------------------------------
1 | from svg_schematic import Schematic, Box, Wire, Label, shift_x, shift_y
2 |
3 |
4 | with Schematic(filename='network-map.svg', line_width=2):
5 | # work network
6 | work = Box(w=6.5, h=4.5, stroke_dasharray="4 2")
7 | Label(C=work.SW, loc='ne', name='work')
8 | bastion = Box(S=work.S, yoff=-25, w=5.5, h=2, color='lightgray')
9 | Wire([bastion.E, shift_x(bastion.E, 75)])
10 | Label(C=bastion.SW, loc='ne', name='bastion')
11 | www = Box(NE=bastion.N, off=(-12.5, 25), w=2, h=1, color='white', name='www')
12 | # Wire([www.W, shift_x(www.W, -25)])
13 | mail = Box(NW=bastion.N, off=(12.5, 25), w=2, h=1, color='white', name='mail')
14 | # Wire([mail.E, shift_x(mail.E, 25)])
15 | dump = Box(SW=bastion.NW, yoff=-25, w=2.5, h=1, name='dump')
16 | # Wire([dump.N, shift_y(dump.N, -25)])
17 | laptop = Box(SE=bastion.NE, yoff=-25, w=2.5, h=1, name='my laptop', stroke_dasharray="2 2")
18 | # Wire([laptop.N, shift_y(laptop.N, -25)])
19 | # Wire([work.E, shift_x(work.E, 50)])
20 |
21 | # home network
22 | home = Box(N=work.S, yoff=50, w=6.5, h=2, stroke_dasharray="4 2")
23 | Label(C=home.SW, loc='ne', name='home')
24 | laptop = Box(SW=home.SW, off=(25, -25), w=2.5, h=1, color='lightgray', name='my laptop', stroke_dasharray="2 2")
25 | # Wire([laptop.N, shift_y(laptop.N, -25)])
26 | media = Box(SE=home.SE, off=(-25, -25), w=2.5, h=1, name='media')
27 | # Wire([media.N, shift_y(media.N, -25)])
28 | Wire([media.E, shift_x(media.E, 75)])
29 |
30 | # internet
31 | internet = Wire([shift_x(work.NE, 50), shift_x(home.SE, 50)], line_width=4)
32 | Label(C=internet.e, loc='s', name='internet')
33 |
34 | # external network
35 | github = Box(NW=internet.b, off=(50, 25), w=3, h=1, name='github')
36 | Wire([github.W, shift_x(github.W, -50)])
37 | cloud = Box(N=github.S, yoff=25, w=3, h=1, name='vps')
38 | Wire([cloud.W, shift_x(cloud.W, -50)])
39 | backups = Box(N=cloud.S, yoff=25, w=3, h=1, name='backups')
40 | Wire([backups.W, shift_x(backups.W, -50)])
41 | hotspot = Box(N=backups.S, yoff=25, w=3, h=2, stroke_dasharray="4 2")
42 | # Wire([hotspot.W, shift_x(hotspot.W, -50)])
43 | Label(C=hotspot.SW, loc='ne', name='a wifi hotspot')
44 | laptop = Box(C=hotspot.C, w=2, h=1, name='my laptop', stroke_dasharray="2 2")
45 | # Wire([laptop.N, shift_y(laptop.N, -25)])
46 |
--------------------------------------------------------------------------------
/doc/figures/network-map.svg:
--------------------------------------------------------------------------------
1 |
2 |
146 |
--------------------------------------------------------------------------------
/doc/figures/proxy1.py:
--------------------------------------------------------------------------------
1 | from svg_schematic import Schematic, Box, Wire, Label, midpoint, shift_y
2 |
3 | with Schematic(filename='proxy1.svg', line_width=2, background='none'):
4 | client = Box(w=5, h=2, name='SSH Client')
5 | server = Box(W=client.E, xoff=150, w=5, h=2, name='SSH Server', value='NNN.NNN.NNN.NNN:PPP')
6 | Wire([client.E, server.W])
7 | Label(C=server.W, kind='arrow|', loc='W')
8 | fw = midpoint(client.E, server.W)
9 | FW = Wire([shift_y(fw, 100), shift_y(fw, -100)], stroke_dasharray="4 4")
10 | Label(C=FW.b, kind='none', loc='S', name='firewall')
11 | Label(C=FW.b, yoff=20, kind='none', loc='S', name='blocks port 22')
12 |
--------------------------------------------------------------------------------
/doc/figures/proxy1.svg:
--------------------------------------------------------------------------------
1 |
2 |
43 |
--------------------------------------------------------------------------------
/doc/figures/proxy2.py:
--------------------------------------------------------------------------------
1 | from svg_schematic import Schematic, Box, Wire, Label, midpoint, shift_y
2 |
3 | with Schematic(filename='proxy2.svg', line_width=2, background='none'):
4 | client = Box(w=5, h=2, name='SSH Client')
5 | proxy = Box(W=client.E, xoff=150, w=5, h=2, name='Remote Proxy', value='MMM.MMM.MMM.MMM:PPP')
6 | server = Box(W=proxy.E, xoff=50, w=5, h=2, name='SSH Server', value='localhost:22')
7 | Box(W=client.E, xoff=100, w=12.5, h=3, stroke_dasharray="4 4")
8 | Wire([client.E, proxy.W])
9 | Wire([proxy.E, server.W])
10 | Label(C=proxy.W, kind='arrow|', loc='W')
11 | Label(C=server.W, kind='arrow|', loc='W')
12 | fw = midpoint(client.E, proxy.W)
13 | FW = Wire([shift_y(fw, 100), shift_y(fw, -100)], stroke_dasharray="4 4")
14 | Label(C=FW.b, kind='none', loc='S', name='firewall')
15 | Label(C=FW.b, yoff=20, kind='none', loc='S', name='blocks port 22')
16 |
--------------------------------------------------------------------------------
/doc/figures/proxy2.svg:
--------------------------------------------------------------------------------
1 |
2 |
64 |
--------------------------------------------------------------------------------
/doc/figures/proxy3.py:
--------------------------------------------------------------------------------
1 | from svg_schematic import Schematic, Box, Wire, Label, midpoint, shift_y
2 |
3 | with Schematic(filename='proxy3.svg', line_width=2, background='none'):
4 | client = Box(w=5, h=2, name='SSH Client')
5 | lproxy = Box(W=client.E, xoff=50, w=5, h=2, name='Pass Through Proxy', value='MMM.MMM.MMM.MMM:LPP')
6 | rproxy = Box(W=lproxy.E, xoff=150, w=5, h=2, name='Remote Proxy', value='NNN.NNN.NNN.NNN:RPP')
7 | server = Box(W=rproxy.E, xoff=50, w=5, h=2, name='SSH Server', value='localhost:22')
8 | Box(W=rproxy.W, xoff=-50, w=12.5, h=3, stroke_dasharray="4 4")
9 | Wire([client.E, lproxy.W])
10 | Wire([shift_y(client.E, -12), shift_y(lproxy.W, -12)], stroke_dasharray="4 8")
11 | Wire([shift_y(client.E, 12), shift_y(lproxy.W, 12)], stroke_dasharray="4 8")
12 | Wire([lproxy.E, rproxy.W])
13 | Wire([shift_y(lproxy.E, -12), shift_y(rproxy.W, -12)], stroke_dasharray="4 8")
14 | tunnel = Wire([shift_y(lproxy.E, 12), shift_y(rproxy.W, 12)], stroke_dasharray="4 8")
15 | Label(C=tunnel.m, kind='none', loc='S', name='TLS tunnel')
16 | Wire([rproxy.E, server.W])
17 | Label(C=rproxy.W, kind='arrow|', loc='W')
18 | Label(C=server.W, kind='arrow|', loc='W')
19 | fw_n = Wire([lproxy.N, shift_y(lproxy.N, -50)], stroke_dasharray="4 4")
20 | fw_s = Wire([lproxy.S, shift_y(lproxy.S, 50)], stroke_dasharray="4 4")
21 | Label(C=fw_s.e, kind='none', loc='S', name='firewall')
22 | Label(C=fw_s.e, yoff=20, kind='none', loc='S', name='blocks all ports')
23 |
--------------------------------------------------------------------------------
/doc/figures/proxy3.svg:
--------------------------------------------------------------------------------
1 |
2 |
96 |
--------------------------------------------------------------------------------
/doc/index.rst:
--------------------------------------------------------------------------------
1 | SSH Config
2 | ==========
3 |
4 | :Author: Ken Kundert
5 | :Version: 2.2.1
6 | :Released: 2023-11-08
7 |
8 |
9 | Introduction
10 | ------------
11 |
12 | SSH Config generates an SSH config file adapted to the network you are currently
13 | using. In this way, you always use the fastest paths available for your SSH
14 | related activities (sshfs, email, vnc, mercurial, etc.). You can also easily
15 | reconfigure SSH to make use of proxies as needed or select certain servers or
16 | ports based on your location or restrictions with the network.
17 |
18 | The following situations are supported:
19 |
20 | #. You may give the mac address or addresses for your router or routers and your
21 | network will automatically be recognized.
22 | #. You can configure which hostname or IP address is used for a particular host
23 | depending on which network you are on. In this way you always use the fastest
24 | connection available for each host.
25 | #. You can specify that certain hosts are hidden behind other hosts, so that
26 | a SSH proxy should be used to access them.
27 | #. You can specify port forwarding information for each host. Then, two SSH
28 | configurations will be created for those hosts, one that includes port
29 | forwarding and one that does not. That way, once the port forwards are
30 | established, you can open additional shells on that host without SSH trying
31 | to create conflicting port forwards.
32 | #. You can enter multiple hostnames or IP addresses and give their locations.
33 | Then, if you specify your location, the closest server will be used
34 | automatically.
35 | #. You can specify proxy configurations and specify that one should be used for
36 | all hosts not on your current network.
37 | #. You can specify port restrictions and have SSH work around them if possible
38 | (if your server supports alternative ports).
39 | #. You can configure a default location, proxy, or set of port restrictions for
40 | each of your known networks.
41 | #. Once host names are defined, they do not change even though you are using
42 | different configurations (different networks, locations, proxies, and port
43 | restrictions). In this way you can hard code your host names in applications
44 | such as Mercurial or Git, and they automatically adapt to your existing
45 | network.
46 | #. The entire application, including the configuration files, are Python code,
47 | so you have considerable freedom to change the configuration based on things
48 | like the name of the machine or the user when generating the SSH config file.
49 |
50 |
51 | Trivial Configuration
52 | ---------------------
53 |
54 | The hosts that you would like to connect to are described in the hosts.conf
55 | file. A very simple hosts.conf file would look like this:
56 |
57 | .. code-block:: python
58 |
59 | from sshconfig import HostEntry
60 |
61 | class Zeebra(HostEntry):
62 | user = 'herbie'
63 | hostname = 'zeebra.he.net'
64 |
65 | Hosts are described by directly subclassing HostEntry. Attributes are added
66 | that are generally converted to fields in the SSH config file.
67 |
68 | The contents of ~/.ssh/config are replaced when you run::
69 |
70 | sshconfig
71 |
72 | The above hosts.conf file is converted into the following SSH config file::
73 |
74 | # SSH Configuration for unknown network
75 | # Generated at 1:04 PM on 22 July 2014.
76 |
77 | #
78 | # HOSTS
79 | #
80 |
81 | host zeebra
82 | user herbie
83 | hostname zeebra.he.net
84 | forwardAgent no
85 |
86 | The transformation between a host entry in the hosts.conf file and the SSH
87 | config file could be affected by the network you are on and any command line
88 | options that are specified to *sshconfig*, but in this case it is not. Notice
89 | that the class name is converted to lower case when creating the hostname.
90 |
91 | In most cases, adding an attribute to the definition of your host simply results
92 | in that attribute being added the the SSH configuration, so:
93 |
94 | .. code-block:: python
95 |
96 | class Zeebra(HostEntry):
97 | user = 'herbie'
98 | hostname = 'zeebra.he.net'
99 | port = 22022
100 |
101 | becomes::
102 |
103 | host zeebra
104 | user herbie
105 | hostname zeebra.he.net
106 | port 22022
107 | forwardAgent no
108 |
109 |
110 | Installation Requirements
111 | -------------------------
112 |
113 | You can download and install the latest
114 | stable version of the code from `PyPI `_ using::
115 |
116 | pip3 install --user sshconfig
117 |
118 | You can find the latest development version of the source code on
119 | `Github `_.
120 |
121 | Requires in Python3.6 or later.
122 |
123 |
124 | Related Software
125 | ----------------
126 |
127 | `AddSSHKeys `_ is a Python utility
128 | that allows you to add all of your SSH keys to your agent in one go.
129 |
130 |
131 | Issues
132 | ------
133 |
134 | Please ask questions or report problems on
135 | `Github Issues `_.
136 |
137 |
138 | Contents
139 | --------
140 |
141 | .. toctree::
142 | :maxdepth: 1
143 |
144 | commands
145 | configuring
146 | examples
147 | releases
148 |
149 | * :ref:`genindex`
150 |
--------------------------------------------------------------------------------
/doc/network-map.py:
--------------------------------------------------------------------------------
1 | from svg_schematic import Schematic, Box, Wire, Label, shift_x, shift_y
2 |
3 |
4 | with Schematic(filename='network-map.svg', line_width=2):
5 | # work network
6 | work = Box(w=6.5, h=4.5, stroke_dasharray="4 2")
7 | Label(C=work.SW, loc='ne', name='work')
8 | bastion = Box(S=work.S, yoff=-25, w=5.5, h=2, color='lightgray')
9 | Wire([bastion.E, shift_x(bastion.E, 75)])
10 | Label(C=bastion.SW, loc='ne', name='bastion')
11 | www = Box(NE=bastion.N, off=(-12.5, 25), w=2, h=1, color='white', name='www')
12 | # Wire([www.W, shift_x(www.W, -25)])
13 | mail = Box(NW=bastion.N, off=(12.5, 25), w=2, h=1, color='white', name='mail')
14 | # Wire([mail.E, shift_x(mail.E, 25)])
15 | dump = Box(SW=bastion.NW, yoff=-25, w=2.5, h=1, name='dump')
16 | # Wire([dump.N, shift_y(dump.N, -25)])
17 | laptop = Box(SE=bastion.NE, yoff=-25, w=2.5, h=1, name='my laptop', stroke_dasharray="2 2")
18 | # Wire([laptop.N, shift_y(laptop.N, -25)])
19 | # Wire([work.E, shift_x(work.E, 50)])
20 |
21 | # home network
22 | home = Box(N=work.S, yoff=50, w=6.5, h=2, stroke_dasharray="4 2")
23 | Label(C=home.SW, loc='ne', name='home')
24 | laptop = Box(SW=home.SW, off=(25, -25), w=2.5, h=1, color='lightgray', name='my laptop', stroke_dasharray="2 2")
25 | # Wire([laptop.N, shift_y(laptop.N, -25)])
26 | media = Box(SE=home.SE, off=(-25, -25), w=2.5, h=1, name='media')
27 | # Wire([media.N, shift_y(media.N, -25)])
28 | Wire([media.E, shift_x(media.E, 75)])
29 |
30 | # internet
31 | internet = Wire([shift_x(work.NE, 50), shift_x(home.SE, 50)], line_width=4)
32 | Label(C=internet.e, loc='s', name='internet')
33 |
34 | # external network
35 | github = Box(NW=internet.b, off=(50, 25), w=3, h=1, name='github')
36 | Wire([github.W, shift_x(github.W, -50)])
37 | cloud = Box(N=github.S, yoff=25, w=3, h=1, name='vps')
38 | Wire([cloud.W, shift_x(cloud.W, -50)])
39 | backups = Box(N=cloud.S, yoff=25, w=3, h=1, name='backups')
40 | Wire([backups.W, shift_x(backups.W, -50)])
41 | hotspot = Box(N=backups.S, yoff=25, w=3, h=2, stroke_dasharray="4 2")
42 | # Wire([hotspot.W, shift_x(hotspot.W, -50)])
43 | Label(C=hotspot.SW, loc='ne', name='a wifi hotspot')
44 | laptop = Box(C=hotspot.C, w=2, h=1, name='my laptop', stroke_dasharray="2 2")
45 | # Wire([laptop.N, shift_y(laptop.N, -25)])
46 |
--------------------------------------------------------------------------------
/doc/network-map.svg:
--------------------------------------------------------------------------------
1 |
2 |
146 |
--------------------------------------------------------------------------------
/doc/releases.rst:
--------------------------------------------------------------------------------
1 | Releases
2 | ========
3 |
4 | Latest development release
5 | --------------------------
6 |
7 | | Version: 2.2.1
8 | | Released: 2023-11-08
9 |
10 | - Added *nmcli_connection* attribute to the *NetworkEntry* class.
11 | - Added *NMCLI_CONNS* setting.
12 |
13 | Both these changes support the use of secondary networks, meaning that if your
14 | machine is connected to multiple networks, you can configure a host so that ssh
15 | connects to it directly through a secondary network rather than using the
16 | primary gateway.
17 |
18 |
19 | 2.3 (2024-11-??)
20 | ----------------
21 | - Add folding to generated ~/.ssh/config file.
22 |
23 |
24 | 2.2 (2022-11-19)
25 | ----------------
26 | - Make path to arp command user settable.
27 |
28 |
29 | 2.1 (2021-01-18)
30 | ----------------
31 | - Make path to arp command user settable.
32 |
33 |
34 | 2.1 (2021-01-18)
35 | ----------------
36 | - Improved the documentation.
37 |
38 |
39 | 2.0 (2020-04-16)
40 | ----------------
41 | - Improve documentation.
42 |
43 |
44 | 1.3 (2020-03-11)
45 | ----------------
46 | - Add available SSH algorithms filtering.
47 | - Make SSH settings case insensitive.
48 | - Added shared config files examples.
49 | - Refine *identityfile* behavior.
50 | - Eliminate *tun_trusted*.
51 |
52 |
53 | 1.2 (2020-01-07)
54 | ----------------
55 | - Configuration is now external to the program source code
56 | (it is now in ``~/.config/sshconfig``).
57 |
--------------------------------------------------------------------------------
/doc/requirements.txt:
--------------------------------------------------------------------------------
1 | sphinx>=6.0.0
2 | sphinx-rtd-theme>=1.2.0
3 |
--------------------------------------------------------------------------------
/doc/spell:
--------------------------------------------------------------------------------
1 | #!/bin/csh -f
2 |
3 | foreach f (*.rst ../README.rst)
4 | echo "=== ${f} ==="
5 | rstspell $f
6 | end
7 |
8 | # Use 'rstspell -u filename.rst' to update the exceptions file.
9 |
--------------------------------------------------------------------------------
/examples/unlock-peets:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | #
3 | # Unlock Peet's WiFi
4 | #
5 | # Peet's has an annoying click through that forces you to accept the terms and
6 | # conditions. This program uses mechanize to automate this process.
7 |
8 | from __future__ import print_function
9 | from mechanize import Browser, BrowserStateError, LinkNotFoundError
10 | # mechanize is not yet available for python3
11 | import sys
12 |
13 | # This url should return the country code of Mount Denali, which is 'US'.
14 | # This is one of any number of URLs that could be used for this purpose. We just
15 | # need one that does not employ SSL and has an easily recognizable result.
16 | test_url = 'http://api.geonames.org/countryCode?' + '&'.join([
17 | 'lat=63.069', # latitude of Denali
18 | 'lng=-151.0', # longitude of Denali
19 | 'username=transfix', # name of an account I created
20 | ])
21 |
22 | # Activate mechanize
23 | browser = Browser()
24 | browser.set_handle_robots(False)
25 |
26 | # Determine whether network is already unlocked
27 | resp = browser.open(test_url)
28 | if 'US' == resp.get_data().strip().upper():
29 | # We received the expected result, this would only happen if the network was
30 | # already unlocked.
31 | print("Peet's wifi is already unlocked.")
32 | sys.exit()
33 |
34 | try:
35 | # We did not receive the result, meaning that we should have been redirected
36 | # to the terms and conditions page, and we simply need to accept them.
37 | # This is done by looking for the link that contains 'continue_url' and
38 | # following it (clicking on it).
39 | links = list(browser.links(url_regex='.*continue_url.*'))
40 | assert len(links) == 1
41 | resp = browser.follow_link(links[0])
42 | assert resp.code == 200
43 | print("Peet's wifi successfully unlocked.")
44 |
45 | except (AssertionError, BrowserStateError, LinkNotFoundError):
46 | print('Whoops, something is wrong. Cannot find accept button. Response saved to resp.html.')
47 | page = resp.get_data()
48 | with open('resp.html', 'w') as f:
49 | f.write(page)
50 |
--------------------------------------------------------------------------------
/install:
--------------------------------------------------------------------------------
1 | #!/bin/csh -f
2 | set supportedPythonVersions=(3)
3 | set packageName=sshconfig
4 |
5 | rm -f install.out
6 |
7 | foreach vers ($supportedPythonVersions)
8 | # remove build directory from a previous install to assure a clean install
9 | rm -rf build
10 |
11 | which python$vers >& /dev/null
12 | if ($status == 0) then
13 | echo "Installing $packageName to Python$vers."
14 | python$vers setup.py install --quiet --user >>& install.out
15 | if ($status) then
16 | echo "Problems found, aborting (see install.out)"
17 | exit(1)
18 | endif
19 | else
20 | echo "Cannot install $packageName to Python$vers, it is not available."
21 | endif
22 | end
23 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from codecs import open
4 |
5 | from setuptools import setup
6 |
7 | with open("README.rst", encoding="utf-8") as f:
8 | readme = f.read()
9 |
10 | setup(
11 | name = "sshconfig",
12 | version = "2.2.1",
13 | author = "Ken Kundert",
14 | author_email = "sshconfig@nurdletech.com",
15 | description = "SSH config file generator",
16 | long_description = readme,
17 | long_description_content_type = 'text/x-rst',
18 | url = "https://sshconfig.readthedocs.io",
19 | download_url = "https://github.com/kenkundert/sshconfig/tarball/master",
20 | license = "GPLv3+",
21 | packages = "sshconfig".split(),
22 | entry_points = {"console_scripts": ["sshconfig=sshconfig.main:main"]},
23 | install_requires = "appdirs arrow docopt inform shlib".split(),
24 | python_requires = ">=3.6",
25 | zip_safe = True,
26 | keywords = "ssh".split(),
27 | classifiers = [
28 | "Development Status :: 5 - Production/Stable",
29 | "Intended Audience :: Developers",
30 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
31 | "Natural Language :: English",
32 | "Operating System :: POSIX :: Linux",
33 | "Programming Language :: Python :: 3.6",
34 | "Programming Language :: Python :: 3.7",
35 | "Programming Language :: Python :: 3.8",
36 | "Programming Language :: Python :: 3.9",
37 | "Programming Language :: Python :: 3.10",
38 | "Topic :: Utilities",
39 | ],
40 | )
41 |
--------------------------------------------------------------------------------
/sshconfig/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = "2.2.1"
2 | __released__ = "2023-11-08"
3 |
4 | from .sshconfig import (
5 | VNC,
6 | HostEntry,
7 | NetworkEntry,
8 | filter_algorithms,
9 | get_network_name,
10 | is_ip_addr,
11 | locations,
12 | ports,
13 | )
14 | from .utilities import gethostname, getusername
15 |
--------------------------------------------------------------------------------
/sshconfig/command.py:
--------------------------------------------------------------------------------
1 | # Commands
2 |
3 | # License {{{1
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see http://www.gnu.org/licenses/.
16 |
17 |
18 | # Imports {{{1
19 | import sys
20 | from textwrap import dedent
21 |
22 | import arrow
23 | from docopt import docopt
24 |
25 | from inform import Error, columns, display, full_stop, narrate, output
26 |
27 | from .preferences import (
28 | DATE_FORMAT,
29 | DEFAULT_COMMAND,
30 | SSH_DEFAULTS,
31 | SSH_HEADER,
32 | SSH_HOSTS,
33 | SSH_OVERRIDES,
34 | fold
35 | )
36 | from .sshconfig import NetworkEntry
37 | from .utilities import two_columns
38 |
39 |
40 | # Utilities {{{1
41 | # title() {{{2
42 | def title(text):
43 | return full_stop(text.capitalize())
44 |
45 |
46 | # Command base class {{{1
47 | class Command(object):
48 | @classmethod
49 | def commands(cls):
50 | for cmd in cls.__subclasses__():
51 | if hasattr(cmd, "NAMES"):
52 | yield cmd
53 | for sub in cmd.commands():
54 | if hasattr(sub, "NAMES"):
55 | yield sub
56 |
57 | @classmethod
58 | def commands_sorted(cls):
59 | for cmd in sorted(cls.commands(), key=lambda c: c.get_name()):
60 | yield cmd
61 |
62 | @classmethod
63 | def find(cls, name):
64 | if not name:
65 | name = DEFAULT_COMMAND
66 | for command in cls.commands():
67 | if name in command.NAMES:
68 | return command, command.NAMES[0]
69 | raise Error("unknown command.", culprit=name)
70 |
71 | @classmethod
72 | def execute(cls, name, args, settings, options):
73 | if hasattr(cls, "run"):
74 | narrate("running {} command".format(name))
75 | exit_status = cls.run(name, args if args else [], settings, options)
76 | return 0 if exit_status is None else exit_status
77 |
78 | @classmethod
79 | def summarize(cls, width=16):
80 | summaries = []
81 | for cmd in Command.commands_sorted():
82 | summaries.append(two_columns(", ".join(cmd.NAMES), cmd.DESCRIPTION))
83 | return "\n".join(summaries)
84 |
85 | @classmethod
86 | def get_name(cls):
87 | return cls.NAMES[0]
88 |
89 | @classmethod
90 | def help(cls):
91 | text = dedent(
92 | """
93 | {title}
94 |
95 | {usage}
96 | """
97 | ).strip()
98 |
99 | return text.format(title=title(cls.DESCRIPTION), usage=cls.USAGE)
100 |
101 |
102 | # CreateCommand command {{{1
103 | class CreateCommand(Command):
104 | NAMES = "create".split()
105 | DESCRIPTION = "create an SSH config file"
106 | USAGE = dedent(
107 | """
108 | Usage:
109 | sshconfig create
110 | """
111 | ).strip()
112 |
113 | @classmethod
114 | def run(cls, command, args, settings, options):
115 | # read command line
116 | docopt(cls.USAGE, argv=[command] + args)
117 |
118 | # display summary
119 | display(full_stop(settings.get_summary()))
120 |
121 | # initialize the network
122 | settings.initialize_network()
123 | # initializing the network must be done before reading the hosts
124 | # file as it may try to do network operations
125 |
126 | # create SSH config file components
127 | # header
128 | name = settings.primary_network.Name()
129 | desc = settings.primary_network.description
130 | if desc:
131 | network = f"{name} network — {desc}"
132 | else:
133 | network = f"{name} network"
134 | now = arrow.now()
135 | time = now.format(DATE_FORMAT)
136 | header = SSH_HEADER.format(
137 | network=network, time=time, config_dir=settings.config_dir
138 | )
139 |
140 | # overrides
141 | overrides = settings.ssh_overrides
142 | if overrides:
143 | overrides = SSH_OVERRIDES.format(overrides=overrides, fold=fold(1))
144 |
145 | # hosts
146 | settings.read_hosts()
147 | hosts = SSH_HOSTS.format(hosts=settings.hosts.output(), fold=fold(1))
148 |
149 | # defaults
150 | defaults = settings.ssh_defaults
151 | if defaults:
152 | defaults = SSH_DEFAULTS.format(defaults=defaults, fold=fold(1))
153 |
154 | # combine everything and write as SSH config file
155 | contents = "\n\n\n".join(
156 | section.strip()
157 | for section in [header, overrides, hosts, defaults]
158 | if section
159 | )
160 | settings.write_ssh_config(contents + '\n')
161 |
162 |
163 | # FindCommand command {{{1
164 | class FindCommand(Command):
165 | NAMES = "find".split()
166 | DESCRIPTION = "find SSH host configurations whose names contains a substring"
167 | USAGE = dedent(
168 | """
169 | Usage:
170 | sshconfig find
171 | """
172 | ).strip()
173 |
174 | @classmethod
175 | def run(cls, command, args, settings, options):
176 | # read command line
177 | cmdline = docopt(cls.USAGE, argv=[command] + args)
178 | text = cmdline[""]
179 |
180 | # display matches
181 | settings.read_hosts()
182 | for name in settings.hosts.hosts_by_name.keys():
183 | if text in name:
184 | display(name)
185 |
186 |
187 | # HelpCommand {{{1
188 | class HelpCommand(Command):
189 | NAMES = "help".split()
190 | DESCRIPTION = "give information about commands or other topics"
191 | USAGE = dedent(
192 | """
193 | Usage:
194 | sshconfig help []
195 | """
196 | ).strip()
197 | REQUIRES_EXCLUSIVITY = False
198 | COMPOSITE_CONFIGS = None
199 |
200 | @classmethod
201 | def run(cls, command, args, settings, options):
202 | # read command line
203 | cmdline = docopt(cls.USAGE, argv=[command] + args)
204 |
205 | from .help import HelpMessage
206 |
207 | HelpMessage.show(cmdline[""])
208 | return 0
209 |
210 |
211 | # AvailableCommand command {{{1
212 | class AvailableCommand(Command):
213 | NAMES = "available".split()
214 | DESCRIPTION = "list available choices for command line options"
215 | USAGE = dedent(
216 | """
217 | Usage:
218 | sshconfig available
219 | """
220 | ).strip()
221 |
222 | @classmethod
223 | def run(cls, command, args, settings, options):
224 | # read command line
225 | docopt(cls.USAGE, argv=[command] + args)
226 |
227 | display("Explicit proxies (you can also use SSH hosts as proxies):")
228 | display(columns(sorted(settings.proxies.keys())))
229 | display()
230 |
231 | display("Locations:")
232 | for loc in sorted(settings.locations.keys()):
233 | display(
234 | loc=loc,
235 | desc=settings.locations[loc],
236 | template=[" {loc}: {desc}", " {loc}"],
237 | )
238 | display()
239 |
240 | display("Networks:")
241 | for nw in sorted(NetworkEntry.all_networks(), key=lambda n: n.name()):
242 | display(
243 | nw=nw.name(), desc=nw.desc(), template=[" {nw}: {desc}", " {nw}"]
244 | )
245 | display(" unknown: a generic unknown network")
246 | display()
247 |
248 |
249 | # ShowCommand command {{{1
250 | class ShowCommand(Command):
251 | NAMES = "show".split()
252 | DESCRIPTION = "show an SSH host configuration"
253 | USAGE = dedent(
254 | """
255 | Usage:
256 | sshconfig show
257 | """
258 | ).strip()
259 |
260 | @classmethod
261 | def run(cls, command, args, settings, options):
262 | # read command line
263 | cmdline = docopt(cls.USAGE, argv=[command] + args)
264 | name = cmdline[""]
265 |
266 | # display summary
267 | display(full_stop(settings.get_summary()))
268 | display()
269 |
270 | # display host
271 | settings.read_hosts()
272 | try:
273 | display(settings.hosts.hosts_by_name[name])
274 | except KeyError:
275 | raise Error("not found.", culprit=name)
276 |
277 |
278 | # VersionCommand {{{1
279 | class VersionCommand(Command):
280 | NAMES = ("version",)
281 | DESCRIPTION = "display sshconfig version"
282 | USAGE = dedent(
283 | """
284 | Usage:
285 | sshconfig version
286 | """
287 | ).strip()
288 |
289 | @classmethod
290 | def run(cls, command, args, settings, options):
291 |
292 | # get the Python version
293 | python = "Python %s.%s.%s" % (
294 | sys.version_info.major,
295 | sys.version_info.minor,
296 | sys.version_info.micro,
297 | )
298 |
299 | # output the SSHconfig version along with the Python version
300 | from .__init__ import __version__, __released__
301 |
302 | output("sshconfig version: %s (%s) [%s]." % (__version__, __released__, python))
303 |
--------------------------------------------------------------------------------
/sshconfig/core.py:
--------------------------------------------------------------------------------
1 | # Core internal classes and functions
2 |
3 | # Imports {{{1
4 | import re
5 |
6 | from inform import display, indent, is_str, warn
7 | from shlib import to_path
8 |
9 | from .preferences import DEFAULT_NETWORK_NAME, SSH_SETTINGS, fold
10 | from .sshconfig import NetworkEntry
11 |
12 |
13 | # Fields Class {{{1
14 | class Fields:
15 | def __init__(self):
16 | self.fields = []
17 |
18 | def append(self, field):
19 | if field:
20 | self.fields.append(field)
21 |
22 | def _format_field(self, field):
23 | comment_leader = "\n # "
24 | key, value, desc = field
25 | if key.lower() not in SSH_SETTINGS:
26 | warn('unknown SSH setting.', culprit=key)
27 | key = SSH_SETTINGS.get(key.lower(), key)
28 | if value is True:
29 | value = 'yes'
30 | elif value is False:
31 | value = 'no'
32 | text = " {} {}".format(key, value)
33 | if desc:
34 | if not isinstance(desc, list):
35 | desc = [desc]
36 | text += comment_leader + comment_leader.join(desc)
37 | return text
38 |
39 | # Iterate through fields, converting them to strings
40 | def render_host(self):
41 | return [self._format_field(field) for field in self.fields]
42 |
43 | # Iterate through fields, converting them to strings while replacing
44 | # hostname with that of guest and adding proxy through host
45 | def render_guest(self, guestname, name):
46 | # guest are assumed to always use port 22
47 | fields = [
48 | ("hostname", guestname, None),
49 | (
50 | "proxyCommand",
51 | "ssh {} -W {}:22".format(name, guestname),
52 | # on old centos servers this is 'ssh {} nc {} 22'
53 | "Use {} as a proxy to access {}".format(name, guestname),
54 | ),
55 | ] + [
56 | (key, val, desc)
57 | for key, val, desc in self.fields
58 | if key not in ["hostname", "port"]
59 | ]
60 | return [self._format_field(field) for field in fields]
61 |
62 |
63 | # Attributes Class {{{1
64 | class Attributes:
65 | def __init__(self, attributes):
66 | # Copy attributes while converting to a simple dictionary.
67 | # It is important that we copy because attributes will be deleted in this
68 | # function and it is important that this not have side effects.
69 | self.attributes = dict((k.lower(), v) for k, v in attributes.items())
70 |
71 | # return the attribute as a tuple containing key, value, desc
72 | def get(self, key, default=None):
73 | assert not isinstance(default, tuple)
74 | value = self.attributes.pop(key.lower(), default)
75 | if value is not default:
76 | if isinstance(value, tuple):
77 | assert len(value) == 2, value
78 | value, desc = value
79 | return key, value, desc
80 | else:
81 | return key, value, None
82 |
83 | # iterate through a list of attributes
84 | def getall(self, key):
85 | values = self.attributes.pop(key.lower(), [])
86 | for value in values:
87 | if isinstance(value, tuple):
88 | assert len(value) == 2
89 | value, desc = value
90 | yield key, value, desc
91 | else:
92 | yield key, value, None
93 |
94 | # remove an attribute
95 | def remove(self, key):
96 | self.attributes.pop(key.lower(), None)
97 |
98 | # iterate through remaining attributes
99 | def remaining(self):
100 | for key, value in self.attributes.items():
101 | if key != "guests" and key[0:1] != "_":
102 | if isinstance(value, tuple):
103 | assert len(value) == 2
104 | value, desc = value
105 | yield key, value, desc
106 | else:
107 | yield key, value, None
108 |
109 | # does an attribute exist
110 | def __contains__(self, key):
111 | return key.lower() in self.attributes
112 |
113 |
114 | # Hosts Class {{{1
115 | class Hosts:
116 | def __init__(self, networks, proxy, proxies, settings):
117 | self.networks = networks
118 | self.proxy = proxy
119 | self.proxies = proxies
120 | self.config_file = settings.ssh_config_file
121 | self.config_dir = settings.ssh_config_file.parent
122 | self.settings = settings
123 | self.hosts = []
124 | self.hosts_by_name = {}
125 |
126 | def _append(self, name, fields, aliases=None, desc=None, guests=None):
127 | # process primary host
128 | names_as_list = [name] + (aliases if aliases else [])
129 | names = " ".join(names_as_list)
130 | if desc:
131 | lines = desc.strip().splitlines()
132 | lines = [f"{lines[0]} {fold(2)}"] + lines[1:]
133 | desc = indent('\n'.join(lines), leader='# ')
134 | else:
135 | desc = f"# {names} {fold(2)}"
136 | header = f"{desc}\nhost {names}"
137 | host = "\n".join([header] + fields.render_host())
138 | self.hosts.append(host)
139 | for name in names_as_list:
140 | self.hosts_by_name[name] = host
141 |
142 | # process guests
143 | for guest in guests:
144 | key, guestname, desc = guest
145 | fullname = "-".join([name, guestname])
146 | if desc:
147 | header = "# {}\nhost {}".format(desc, fullname)
148 | else:
149 | header = "host {}".format(fullname)
150 | host = "\n".join([header] + fields.render_guest(guestname, name))
151 | self.hosts.append(host)
152 | self.hosts_by_name[fullname] = host
153 |
154 | def process(self, entry, forwards):
155 | fields = Fields()
156 |
157 | # Get fields
158 | attributes = Attributes(entry.fields())
159 | name = entry.__name__.lower()
160 | forwarding = False
161 |
162 | # Return if this is forwarding version and there are no forwards
163 | if forwards:
164 | if (
165 | "localForward" not in attributes
166 | and "remoteForward" not in attributes
167 | and "dynamicForward" not in attributes
168 | ):
169 | return
170 | name = "%s-tun" % name
171 | else:
172 | # Not interested in forwards, so remove them
173 | attributes.remove("localForward")
174 | attributes.remove("remoteForward")
175 | attributes.remove("dynamicForward")
176 |
177 | # Host description
178 | attribute = attributes.get("description")
179 | if attribute:
180 | key, value, desc = attribute
181 | description = (value + " (with port forwards)") if forwards else value
182 | else:
183 | description = None
184 |
185 | # Aliases
186 | aliases = [
187 | val + ("-tun" if forwards else "")
188 | for key, val, desc in attributes.getall("aliases")
189 | ]
190 |
191 | # User
192 | fields.append(attributes.get("user"))
193 |
194 | # Hostname
195 | attribute = attributes.get("hostname")
196 | if attribute:
197 | key, hostnames, desc = attribute
198 | if isinstance(hostnames, dict):
199 | unknown_networks = set(hostnames.keys()) - set(
200 | list(NetworkEntry.known()) + [DEFAULT_NETWORK_NAME]
201 | )
202 | if unknown_networks:
203 | display(
204 | "{}: uses unknown networks: {}".format(
205 | name, ", ".join(sorted(unknown_networks))
206 | )
207 | )
208 | for hn in hostnames:
209 | if hn in self.networks:
210 | hostname = hostnames[hn]
211 | break
212 | # if self.network in hostnames:
213 | # hostname = hostnames[self.network]
214 | else:
215 | if DEFAULT_NETWORK_NAME in hostnames:
216 | hostname = hostnames[DEFAULT_NETWORK_NAME]
217 | else:
218 | return
219 | attribute = key, hostname, desc
220 | else:
221 | hostnames = {}
222 | hostname = hostnames
223 | fields.append(attribute)
224 | else:
225 | hostname = "%h"
226 | hostnames = {}
227 |
228 | # Port
229 | attribute = attributes.get("port")
230 | if attribute:
231 | key, port, desc = attribute
232 | fields.append(attribute)
233 | else:
234 | port = "%p"
235 |
236 | # IdentityFile and IdentitiesOnly
237 | attribute = attributes.get("identityFile")
238 | if attribute:
239 | key, value, desc = attribute
240 | file_found = False
241 | if is_str(value):
242 | value = [value]
243 | for filename in value:
244 | filepath = to_path(self.config_dir, filename)
245 | if filepath.exists():
246 | file_found = True
247 | fields.append((key, filepath, desc))
248 | # Do not use filepath because it includes the config_dir
249 | # and so is an absolute path. That prevents the
250 | # generated config file from being copied to another
251 | # users account, which can help with bootstrapping that
252 | # account. It also results in relative paths being
253 | # used, which give a cleaner config file.
254 | #
255 | # Whoops, I take it all back. SSH is brain dead in that
256 | # it needs absolute paths in the config file. Relative
257 | # paths are relative to the directory where ssh is
258 | # invoked and not relative to the config file itself.
259 | if file_found:
260 | fields.append(('identitiesOnly', 'yes', None))
261 | fields.append(("pubkeyAuthentication", "yes", None))
262 | else:
263 | warn('no identity files found.', culprit=name)
264 |
265 | # ForwardAgent
266 | attribute = attributes.get("trusted")
267 | if attribute:
268 | key, trusted, desc = attribute
269 | else:
270 | trusted = False
271 | fields.append(("forwardAgent", trusted, None))
272 | # fields.append(('forwardX11', 'no' if trusted else 'no', None))
273 |
274 | # LocalForwards
275 | for attribute in attributes.getall("localForward"):
276 | check_forward(attribute)
277 | fields.append(attribute)
278 | forwarding = True
279 |
280 | # RemoteForwards
281 | for attribute in attributes.getall("remoteForward"):
282 | check_forward(attribute)
283 | fields.append(attribute)
284 | forwarding = True
285 |
286 | # DynamicForward
287 | attribute = attributes.get("dynamicForward")
288 | if attribute:
289 | check_forward(attribute, True)
290 | fields.append(attribute)
291 | forwarding = True
292 |
293 | # ExitOnForwardFailure
294 | if forwarding:
295 | fields.append(("exitOnForwardFailure", "yes", None))
296 |
297 | # ProxyCommand
298 | attribute = attributes.get("proxyCommand")
299 | network = NetworkEntry.find(self.networks[0])
300 | network_proxy = network.proxy if network else None
301 | if attribute:
302 | fields.append(attribute)
303 | elif self.proxy and not (
304 | self.proxy == entry.__name__.lower()
305 | or ((self.proxy == network_proxy) and (self.network in hostnames))
306 | ):
307 | # This host does not have a ProxyCommand entry, add it if a global
308 | # proxy is requested unless this host is the itself the proxy or if
309 | # this host is on the same network as the proxy.
310 | # Specifically, do not use a proxy if proxy in use was specified on
311 | # a network for which this host is specifically configured. That
312 | # generally indicates that there is a direct path to this host on
313 | # this network and the proxy is not needed.
314 |
315 | fields.append(
316 | (
317 | "proxyCommand",
318 | self.proxies.get(
319 | self.proxy,
320 | "ssh {} -W {}:{}".format(self.proxy, hostname, port)
321 | # on old centos servers this is 'ssh {} nc {} 22'
322 | ),
323 | "Use %s as global proxy to access %s" % (self.proxy, name),
324 | )
325 | )
326 |
327 | # SSH algorithms
328 | def add_algorithms(name, available):
329 | if available:
330 | attribute = attributes.get(name)
331 | if attribute:
332 | key, value, desc = attribute
333 | values = value.split(',')
334 | values = [v for v in values if v in available]
335 | fields.append((key, ','.join(values), desc))
336 |
337 | add_algorithms("ciphers", self.settings.available_ciphers)
338 | add_algorithms("macs", self.settings.available_macs)
339 | add_algorithms("hostkeyalgorithms", self.settings.available_host_key_algorithms)
340 | add_algorithms("kexalgorithms", self.settings.available_kex_algorithms)
341 |
342 | # Output any unknown attributes
343 | for attribute in attributes.remaining():
344 | fields.append(attribute)
345 |
346 | # Guests (hosts that use this host as a proxy)
347 | guests = [] if forwards else attributes.getall("guests")
348 |
349 | # Save host
350 | self._append(name, fields, aliases, description, guests)
351 |
352 | def output(self):
353 | return "\n\n".join(self.hosts)
354 |
355 |
356 | # check_forward {{{1
357 | # Attribute is an SSH port forward, assure it has correct syntax
358 | re_ipaddr = r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
359 | re_hostname = r"(([a-z][\w-]*\.)*[\w-]*[a-z])"
360 | re_asterix = r"(\*)"
361 | re_port = r"(\d{1,5})"
362 | re_forward = r"\A(({addr}|{host}|{all}):)?{port}\Z".format(
363 | addr=re_ipaddr, host=re_hostname, all=re_asterix, port=re_port
364 | )
365 | forward_pattern = re.compile(re_forward, re.I)
366 |
367 |
368 | def check_forward(attribute, dynamic=False):
369 | if dynamic:
370 | # expected format is [bindaddr:]port where port is an integer and bind
371 | # address may be hostname, ip address, or *.
372 | forward = str(attribute[1])
373 | if not forward_pattern.match(forward):
374 | exit("Invalid dynamic forward: %s" % attribute[1])
375 | else:
376 | forwards = attribute[1].split()
377 | if len(forwards) != 2 or not all(
378 | [bool(forward_pattern.match(each)) for each in forwards]
379 | ):
380 | exit("Invalid forward: %s" % attribute[1])
381 |
--------------------------------------------------------------------------------
/sshconfig/help.py:
--------------------------------------------------------------------------------
1 | # Help
2 | # Output a help topic.
3 |
4 | # License {{{1
5 | # Copyright (C) 2018-2023 Kenneth S. Kundert
6 | #
7 | # This program is free software: you can redistribute it and/or modify it under
8 | # the terms of the GNU General Public License as published by the Free Software
9 | # Foundation, either version 3 of the License, or (at your option) any later
10 | # version.
11 | #
12 | # This program is distributed in the hope that it will be useful, but WITHOUT
13 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 | # details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # this program. If not, see http://www.gnu.org/licenses.
19 |
20 |
21 | # Imports {{{1
22 | from textwrap import dedent
23 |
24 | from inform import Error, error, output
25 |
26 | from .command import Command
27 | from .utilities import pager, two_columns
28 |
29 |
30 | # HelpMessage base class {{{1
31 | class HelpMessage(object):
32 | # get_name() {{{2
33 | @classmethod
34 | def get_name(cls):
35 | try:
36 | return cls.name.lower()
37 | except AttributeError:
38 | # consider converting lower to upper case transitions in __name__ to
39 | # dashes.
40 | return cls.__name__.lower()
41 |
42 | # topics {{{2
43 | @classmethod
44 | def topics(cls):
45 | for sub in cls.__subclasses__():
46 | yield sub
47 |
48 | # show {{{2
49 | @classmethod
50 | def show(cls, name=None):
51 | if name:
52 | # search commands
53 | try:
54 | command, _ = Command.find(name)
55 | if command:
56 | return pager(command.help())
57 | except Error:
58 | pass
59 |
60 | # search topics
61 | for topic in cls.topics():
62 | if name == topic.get_name():
63 | return pager(topic.help())
64 |
65 | error("topic not found.", culprit=name)
66 | else:
67 | from .main import synopsis
68 |
69 | cls.help(synopsis)
70 |
71 | # summarize {{{2
72 | @classmethod
73 | def summarize(cls, width=16):
74 | summaries = []
75 | for topic in sorted(cls.topics(), key=lambda topic: topic.get_name()):
76 | summaries.append(two_columns(topic.get_name(), topic.DESCRIPTION))
77 | return "\n".join(summaries)
78 |
79 | # help {{{2
80 | @classmethod
81 | def help(cls, desc):
82 | if desc:
83 | output(desc.strip() + "\n")
84 |
85 | output("Available commands:")
86 | output(Command.summarize())
87 |
88 | output("\nAvailable topics:")
89 | output(cls.summarize())
90 |
91 |
92 | # Overview class {{{1
93 | class Overview(HelpMessage):
94 | DESCRIPTION = "overview of sshconfig"
95 |
96 | @staticmethod
97 | def help():
98 | text = dedent(
99 | """
100 | SSH Config generates an SSH config file adapted to the network you
101 | are currently using. In this way, you always use the fastest paths
102 | available for your SSH related activities (sshfs, email, vnc,
103 | mercurial, etc.). You can also easily reconfigure SSH to make use
104 | of proxies as needed or select certain servers or ports based on
105 | your location or restrictions on the network.
106 | """
107 | ).strip()
108 | return text
109 |
--------------------------------------------------------------------------------
/sshconfig/main.py:
--------------------------------------------------------------------------------
1 | # Usage {{{1
2 | """
3 | Generate SSH Config File
4 |
5 | Creates an SSH config file that is specifically tailored to the current network
6 | situation.
7 |
8 | Usage:
9 | sshconfig [options] [ [...]]
10 |
11 | Options:
12 | -l LOCATION, --location LOCATION specifies location
13 | -n NETWORK, --network NETWORK specifies the network
14 | -p PORTS, --ports PORTS specifies list of available ports
15 | -P NAME, --proxy NAME specifies the global proxy
16 | -q, --quiet suppress optional output
17 |
18 | Specify the list of available ports as a comma separated list (no spaces). For
19 | example, --ports=80,443.
20 |
21 | Normally the network is determined automatically and need not be specified.
22 |
23 | Run 'sshconfig help' for list of available commands and help topics.
24 | Run 'sshconfig help ' for information on a specific command.
25 | Run 'sshconfig available' to see available choices for proxies, locations, and networks.
26 | """
27 |
28 | # License {{{1
29 | # Copyright (C) 2018-2023 Kenneth S. Kundert
30 | #
31 | # This program is free software: you can redistribute it and/or modify
32 | # it under the terms of the GNU General Public License as published by
33 | # the Free Software Foundation, either version 3 of the License, or
34 | # (at your option) any later version.
35 | #
36 | # This program is distributed in the hope that it will be useful,
37 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
38 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 | # GNU General Public License for more details.
40 | #
41 | # You should have received a copy of the GNU General Public License
42 | # along with this program. If not, see http://www.gnu.org/licenses/.
43 |
44 |
45 | # Imports {{{1
46 | from docopt import docopt
47 |
48 | from inform import Error, Inform, display, done, fatal, os_error
49 | from shlib import set_prefs as shlib_set_prefs
50 | from shlib import to_path
51 |
52 | from . import __released__, __version__
53 | from .command import Command
54 | from .preferences import CONFIG_DIR, DATA_DIR, LOG_FILE
55 | from .settings import Settings
56 |
57 | shlib_set_prefs(use_inform=True)
58 |
59 |
60 | # Globals {{{1
61 | synopsis = __doc__.format(commands=Command.summarize())
62 | version = f"{__version__} ({__released__})"
63 |
64 |
65 | # Main {{{1
66 | def main():
67 | with Inform(notify_if_no_tty=True, version=version) as inform:
68 | try:
69 | # assure config and log directories exist
70 | to_path(CONFIG_DIR).mkdir(parents=True, exist_ok=True)
71 | to_path(DATA_DIR).mkdir(parents=True, exist_ok=True)
72 | inform.set_logfile(to_path(DATA_DIR, LOG_FILE))
73 |
74 | # read command line
75 | cmdline = docopt(synopsis, options_first=True, version=version)
76 | command = cmdline[""]
77 | args = cmdline[""]
78 | if cmdline["--quiet"]:
79 | inform.quiet = True
80 |
81 | # find and run command
82 | settings = Settings(cmdline)
83 | cmd, cmd_name = Command.find(command)
84 | cmd.execute(cmd_name, args, settings, cmdline)
85 |
86 | except KeyboardInterrupt:
87 | display("Terminated by user.")
88 | except Error as e:
89 | e.terminate()
90 | except OSError as e:
91 | fatal(os_error(e))
92 | done()
93 |
--------------------------------------------------------------------------------
/sshconfig/preferences.py:
--------------------------------------------------------------------------------
1 | # SSH-Config Settings
2 |
3 | # License {{{1
4 | # Copyright (C) 2018-2023 Kenneth S. Kundert
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see http://www.gnu.org/licenses/.
18 |
19 | # Imports {{{1
20 | from textwrap import dedent
21 |
22 | from appdirs import user_config_dir, user_data_dir
23 |
24 | # Preferences {{{1
25 | # Program defaults {{{2
26 | PROGRAM_NAME = "sshconfig"
27 | DEFAULT_COMMAND = "create"
28 | ENCODING = "utf-8"
29 | INDENT = " "
30 | ARP = "/usr/sbin/arp -a"
31 | NMCLI_CONNS = None
32 | # use con rather than connection for compatibility with centos6
33 | UNKNOWN_NETWORK_NAME = "unknown"
34 | DEFAULT_NETWORK_NAME = "default"
35 | DATE_FORMAT = "H:mm A on D MMMM YYYY"
36 |
37 | def fold(level):
38 | return 3*'{' + str(level)
39 |
40 |
41 | # Paths {{{2
42 | CONFIG_DIR = user_config_dir(PROGRAM_NAME)
43 | DATA_DIR = user_data_dir(PROGRAM_NAME)
44 | LOG_FILE = "sshconfig.log"
45 | SSH_CONFIG_FILE = "~/.ssh/config"
46 |
47 | # Config file components {{{2
48 | SSH_HEADER = dedent(
49 | """
50 | # SSH Configuration for {network!s}
51 | # Generated at {time!s}
52 | #
53 | # DO NOT EDIT THIS FILE
54 | #
55 | # It is automatically generated by sshconfig.
56 | # To make changes in this file, edit files in {config_dir!s} and run:
57 | #
58 | # sshconfig create
59 | """
60 | ).strip()
61 |
62 | SSH_DEFAULTS = dedent(
63 | """
64 | # GLOBAL DEFAULTS {fold}
65 | {defaults}
66 | """
67 | ).strip()
68 |
69 |
70 | SSH_HOSTS = dedent(
71 | """
72 | # HOSTS {fold}
73 | {hosts}
74 | """
75 | ).strip()
76 |
77 | SSH_OVERRIDES = dedent(
78 | """
79 | # GLOBAL OVERRIDES {fold}
80 | {overrides}
81 | """
82 | ).strip()
83 |
84 | # SSH Settings {{{1
85 | # ssh_settings {{{2
86 | ssh_settings = """
87 | Host
88 | Match
89 | AddKeysToAgent
90 | AddressFamily
91 | BatchMode
92 | BindAddress
93 | BindInterface
94 | CanonicalDomains
95 | CanonicalizeFallbackLocal
96 | CanonicalizeHostname
97 | CanonicalizeMaxDots
98 | CanonicalizePermittedCNAMEs
99 | CASignatureAlgorithms
100 | CertificateFile
101 | ChallengeResponseAuthentication
102 | CheckHostIP
103 | Ciphers
104 | ClearAllForwardings
105 | Compression
106 | ConnectionAttempts
107 | ConnectTimeout
108 | ControlMaster
109 | ControlPath
110 | ControlPersist
111 | DynamicForward
112 | EnableSSHKeysign
113 | EscapeChar
114 | ExitOnForwardFailure
115 | FingerprintHash
116 | ForwardAgent
117 | ForwardX11
118 | ForwardX11Timeout
119 | ForwardX11Trusted
120 | GatewayPorts
121 | GlobalKnownHostsFile
122 | GSSAPIAuthentication
123 | GSSAPIClientIdentity
124 | GSSAPIDelegateCredentials
125 | GSSAPIKeyExchange
126 | GSSAPIRenewalForcesRekey
127 | GSSAPIServerIdentity
128 | GSSAPITrustDns
129 | GSSAPIKexAlgorithms
130 | HashKnownHosts
131 | HostbasedAuthentication
132 | HostbasedKeyTypes
133 | HostKeyAlgorithms
134 | HostKeyAlias
135 | Hostname
136 | IdentitiesOnly
137 | IdentityAgent
138 | IdentityFile
139 | IgnoreUnknown
140 | Include
141 | IPQoS
142 | KbdInteractiveAuthentication
143 | KbdInteractiveDevices
144 | KexAlgorithms
145 | LocalCommand
146 | LocalForward
147 | LogLevel
148 | MACs
149 | NoHostAuthenticationForLocalhost
150 | NumberOfPasswordPrompts
151 | PasswordAuthentication
152 | PermitLocalCommand
153 | PKCS11Provider
154 | Port
155 | ProxyCommand
156 | ProxyJump
157 | ProxyUseFdpass
158 | PubkeyAcceptedKeyTypes
159 | PubkeyAuthentication
160 | RekeyLimit
161 | RemoteCommand
162 | RemoteForward
163 | RequestTTY
164 | RevokedHostKeys
165 | SendEnv
166 | ServerAliveCountMax
167 | ServerAliveInterval
168 | SetEnv
169 | StreamLocalBindMask
170 | StreamLocalBindUnlink
171 | StrictHostKeyChecking
172 | SyslogFacility
173 | TCPKeepAlive
174 | Tunnel
175 | TunnelDevice
176 | UpdateHostKeys
177 | User
178 | UserKnownHostsFile
179 | VerifyHostKeyDNS
180 | VisualHostKey
181 | XAuthLocation
182 | """.split()
183 |
184 | # SSH_SETTINGS {{{2
185 | SSH_SETTINGS = {o.lower(): o for o in ssh_settings}
186 |
--------------------------------------------------------------------------------
/sshconfig/python.py:
--------------------------------------------------------------------------------
1 | #
2 | # Read and Write Python files
3 | #
4 | # Package for reading and writing Python files.
5 |
6 | # License {{{1
7 | # Copyright (C) 2018-2023 Kenneth S. Kundert
8 | #
9 | # This program is free software: you can redistribute it and/or modify it under
10 | # the terms of the GNU General Public License as published by the Free Software
11 | # Foundation, either version 3 of the License, or (at your option) any later
12 | # version.
13 | #
14 | # This program is distributed in the hope that it will be useful, but WITHOUT
15 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 | # details.
18 | #
19 | # You should have received a copy of the GNU General Public License along with
20 | # this program. If not, see http://www.gnu.org/licenses.
21 |
22 |
23 | # Imports {{{1
24 | from inform import Error, display, full_stop, narrate, os_error
25 | from shlib import cp, to_path
26 |
27 |
28 | # PythonFile class {{{1
29 | class PythonFile:
30 | ActivePythonFile = None
31 |
32 | @classmethod
33 | def get_active_python_file(cls):
34 | return cls.ActivePythonFile
35 |
36 | def __init__(self, *path_components):
37 | self.path = to_path(*path_components)
38 |
39 | def save(self, contents):
40 | path = self.path
41 | path.write_text(contents, encoding="utf-8")
42 |
43 | def read(self):
44 | path = self.path
45 | return path.read_text(encoding="utf-8")
46 |
47 | def remove(self):
48 | self.path.unlink()
49 |
50 | def backup(self, extension):
51 | """Creates a backup copy of the file.
52 |
53 | The name of the new file has the specified extension prepended to the
54 | existing suffixes.
55 | """
56 | # prepend extension to list of suffixes
57 | suffixes = self.path.suffixes
58 | stem = self.path.stem.partition(".")[0] # remove all suffixes
59 | new = to_path(self.path.parent, "".join([stem, extension] + suffixes))
60 | self.backup_path = new
61 |
62 | cp(self.path, new)
63 | return new
64 |
65 | def restore(self):
66 | "Restores the backup copy of the file."
67 | cp(self.backup_path, self.path)
68 |
69 | def run(self):
70 | self.ActivePythonFile = self.path
71 | path = self.path
72 | narrate("reading:", path)
73 | try:
74 | self.code = self.read()
75 | # need to save the code for the new command
76 | except OSError as err:
77 | raise Error(os_error(err))
78 |
79 | try:
80 | compiled = compile(self.code, str(path), "exec")
81 | except SyntaxError as err:
82 | culprit = (err.filename, err.lineno)
83 | if err.text is None or err.offset is None:
84 | raise Error(full_stop(err.msg), culprit=culprit)
85 | else:
86 | raise Error(
87 | err.msg + ":",
88 | err.text.rstrip(),
89 | (err.offset - 1) * " " + "^",
90 | culprit=culprit,
91 | sep="\n",
92 | )
93 |
94 | contents = {}
95 | try:
96 | exec(compiled, contents)
97 | except Exception as err:
98 | from .utilities import error_source
99 |
100 | raise Error(full_stop(err), culprit=error_source())
101 | self.ActivePythonFile = None
102 | # strip out keys that start with '__' and return them
103 | return {k: v for k, v in contents.items() if not k.startswith("__")}
104 |
105 | def create(self, contents):
106 | path = self.path
107 | try:
108 | if path.exists():
109 | # file creation (init) requested, but file already exists
110 | # don't overwrite the file, instead read it so the information
111 | # can be used to create any remaining files.
112 | display("%s: already exists." % path)
113 | return
114 | # create the file
115 | display("%s: creating." % path)
116 | # file is not encrypted
117 | with path.open("wb") as f:
118 | f.write(contents.encode("utf-8"))
119 | except OSError as err:
120 | raise Error(os_error(err))
121 |
122 | def exists(self):
123 | return self.path.exists()
124 |
125 | def __str__(self):
126 | return str(self.path)
127 |
--------------------------------------------------------------------------------
/sshconfig/settings.py:
--------------------------------------------------------------------------------
1 | # Settings
2 |
3 | # License {{{1
4 | # Copyright (C) 2018-2023 Kenneth S. Kundert
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see http://www.gnu.org/licenses/.
18 |
19 | # Imports {{{1
20 | from inform import Error, codicil, conjoin, display, full_stop, narrate, warn
21 | from shlib import Run, to_path
22 |
23 | from .core import Hosts
24 | from .preferences import (
25 | ARP,
26 | CONFIG_DIR,
27 | NMCLI_CONNS,
28 | SSH_CONFIG_FILE,
29 | UNKNOWN_NETWORK_NAME,
30 | )
31 | from .python import PythonFile
32 | from .sshconfig import HostEntry, NetworkEntry, locations, ports, set_network_name
33 |
34 | # Globals {{{1
35 | sshconfig_names = set(
36 | """
37 | HostEntry NetworkEntry VNC ports locations is_ip_addr get_network_name
38 | gethostname getusername
39 | """.split()
40 | )
41 |
42 |
43 | # Settings class {{{1
44 | class Settings:
45 | # Constructor {{{2
46 | def __init__(self, cmdline):
47 | self.settings = {}
48 | self.settings = dict()
49 | self.config_dir = to_path(CONFIG_DIR)
50 | self.read_confs()
51 | self.set_network(cmdline["--network"])
52 | self.set_proxy(cmdline["--proxy"])
53 | self.set_ports(cmdline["--ports"])
54 | self.set_location(cmdline["--location"])
55 |
56 | # read_confs() {{{2
57 | def read_confs(self):
58 | # read the .conf files in our config directory (except for hosts.conf)
59 | for name in "ssh networks locations proxies".split():
60 | conf_file = to_path(CONFIG_DIR, name + ".conf")
61 | if conf_file.exists():
62 | settings = PythonFile(conf_file).run()
63 | overlap = settings.keys() & self.settings.keys()
64 | overlap -= sshconfig_names
65 | overlap = [k for k in overlap if not k.startswith("_")]
66 | if overlap:
67 | warn("conflicting settings:", conjoin(overlap), culprit=conf_file)
68 | self.settings.update(settings)
69 |
70 | self.ssh_config_file = to_path(
71 | self.settings.get("CONFIG_FILE", SSH_CONFIG_FILE)
72 | )
73 | if not self.ssh_config_file.is_absolute():
74 | raise Error(
75 | "path to SSH config file should be absolute.",
76 | culprit=self.ssh_config_file,
77 | )
78 | self.ssh_defaults = self.settings.get("DEFAULTS", "")
79 | self.ssh_overrides = self.settings.get("OVERRIDES", "")
80 | self.preferred_networks = self.settings.get("PREFERRED_NETWORKS", [])
81 | self.locations = self.settings.get("LOCATIONS", {})
82 | self.proxies = self.settings.get("PROXIES", {})
83 | self.arp = self.settings.get("ARP", ARP)
84 | self.get_nmcli_conns = self.settings.get("NMCLI_CONNS", NMCLI_CONNS)
85 |
86 | self.available_ciphers = self.settings.get("AVAILABLE_CIPHERS")
87 | self.available_macs = self.settings.get("AVAILABLE_MACS")
88 | self.available_host_key_algorithms = self.settings.get("AVAILABLE_HOST_KEY_ALGORITHMS")
89 | self.available_kex_algorithms = self.settings.get("AVAILABLE_KEX_ALGORITHMS")
90 |
91 | # read_hosts() {{{2
92 | # must be read after port, location, and proxy choices are made
93 | def read_hosts(self):
94 | set_network_name(self.primary_network.name())
95 | conf_file = to_path(CONFIG_DIR, "hosts.conf")
96 | narrate("reading:", conf_file)
97 | PythonFile(conf_file).run()
98 |
99 | # Process each host
100 | available_networks = [network.name() for network in self.networks]
101 | hosts = Hosts(available_networks, self.proxy, self.proxies, self)
102 | for host in HostEntry.all_hosts():
103 | hosts.process(host, forwards=False)
104 | hosts.process(host, forwards=True)
105 | self.hosts = hosts
106 |
107 | # set_network() {{{2
108 | def set_network(self, given=None):
109 | networks = []
110 | if given:
111 | network = [NetworkEntry.find(given)]
112 | if not given:
113 | networks = self.identify_networks()
114 | network = networks[0] if networks else None
115 |
116 | if not network:
117 |
118 | class UnknownNetwork(NetworkEntry):
119 | key = UNKNOWN_NETWORK_NAME
120 |
121 | network = NetworkEntry.find(UNKNOWN_NETWORK_NAME)
122 |
123 | self.primary_network = network
124 | self.networks = networks if networks else [network]
125 |
126 | if network.ports:
127 | ports.available(network.ports)
128 | if network.location:
129 | locations.set_location(network.location)
130 |
131 | def initialize_network(self):
132 | network = self.network
133 |
134 | # run the init script if given
135 | try:
136 | if network.init_script:
137 | script = Run(network.init_script, "sOEW")
138 | if script.stdout:
139 | display(script.stdout.rstrip())
140 | except AttributeError:
141 | pass
142 | except Error as e:
143 | warn(
144 | "{} network init_script failed: {}".format(
145 | network.name(), network.init_script
146 | )
147 | )
148 | codicil(e.get_message())
149 |
150 | # set_proxy() {{{2
151 | def set_proxy(self, given=None):
152 | self.proxy = given if given else self.primary_network.proxy
153 |
154 | # set_ports() {{{2
155 | def set_ports(self, given=None):
156 | ports.available(given if given else self.primary_network.ports)
157 |
158 | # set_location() {{{2
159 | def set_location(self, given=None):
160 | locations.set_location(given if given else self.primary_network.location)
161 | unknown = locations.unknown_locations(self.locations)
162 | if unknown:
163 | warn("the following locations are unknown (add them to LOCATIONS):")
164 | codicil(*sorted(unknown), sep="\n")
165 | self.location = self.locations.get(locations.my_location)
166 | if locations.my_location and not self.location:
167 | raise Error("unknown location, choose from:", conjoin(self.locations))
168 |
169 | # get_summary() {{{2
170 | def get_summary(self):
171 | summary = ["Network is", self.primary_network.Name()]
172 | network_desc = self.primary_network.description
173 | if network_desc:
174 | summary.append("({})".format(network_desc))
175 | if self.location:
176 | summary.append("located near {}".format(self.location))
177 | if ports.available_ports:
178 | summary.append(
179 | "using port {}".format(
180 | conjoin([str(port) for port in ports.available_ports], " or ")
181 | )
182 | )
183 | if self.proxy:
184 | summary.append("proxying through {}".format(self.proxy))
185 | return full_stop(" ".join(summary))
186 |
187 | # identify_networks() {{{2
188 | # Identifies which networks are currently available
189 | # uses the arp and nmcli commands
190 | def identify_networks(self):
191 |
192 | def known_networks(preferred):
193 | # First offer the preferred networks, in order
194 | for name in preferred:
195 | network = NetworkEntry.find(name)
196 | if network:
197 | yield network
198 |
199 | # Offer the remaining networks in arbitrary order
200 | for network in NetworkEntry.all_networks():
201 | yield network
202 |
203 | # get MAC address of all devices on active networks
204 | macs = []
205 | try:
206 | arp = Run(self.arp, "sOeW")
207 | arp_table = arp.stdout
208 | for row in arp_table.split("\n"):
209 | try:
210 | name, ipaddr, at, mac, hwtype, on, interface = row.split()
211 | macs.append(mac)
212 | except ValueError:
213 | continue
214 | except Error as e:
215 | e.report()
216 | return []
217 |
218 | # filter out any network devices that are not routers for known networks
219 | networks = [
220 | network
221 | for network in known_networks(self.preferred_networks)
222 | for mac in macs
223 | if mac in network.routers
224 | ]
225 |
226 | # get SSID of WiFi network
227 | # if only on wifi, this will identify the same network already
228 | # identified, however this will identify a different network if both a
229 | # wired and wireless network is active at the same time
230 | try:
231 | if self.get_nmcli_conns:
232 | nmcli = Run(self.get_nmcli_conns, "sOeW")
233 | connections = nmcli.stdout.splitlines()
234 | for network in known_networks(self.preferred_networks):
235 | if getattr(network, 'nmcli_connection', None) in connections:
236 | networks.append(network)
237 | except Error as e:
238 | e.report(codicil="Set nmcli_conns setting to None if nmcli is not available.")
239 |
240 | return list(dict.fromkeys(networks))
241 |
242 |
243 | # write_ssh_config() {{{2
244 | def write_ssh_config(self, contents):
245 | narrate("writing:", self.ssh_config_file)
246 | self.ssh_config_file.parent.mkdir(parents=True, exist_ok=True)
247 | self.ssh_config_file.write_text(contents)
248 | self.ssh_config_file.chmod(0o600)
249 |
250 | # get attribute {{{2
251 | def __getattr__(self, name):
252 | return self.settings.get(name)
253 |
254 | # iterate through settings {{{2
255 | def __iter__(self):
256 | for key in sorted(self.settings.keys()):
257 | yield key, self.settings[key]
258 |
--------------------------------------------------------------------------------
/sshconfig/sshconfig.py:
--------------------------------------------------------------------------------
1 | # SSHConfig utility classes and functions
2 | #
3 | # These are used by the user in the conf files.
4 |
5 | # Imports {{{1
6 | from inform import Error, full_stop, is_str
7 | from shlib import Run, set_prefs as shlib_set_prefs
8 | import re
9 |
10 | # Globals {{{1
11 | KEYS_TO_INHERIT = ["user", "identityFile"]
12 | LOWER_TO_UPPER_TRANSITION = re.compile(r"([a-z])([A-Z])")
13 | CHOSEN_NETWORK_NAME = None
14 | FALLBACK_ALGORITHMS = {}
15 | shlib_set_prefs(use_inform=True)
16 |
17 | # Utilities {{{1
18 | # set_network_name {{{2
19 | # called from main with the name of the chosen network
20 | # allows users to change their configuration based on the active network
21 | def set_network_name(name):
22 | global CHOSEN_NETWORK_NAME
23 | CHOSEN_NETWORK_NAME = name.lower()
24 |
25 |
26 | # get_network_name {{{2
27 | def get_network_name():
28 | "Returns name of network (lowercase)"
29 | return CHOSEN_NETWORK_NAME
30 |
31 |
32 | # is_ip_addr {{{2
33 | def is_ip_addr(addr):
34 | return re.match(r"\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s*\Z", addr)
35 |
36 |
37 | # filter_algorithms {{{2
38 | def filter_algorithms(name, desired=(), fallback=()):
39 | """Filter Algorithms
40 |
41 | Given a desired set of algorithms, this function filters out those that are
42 | not available.
43 |
44 | name (str):
45 | The class of algorithm to filter. value must be acceptable to `ssh -Q
46 | ⟪name⟫` (see `man ssh`). Typical value: ciphers, kex, key, mac or sig.
47 | desired (str or array):
48 | The ordered list of preferred algorithms.
49 | fallback (str or array):
50 | The ordered list of algorithms to use if no desired algorithms are
51 | available.
52 | """
53 |
54 | if is_str(desired):
55 | desired = desired.replace(',', ' ').split()
56 | if is_str(fallback):
57 | fallback = fallback.replace(',', ' ').split()
58 |
59 | if not fallback:
60 | fallback = FALLBACK_ALGORITHMS.get(name, [])
61 | FALLBACK_ALGORITHMS[name] = fallback
62 |
63 | try:
64 | ssh = Run(['ssh', '-Q', name], modes='sOEW')
65 | available = ssh.stdout.split()
66 | except Error as e:
67 | # this should only occur on old version of ssh that don't support -Q
68 | assert 'option' in e.stderr and 'Q' in e.stderr
69 | available = fallback
70 |
71 | filtered = [d for d in desired if d in available]
72 |
73 | return ','.join(filtered if filtered else fallback)
74 |
75 |
76 | # VNC {{{2
77 | # Generates forwards for VNC
78 | def VNC(dispNum=0, rmtHost="localhost", lclDispNum=None, rmtDispNum=None, lclHost=None):
79 | if lclDispNum is None:
80 | lclDispNum = dispNum
81 | if rmtDispNum is None:
82 | rmtDispNum = dispNum
83 | lclHost = lclHost + ":" if lclHost else ""
84 | return "%s%d %s:%d" % (lclHost, 5900 + lclDispNum, rmtHost, 5900 + rmtDispNum)
85 |
86 |
87 | # NetworkEntry class {{{1
88 | # Used to describe a known network
89 | class NetworkEntry:
90 | key = None # succinct version of the name (optional)
91 | description = None # descriptive version of the name (optional)
92 | routers = []
93 | ports = None
94 | location = None
95 | proxy = None
96 |
97 | def __init__(self):
98 | raise NotImplementedError
99 |
100 | @classmethod
101 | def all_networks(cls):
102 | # yields all known networks
103 | for subclass in cls.__subclasses__():
104 | yield subclass
105 | for subclass in subclass.all_networks():
106 | yield subclass
107 |
108 | @classmethod
109 | def name(cls):
110 | return cls.key.lower() if cls.key else cls.__name__.lower()
111 |
112 | @classmethod
113 | def Name(cls):
114 | return cls.key if cls.key else cls.__name__
115 |
116 | @classmethod
117 | def desc(cls):
118 | # the descriptions that are created from the class name are
119 | # unattractive, and the rest of the code tends to use cls.description
120 | # rather than cls.desc().
121 | if cls.description:
122 | return cls.description
123 | # Return formatted name
124 | # '__' is converted to ' - ', so Library__MV becomes 'Library - MV'
125 | # '_' is replaced by ' '
126 | # space inserted upon lower case to upper case transitions
127 | description = cls.__name__.replace("__", " - ")
128 | description = description.replace("_", " ")
129 | description = LOWER_TO_UPPER_TRANSITION.sub(r"\1 \2", description)
130 | return description
131 |
132 | @classmethod
133 | def fields(cls):
134 | parents = cls.__bases__
135 | assert len(parents) == 1
136 | parent = parents[0]
137 | my_fields = dict(cls.__dict__)
138 |
139 | # Inherit fields from the parent, overriding fields that were specified
140 | fields = dict(parent.__dict__)
141 | fields.update(my_fields)
142 | return fields
143 |
144 | @classmethod
145 | def find(cls, name):
146 | name = name.lower()
147 | for subclass in cls.__subclasses__():
148 | if subclass.key and subclass.key.lower() == name:
149 | return subclass
150 | if subclass.__name__.lower() == name:
151 | return subclass
152 | return None
153 |
154 | @classmethod
155 | def known(cls):
156 | # yields the names associated with any known network
157 | for subclass in cls.__subclasses__():
158 | if subclass.key:
159 | yield subclass.key.lower()
160 | yield subclass.__name__.lower()
161 |
162 | @classmethod
163 | def get_location(cls, given=None):
164 | return given if given else cls.location
165 |
166 |
167 | # HostEntry class {{{1
168 | # Used to describe an available host
169 | class HostEntry:
170 | def __init__(self):
171 | raise NotImplementedError
172 |
173 | @classmethod
174 | def all_hosts(cls):
175 | for subclass in sorted(cls.__subclasses__(), key=lambda s: s.__name__):
176 | yield subclass
177 | for subclass in subclass.all_hosts():
178 | yield subclass
179 |
180 | @classmethod
181 | def name(cls):
182 | return cls.__name__.lower()
183 |
184 | @classmethod
185 | def fields(cls):
186 | parents = cls.__bases__
187 | assert len(parents) == 1
188 | parent = parents[0]
189 | my_fields = dict(cls.__dict__)
190 |
191 | # Inherit selected fields from the parent
192 | if parent.__name__ != HostEntry.__name__:
193 | parent_fields = parent.__dict__
194 | # Get the hostname and port number
195 | hostname = my_fields.pop("hostname", cls.name())
196 | port = my_fields.pop("port", 22)
197 | fields = {
198 | key: parent_fields[key]
199 | for key in KEYS_TO_INHERIT
200 | if key in parent_fields
201 | }
202 | fields.update(
203 | {
204 | "proxyCommand": (
205 | # 'ssh {} -W %h:%p'.format(parent.name()),
206 | # Above works in most cases, but it uses the ssh config
207 | # entry name as %h rather than the hostname, so it fails
208 | # when ssh config entry name does not correspond to
209 | # a known host by the proxy host (occurs with forwarding
210 | # entries). So instead use the actual specified
211 | # hostname.
212 | "ssh {} -W {}:{}".format(parent.name(), hostname, port),
213 | "Use {} as a proxy to access {} via port {}".format(
214 | parent.name(), hostname, port
215 | ),
216 | )
217 | }
218 | )
219 | else:
220 | fields = {}
221 |
222 | # Override inherited fields with those that were specified
223 | fields.update(my_fields)
224 |
225 | return fields
226 |
227 |
228 | # Ports class {{{1
229 | # Used when selecting which port to use when several are available
230 | class Ports:
231 | def __init__(self):
232 | self.available_ports = None
233 |
234 | def available(self, ports):
235 | try:
236 | self.available_ports = [int(port) for port in ports.split(",")]
237 | except AttributeError:
238 | self.available_ports = ports
239 | except ValueError as e:
240 | raise Error(full_stop(e))
241 |
242 | def not_available(self, port):
243 | return self.available_ports and port not in self.available_ports
244 |
245 | def choose(self, supported_ports):
246 | if self.available_ports is None:
247 | return supported_ports[0]
248 | for port in self.available_ports:
249 | if port in supported_ports:
250 | return port
251 | return None
252 |
253 |
254 | # Locations class {{{1
255 | # Used when selecting hostname as a function of current location
256 | class Locations:
257 | def __init__(self):
258 | self.my_location = None
259 | self.seen_locations = {}
260 |
261 | def set_location(self, location):
262 | self.my_location = location
263 |
264 | def choose(self, locations, maps, default):
265 | location = self.my_location
266 | if maps:
267 | self.seen_locations.update(maps)
268 | location = maps.get(
269 | location, location if location in locations else default
270 | )
271 | return locations.get(location)
272 |
273 | def unknown_locations(self, known_locations):
274 | seen = set(self.seen_locations.keys())
275 | for each in known_locations:
276 | seen.discard(each)
277 | return seen
278 |
279 |
280 | ports = Ports()
281 | locations = Locations()
282 |
--------------------------------------------------------------------------------
/sshconfig/utilities.py:
--------------------------------------------------------------------------------
1 | # Utilities
2 |
3 | # License {{{1
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see http://www.gnu.org/licenses/.
16 |
17 | # Imports {{{1
18 | from shlib import Run
19 | import os
20 | import socket
21 | import pwd
22 |
23 |
24 | # gethostname {{{1
25 | # returns short version of the hostname (the hostname without any domain name)
26 | def gethostname():
27 | return socket.gethostname().split('.')[0]
28 |
29 |
30 | # getusername {{{1
31 | def getusername():
32 | return pwd.getpwuid(os.getuid()).pw_name
33 |
34 |
35 | # pager {{{1
36 | def pager(text):
37 | program = os.environ.get('PAGER', 'less')
38 | Run([program], stdin=text, modes='Woes')
39 |
40 |
41 | # two_columns {{{1
42 | def two_columns(col1, col2, width=16, indent=True):
43 | indent = ' '
44 | if len(col1) > width:
45 | return '%s%s\n%s%s%s' % (
46 | indent, col1, indent, ' ' + width * ' ', col2
47 | )
48 | else:
49 | return '%s%-*s %s' % (indent, width, col1, col2)
50 |
51 |
52 | # error_source {{{1
53 | def error_source():
54 | """Source of error
55 | Reads stack trace to determine filename and line number of error.
56 | """
57 | import traceback
58 | try:
59 | # return filename and lineno
60 | # context and content are also available
61 | import sys
62 | exc_cls, exc, tb = sys.exc_info()
63 | trace = traceback.extract_tb(tb)
64 | filename, line, context, text = trace[-1]
65 | except SyntaxError:
66 | # extract_stack() does not work on binary encrypted files. It generates
67 | # a syntax error that indicates that the file encoding is missing
68 | # because the function tries to read the file and sees binary data. This
69 | # is not a problem with ascii encrypted files as we don't actually show
70 | # code, which is gibberish, but does not require an encoding. In this
71 | # case, extract the line number from the trace.
72 | from .gpg import get_active_python_file
73 | filename = get_active_python_file()
74 | line = tb.tb_next.tb_lineno
75 | return filename, 'line %s' % line
76 |
--------------------------------------------------------------------------------