pax_global_header00006660000000000000000000000064145751460440014524gustar00rootroot0000000000000052 comment=c6389abd09a517c59056aa2c022db8c130285b2e ssh-tools/000077500000000000000000000000001457514604400130235ustar00rootroot00000000000000ssh-tools/CHANGELOG.md000066400000000000000000000055431457514604400146430ustar00rootroot00000000000000# 1.8 (2024-03-15) ## Added - **ssh-last**: like last but for SSH sessions - **ssh-pwd**: quickly echo path to use for scp, rsync ## Changed - ssh-facts: - Bugfix for newer FreeBSDs - Updated explorers from cdist - ssh-ping: - Add new option **-E** which exits ssh-ping immediately after first successful ping (can be used to trigger a follow up task like rsync) - Add Tab Completion info into usage - Bugfix for Debian Bug #998219 making the package build reproducible - all - Shrink header comments ## Removed - all - Removed HashKnownHosts=no option > Some Distros set several options as standard in /etc/ssh/ssh_config. > Debian uses HashKnownHosts=yes by default > so entries in ~/.ssh/known_hosts get mixed with hashed and unhashed entries. > Removing this option, so ssh's default gets used # 1.7 (2021-10-31) ## Added - **ssh-force-password**: Enforces password authentication - ssh-ping - Option (-C) to connect/reconnect as soon as the host responds - Exit Codes - 1: More than 1 request lost - 2: All requests lost - Environment Variable - SSH_PING_NO_COLORS: if set, no colors are shown (like -n) # 1.6 (2020-01-23) ## Added - **ssh-certinfo**: Shows validity and information of SSH certificates - **ssh-keyinfo**: Prints keys in several formats - ssh-diff: Environment variable to disable remote file checking - ssh-facts: New explorers ( runlevel, disks ) - ssh-ping: Option to print human readable timestamp (-H) ## Changed - all - shellchecked and fixed errors and warnings (https://www.shellcheck.net) - ssh-diff: - Replaced tput with ANSI Escape codes for color output - Pipe output to cat to get a zero exit code for test.sh - ssh-facts: - Update explorers - ssh-ping: - Replaced tput with ANSI Escape codes for color output - Changed from Python to Perl for calculating time - ssh-version: - Updated usage (with examples) # 1.5 (2018-12-23) ## Added - **ssh-hostkeys**: Prints server host keys in several formats ## Removed - Moved packaging files for debian to https://salsa.debian.org/swick-guest/ssh-tools # 1.4 (2018-02-25) ## Added - ssh-facts: uptime and last_reboot fact ## Changed - minor fixes - improved documentation # 1.3 (2017-10-04) ## Added - better OpenBSD support ## Changed - consistent code formatting and better output - more robustness - portable to older Bash versions - changed license from AGPL-3 to GPL-3 and added debian/copyright # 1.2 (2017-09-03) ## Added - **ssh-diff**: Diff a file over SSH - **ssh-facts**: Get some facts about the remote system ## Changed - ssh-ping: works now under OSX - debianized package # 1.1 (2017-08-20) ## Added - ssh-ping: colors in statistics output # 1.0 (2017-08-14) Initial Release - **ssh-ping**: Check if host is reachable using ssh_config - **ssh-version**: Shows version of the SSH server you are connecting to ssh-tools/LICENSE000066400000000000000000001045051457514604400140350ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ssh-tools/examples/000077500000000000000000000000001457514604400146415ustar00rootroot00000000000000ssh-tools/examples/certs/000077500000000000000000000000001457514604400157615ustar00rootroot00000000000000ssh-tools/examples/certs/expired-cert.pub000066400000000000000000000027121457514604400210660ustar00rootroot00000000000000ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAg8LME+FswVlVMrB4MdgCqFx08JrbDFLdOce9j3e2/ybgAAAADAQABAAABAQDmzblLFSpP8sgvF1hNuFVPFC3DdL9Cswu8/eFgzY5nb825Bw8UxCq/DgQm7AuuInFvON96BR2DsAuRFQywJfh5IrwpIdVNT8/waG67v6SYPfvYba3NUlki/skW9Ox6Ch+z6GBWi1oCXb2I5u4w9WM9TFvP7iXBWhxAOt9EQE39zTuJQlNUOW3+93ZLdcWO961gJImr9oaks3YyeDtIBYPRZT89Y1f25gBtVsiLWk+wiO3ezypa5Rhlu4Z7kznDwr5GJ9SZ9rEib6huUGhCn7fz1nN7qL9WyvMZq7qbv1/ToXW9ROMPRmi4MuCgJYyQFJFvQuHcer+t8SBwzKLrHCYDAAAAAAAAAAAAAAABAAAAB2V4cGlyZWQAAAAAAAAAACSFjZEAAAAAKavpkQAAAAAAAACCAAAAFXBlcm1pdC1YMTEtZm9yd2FyZGluZwAAAAAAAAAXcGVybWl0LWFnZW50LWZvcndhcmRpbmcAAAAAAAAAFnBlcm1pdC1wb3J0LWZvcndhcmRpbmcAAAAAAAAACnBlcm1pdC1wdHkAAAAAAAAADnBlcm1pdC11c2VyLXJjAAAAAAAAAAAAAAEXAAAAB3NzaC1yc2EAAAADAQABAAABAQC48zvKsJplnaLTbXo0263ABcXqtl9D0O+hm2jxhqoJ/lS77IAuLoDZwYnaWizYvOknWgY66svE5EkY8kspro4tzSgLG0r9kncWlfNNEJb64kem/K9kiHJLpBvmaup0ZUFhg5BcpNmhDhlU5fm0+NI4+qgRvYXbM1rys8nxobtXGOJIFbNf9GkwA7eHpx/J6dPrDZ2QxUBzEy07fiGe7viGgF1xTaNjIwNuVWu3oz+XXzEqMC0mXsVxalA0qT0ol2arROYNWAp6/qNjGlu5VA1tFGUi1gGwIZ3++yEmJerTSV6OHns2g4JGcDvVU8i0KWvyi2o0xmgUbRgABjMFWSWDAAABDwAAAAdzc2gtcnNhAAABAHt8Sv2cLkGSNN68gAkdl9xW2lOhWvQ0CzFZoHIsC6tVU3Qv8Jyyj9Tx0UZb7h+ZX5Bminx81++Ig5kis64//u6xafzwu2QDPPnxmduJTQJEFg0wqfkTMaWagkWlsT5SrSE+3AbpZ5qn9Tit+RSKiwLxqkQwf52S1mtZXiY26Pz8iLyv177wxOjPjIBVDD8slCnQaGxkJY5kazmDBNaQDblWMThBgo75cgL5ckTpYMGiuxJsmpF5zCaSmLvSfOJKJG79Fl6amjNmdD5B827p6YbT4BaH1AecxI5/HjmpbaKzI36mb/bz4G4Boto/R8e9RWsakVItvmjz8wm2RgFZ37w= swick@8470p ssh-tools/examples/certs/forever-cert.pub000066400000000000000000000027121457514604400210760ustar00rootroot00000000000000ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgEmDHw119SIC5DbYmdwvy2WpCJLwHEGxpqVlgZEV4A3gAAAADAQABAAABAQDmzblLFSpP8sgvF1hNuFVPFC3DdL9Cswu8/eFgzY5nb825Bw8UxCq/DgQm7AuuInFvON96BR2DsAuRFQywJfh5IrwpIdVNT8/waG67v6SYPfvYba3NUlki/skW9Ox6Ch+z6GBWi1oCXb2I5u4w9WM9TFvP7iXBWhxAOt9EQE39zTuJQlNUOW3+93ZLdcWO961gJImr9oaks3YyeDtIBYPRZT89Y1f25gBtVsiLWk+wiO3ezypa5Rhlu4Z7kznDwr5GJ9SZ9rEib6huUGhCn7fz1nN7qL9WyvMZq7qbv1/ToXW9ROMPRmi4MuCgJYyQFJFvQuHcer+t8SBwzKLrHCYDAAAAAAAAAAAAAAABAAAAB2ZvcmV2ZXIAAAAAAAAAAAAAAAD//////////wAAAAAAAACCAAAAFXBlcm1pdC1YMTEtZm9yd2FyZGluZwAAAAAAAAAXcGVybWl0LWFnZW50LWZvcndhcmRpbmcAAAAAAAAAFnBlcm1pdC1wb3J0LWZvcndhcmRpbmcAAAAAAAAACnBlcm1pdC1wdHkAAAAAAAAADnBlcm1pdC11c2VyLXJjAAAAAAAAAAAAAAEXAAAAB3NzaC1yc2EAAAADAQABAAABAQC48zvKsJplnaLTbXo0263ABcXqtl9D0O+hm2jxhqoJ/lS77IAuLoDZwYnaWizYvOknWgY66svE5EkY8kspro4tzSgLG0r9kncWlfNNEJb64kem/K9kiHJLpBvmaup0ZUFhg5BcpNmhDhlU5fm0+NI4+qgRvYXbM1rys8nxobtXGOJIFbNf9GkwA7eHpx/J6dPrDZ2QxUBzEy07fiGe7viGgF1xTaNjIwNuVWu3oz+XXzEqMC0mXsVxalA0qT0ol2arROYNWAp6/qNjGlu5VA1tFGUi1gGwIZ3++yEmJerTSV6OHns2g4JGcDvVU8i0KWvyi2o0xmgUbRgABjMFWSWDAAABDwAAAAdzc2gtcnNhAAABAI7HCo9S1CRvkol1DOiOebCII9+P5LW5j5FpnbAHQZlK5xfG/Dg6e6X4jxYwAyg1VBJOgMAi8kgzVyDrtY7JBDoTVPPMiLh10SLOwwnPklkjONVW1MntdEg8z81Kdbq1TlAq+SxymArVFmVs9NqWbcpY3q5sp4bhZ6XGq2Bx5XwCH1BG+B+GP2qU/nHcQWK32fK3DZYaTWYbsHogxPNrOdErEaavqBBJk/+XSKxMJjWT4PGjsqROFvEUbPFslMc7USGPS46cU+aNgOp/JPL6W9weH+7DmcUUpXIbog5qedxMTnszjQaBRSUHHq2BXrv+eOXmghtqFfv1QLpHRwWbry0= swick@8470p ssh-tools/examples/certs/in-the-future-cert.pub000066400000000000000000000027221457514604400221230ustar00rootroot00000000000000ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgdMSETNhV3OaJETc9NvcmN3fUTtDf6SV541lPlv8l0Q0AAAADAQABAAABAQDmzblLFSpP8sgvF1hNuFVPFC3DdL9Cswu8/eFgzY5nb825Bw8UxCq/DgQm7AuuInFvON96BR2DsAuRFQywJfh5IrwpIdVNT8/waG67v6SYPfvYba3NUlki/skW9Ox6Ch+z6GBWi1oCXb2I5u4w9WM9TFvP7iXBWhxAOt9EQE39zTuJQlNUOW3+93ZLdcWO961gJImr9oaks3YyeDtIBYPRZT89Y1f25gBtVsiLWk+wiO3ezypa5Rhlu4Z7kznDwr5GJ9SZ9rEib6huUGhCn7fz1nN7qL9WyvMZq7qbv1/ToXW9ROMPRmi4MuCgJYyQFJFvQuHcer+t8SBwzKLrHCYDAAAAAAAAAAAAAAABAAAADWluLXRoZS1mdXR1cmUAAAAAAAAAAJCrGjsAAAAAldF2OwAAAAAAAACCAAAAFXBlcm1pdC1YMTEtZm9yd2FyZGluZwAAAAAAAAAXcGVybWl0LWFnZW50LWZvcndhcmRpbmcAAAAAAAAAFnBlcm1pdC1wb3J0LWZvcndhcmRpbmcAAAAAAAAACnBlcm1pdC1wdHkAAAAAAAAADnBlcm1pdC11c2VyLXJjAAAAAAAAAAAAAAEXAAAAB3NzaC1yc2EAAAADAQABAAABAQC48zvKsJplnaLTbXo0263ABcXqtl9D0O+hm2jxhqoJ/lS77IAuLoDZwYnaWizYvOknWgY66svE5EkY8kspro4tzSgLG0r9kncWlfNNEJb64kem/K9kiHJLpBvmaup0ZUFhg5BcpNmhDhlU5fm0+NI4+qgRvYXbM1rys8nxobtXGOJIFbNf9GkwA7eHpx/J6dPrDZ2QxUBzEy07fiGe7viGgF1xTaNjIwNuVWu3oz+XXzEqMC0mXsVxalA0qT0ol2arROYNWAp6/qNjGlu5VA1tFGUi1gGwIZ3++yEmJerTSV6OHns2g4JGcDvVU8i0KWvyi2o0xmgUbRgABjMFWSWDAAABDwAAAAdzc2gtcnNhAAABAJDFYzdjhLoNzhktDuJhlaq574EsiEubJ3z8ElU+VMrsF003LoI6LlBryhwj8uglIZzrQiDrwwEHnqe6NiFr91ysGbJgSF4hnzZq5ye/sAYMw/JpSmTJg3cycnMcPNcXNeFoiDlG9muNfgpeoIEqAjzVc0fbHCRGuqvLTT8y9hxGGNFU3ISmJLbcIgdHB1mgAEs7Sih2zy4Cp1kyCZ3I/Bc+qO50IvFXhVZRlJY1UhfmOIGr6F1zuSsCYimmEs7STyA0fqCXITU4Lj+AN1/kac3B+ASmZyV5puEtfzqogc+g/iMaYNcNnr7FX7UXFug2AV9BhWbrLa+T0R0swUEGtwI= swick@8470p ssh-tools/examples/certs/next-20-years-cert.pub000066400000000000000000000027221457514604400217450ustar00rootroot00000000000000ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgR3GZzAC+KgP+1zk2PMIojpD9Qw83jH6aRcbgORbd/e0AAAADAQABAAABAQDmzblLFSpP8sgvF1hNuFVPFC3DdL9Cswu8/eFgzY5nb825Bw8UxCq/DgQm7AuuInFvON96BR2DsAuRFQywJfh5IrwpIdVNT8/waG67v6SYPfvYba3NUlki/skW9Ox6Ch+z6GBWi1oCXb2I5u4w9WM9TFvP7iXBWhxAOt9EQE39zTuJQlNUOW3+93ZLdcWO961gJImr9oaks3YyeDtIBYPRZT89Y1f25gBtVsiLWk+wiO3ezypa5Rhlu4Z7kznDwr5GJ9SZ9rEib6huUGhCn7fz1nN7qL9WyvMZq7qbv1/ToXW9ROMPRmi4MuCgJYyQFJFvQuHcer+t8SBwzKLrHCYDAAAAAAAAAAAAAAABAAAADW5leHQtMjAteWVhcnMAAAAAAAAAAF0rggQAAAAAgVzwaQAAAAAAAACCAAAAFXBlcm1pdC1YMTEtZm9yd2FyZGluZwAAAAAAAAAXcGVybWl0LWFnZW50LWZvcndhcmRpbmcAAAAAAAAAFnBlcm1pdC1wb3J0LWZvcndhcmRpbmcAAAAAAAAACnBlcm1pdC1wdHkAAAAAAAAADnBlcm1pdC11c2VyLXJjAAAAAAAAAAAAAAEXAAAAB3NzaC1yc2EAAAADAQABAAABAQC48zvKsJplnaLTbXo0263ABcXqtl9D0O+hm2jxhqoJ/lS77IAuLoDZwYnaWizYvOknWgY66svE5EkY8kspro4tzSgLG0r9kncWlfNNEJb64kem/K9kiHJLpBvmaup0ZUFhg5BcpNmhDhlU5fm0+NI4+qgRvYXbM1rys8nxobtXGOJIFbNf9GkwA7eHpx/J6dPrDZ2QxUBzEy07fiGe7viGgF1xTaNjIwNuVWu3oz+XXzEqMC0mXsVxalA0qT0ol2arROYNWAp6/qNjGlu5VA1tFGUi1gGwIZ3++yEmJerTSV6OHns2g4JGcDvVU8i0KWvyi2o0xmgUbRgABjMFWSWDAAABDwAAAAdzc2gtcnNhAAABALCrG6ZqRt1Cm9mhYw821/XkMR+KyERtU3u/RufJqJLecPX7NeaZAFAG3EVXKOmomMgnLiN8bjElZ2j/Qss/OgTlWlSCtv5mLxfNk56r0DRnZgPyd9sREoww57KpFAmprPELKTt4pqrPULF/YmDP6CVNbeOclsryJoP54SuVTq5EjrAlB4hzU0/4DgVsyyxxIrGXP+Q51Q1S7RtDWV7aD8ljiW3MLLFLploPZ9tWtGZeoLiSBCvoFId2VZUSguzaGdPrj1g5yK0RUaM6nSYhEVS/YqzEUxEdlpcnooBLfC9OkycKEgZDwfdmiLH7NKm3VBciL5fvpmwoIdRpCsKM38Q= swick@8470p ssh-tools/examples/keys/000077500000000000000000000000001457514604400156145ustar00rootroot00000000000000ssh-tools/examples/keys/id_rsa_1.pub000066400000000000000000000006161457514604400200100ustar00rootroot00000000000000ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA2/hTtNC2+Oh7jRiq3l5jAFfUxcx8xZhNcuJV8ci67quIoLlsdPsuG7/6+1vg3GESnKozDfOntRdQMxRRdkiCNWGtDvY3BOMJ16T7dTrSNZnPkStpRkZguEqH3Zdey/ShSpgo5cWk0M/puq0KT8YBgH1669cQZyHIToXU0MKDwTEr0G3hwGuxOWw1HmXnh6yCeMtSfSspLP8YSZgw+S10hRJZxpZYPRhmZ3axJuprh8SdfDRpGUV21V6XJBc7ObrSml56DJJjvkpEOkIxPVllJDWhm2IxELd3Zh1yFUe4X2Halhpwx5KurUTDoUgoDCC1OFYX/w3oVqgywxGkzrg0zw== www@iZ23omxvgedZ ssh-tools/examples/keys/id_rsa_2.pub000066400000000000000000000013461457514604400200120ustar00rootroot00000000000000ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEAwrr66r8n6B8Y0zMF3dOpXEapIQD9DiYQ6D6/zwor9o39jSkHNiMMER/GETBbzP83LOcekm02aRjo55ArO7gPPVvCXbrirJu9pkm4AC4BBre5xSLS7soyzwbigFruM8G63jSXqpHqJ/ooi168sKMC2b0Ncsi+JlTfNYlDXJVLKEeZgZOInQyMmtisaDTUQWTIv1snAizf4iIYENuAkGYGNCL77u5Y5VOu5eQipvFajTnps9QvUx/zdSFYn9e2sulWM3Bxc/S4IJ67JWHVRpfJxGi3hinRBH8WQdXuUwdJJTiJHKPyYrrM7Q6Xq4TOMFtcRuLDC6u3BXM1L0gBvHPNOnD5l2Lp5EjUkQ9CBf2j4A4gfH+iWQZyk08esAG/iwArAVxkl368+dkbMWOXL8BN4x5zYgdzoeypQZZ2RKH780MCTSo4WQ19DP8pw+9q3bSFC9H3xYAxrKAJNWjeTUJOTrTe+mWXXU770gYyQTxa2ycnYrlZucn1S3vsvn6eq7NZZ8NRbyv1n15Ocg+nHK4fuKOrwPhU3NbKQwtjb0Wsxx1gAmQqIOLTpAdsrAauPxC7TPYA5qQVCphvimKuhQM/1gMV225JrnjspVlthCzuFYUjXOKC3wxz6FFEtwnXu3uC5bVVkmkNadJmD21gD23yk4BraGXVYpRMIB+X+OTUUI8= dhopson@VMUbuntu-DSH ssh-tools/examples/keys/id_rsa_3.pub000066400000000000000000000006441457514604400200130ustar00rootroot00000000000000ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCtRr15KNnY3mR3r+H+Cy0C0Wyow7gScBTXx+euP2RoO9xHurphg7rvvGENWTfOlk/qzj9V2+BbwkU7tZa7uRC0fLxodKKr+QTO2BXxRGdipkQpjdflUxeascMTEG6WOIsNfmn2+uaPapKNedpTE2bf22hHGlooDqqmFjdfFU17dBWSMKJ8yQCgOCFJ5DVM3c0/t+teShLkXmVzU0G/rKrZDXjKZUlS1B7t46NhgY99ATi/go1/hs3lNMQP+gpc/FM9IM6Y6eWXoS3F6nTbibavVdsx/qig8sbv6FqoEi2cDx2QyPlXjLCVlt2Z1kv+KhXX8fltjmBifFgiq/H35cZT hs@schlittermann.de openpgp:0x0A51ECF9 ssh-tools/examples/keys/id_rsa_4.pub000066400000000000000000000013421457514604400200100ustar00rootroot00000000000000ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDR8v5+P4jvK0ITa62f3HvX7hfHHscjkO/IHKklXGDGpbjqVj95E6Qg2afG7pLNP+U2Ati+E/9lzA6xuRz7/BFOn0zJLP4bzSnCIumMeTe+4l6VxkPxAd8x6MJ8rqN+PnyY7J1ekbruINv0vd4wnvH2q2h8qOs1y65WdzN4WfDJP9v4u4ySLji14/kcmIafJGIMa8bemvdmeVA6R5WQ6WY8A6TCVi8lt9SelPyRfNwbDmhOp6obbxDBct+oaCMFepSfwKxYJ8LO/e9srNx2vOcji1xDUT0YXEnY+DfBNiBDB/2uTOBuw7zl/w0k4V+R2s/D4nogwGgm0QevadAddx+QXXwzEyWWX1cuk3Ufx3zQkEDzV+x9E+ARJLU9Xs0cvhR0RmovBkqsaJIGwppPPkBO+9wrwjFN2NDx8rLUlIWQyPIjwhIbWpOzjxaIJLJkqQhF7onr90huEUFiW+Zjq+OE9ovls1ORYHPgH1Vd7S+J4jlNZEEDX6KJ7gOCk5yQK80H1cdWFuqPD3k+qKfOaRh89Xk2dv7y6TY+RB4JATUWqadT6kmmpKlqnaKe67yuE1KssDczl+8k+1eiNhSexdfmy9ny75Oav4ZyXBZLkya4a6Q2h+s7TAyPeh/n5Ixe5N8CUejBLx/rbeHd+Z3X67SNeLyTW+5nv48EqCT9qbGoGw== heiko@jumper ssh-tools/ssh-certinfo000077500000000000000000000174311457514604400153630ustar00rootroot00000000000000#!/usr/bin/env bash # +------------------------------------------------------------------+ # | Title : ssh-certinfo | # | Description : shows validity and information of SSH certificates | # | Author : Sven Wick | # | URL : https://codeberg.org/vaporup/ssh-tools | # +------------------------------------------------------------------+ # shellcheck disable=SC2207 # # Some colors for better output # RED='\033[0;91m' GREEN='\033[0;92m' YELLOW='\033[0;93m' RESET='\033[0m' # # Defaults # WARN=30 # days before cert expires # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [OPTIONS] CERT-FILE [...] OPTIONS: -c show colors -h Show this message -w days warning threshold (default: 30) -v Verbose output Examples: Default: ${0##*/} ~/.ssh/id_rsa-cert.pub ${0##*/} ~/.ssh/*.pub Certificates which expire within the next 2 months (colored output): ${0##*/} -c -w 60 ~/.ssh/id_rsa-cert.pub ${0##*/} -c -w 60 ~/.ssh/*.pub EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi # # Command line Options # # shellcheck disable=SC2249 while getopts ":chvw:" opt; do case ${opt} in c ) colors="yes" ;; h ) usage exit 1 ;; v ) verbose="yes" ;; w ) [[ ${OPTARG} =~ ^[0-9]+$ ]] && WARN=${OPTARG} ;; \? ) echo "Invalid option: ${OPTARG}" 1>&2 usage exit 1 ;; esac done function return_epoch_from_date_string() { # # date behaves differently on *BSD, Busybox, etc.. # Trying multiple variants and use first that succeeds # DATES=() # # GNU date # DATES+=( $( date -d "$1" +%s 2>/dev/null || echo NO_DATE ) ) # # BSD date # DATES+=( $( date -j -f "%Y-%m-%dT%T" "$1" "+%s" 2>/dev/null || echo NO_DATE ) ) # # BusyBox # DATES+=( $( date -d "${1//T/ }" +%s 2>/dev/null || echo NO_DATE ) ) for DATE in "${DATES[@]}"; do if [[ ${DATE} -gt 0 ]]; then echo "${DATE}" break fi done } function print_cert() { ssh-keygen -L -f "${cert}" echo } function get_cert_data() { valid_from=$( echo "${valid}" | awk '{print $3}' ) valid_to=$( echo "${valid}" | awk '{print $5}' ) valid_from_epoch=$( return_epoch_from_date_string "${valid_from}" ) valid_to_epoch=$( return_epoch_from_date_string "${valid_to}" ) valid_to_epoch_warning=$(( valid_to_epoch - WARN_SECONDS )) expires_in_days=$(( WARN - ( ( now - valid_to_epoch_warning ) / 60 / 60 / 24 ) -1 )) } function print_if_certs_were_found() { if grep -q "yes" "${certs_found}"; then echo else if [[ ${colors} == yes ]]; then echo -e -n "${YELLOW}" echo -e "No SSH certificates found.\n" echo -e -n "${RESET}" else echo -e "No SSH certificates found.\n" fi fi } function cert_is_valid() { if [[ ${now} -gt ${valid_from_epoch} && ${now} -lt ${valid_to_epoch} ]]; then return 0 else return 1 fi } function cert_is_invalid() { if [[ ${now} -lt ${valid_from_epoch} ]]; then return 0 else return 1 fi } function cert_is_expired() { if [[ ${now} -gt ${valid_to_epoch} ]]; then return 0 else return 1 fi } function cert_expires() { if [[ ${now} -gt ${valid_to_epoch_warning} ]]; then return 0 else return 1 fi } WARN_SECONDS=$(( WARN * 24 * 60 * 60)) CERTS=( "${@:${OPTIND}}" ) now=$(date +%s) certs_found="$(mktemp)" trap 'rm -f ${certs_found}' EXIT echo if [[ ${verbose} == yes ]]; then for cert in "${CERTS[@]}"; do valid=$( print_cert 2>/dev/null | grep -i valid) if [[ -z ${valid} ]]; then continue else echo "yes" > "${certs_found}" fi if [[ ${valid} == *"forever"* ]]; then if [[ ${colors} == yes ]]; then echo -e -n "${GREEN}" print_cert echo -e -n "${RESET}" continue else print_cert continue fi fi get_cert_data if cert_is_invalid; then if [[ ${colors} == yes ]]; then echo -e -n "${YELLOW}" print_cert echo -e -n "${RESET}" continue else print_cert continue fi fi if cert_is_expired; then if [[ ${colors} == yes ]]; then echo -e -n "${RED}" print_cert echo -e -n "${RESET}" continue else print_cert continue fi fi if cert_expires; then if [[ ${colors} == yes ]]; then echo -e -n "${YELLOW}" print_cert echo -e -n "${RESET}" continue else print_cert continue fi fi if cert_is_valid; then if [[ ${colors} == yes ]]; then echo -e -n "${GREEN}" print_cert echo -e -n "${RESET}" continue else print_cert continue fi fi done print_if_certs_were_found else for cert in "${CERTS[@]}"; do valid=$( print_cert 2>/dev/null | grep -i valid) if [[ -z ${valid} ]]; then continue else echo "yes" > "${certs_found}" fi if [[ ${valid} == *"forever"* ]]; then if [[ ${colors} == yes ]]; then echo -e "${GREEN}${cert} SSH_CERT_VALID forever -> forever${RESET}" continue else echo "${cert} SSH_CERT_VALID forever -> forever" continue fi fi get_cert_data if cert_is_invalid; then if [[ ${colors} == yes ]]; then echo -e "${YELLOW}${cert} SSH_CERT_INVALID ${valid_from} -> ${valid_to}${RESET}" continue else echo "${cert} SSH_CERT_INVALID ${valid_from} -> ${valid_to}" continue fi fi if cert_is_expired; then if [[ ${colors} == yes ]]; then echo -e "${RED}${cert} SSH_CERT_EXPIRED ${valid_from} -> ${valid_to}${RESET}" continue else echo "${cert} SSH_CERT_EXPIRED ${valid_from} -> ${valid_to}" continue fi fi if cert_expires; then if [[ ${colors} == yes ]]; then echo -e "${YELLOW}${cert} SSH_CERT_EXPIRES_IN_${expires_in_days}_DAYS ${valid_from} -> ${valid_to} ${RESET}" continue else echo "${cert} SSH_CERT_EXPIRES_IN_${expires_in_days}_DAYS ${valid_from} -> ${valid_to}" continue fi fi if cert_is_valid; then if [[ ${colors} == yes ]]; then echo -e "${GREEN}${cert} SSH_CERT_VALID ${valid_from} -> ${valid_to}${RESET}" continue else echo "${cert} SSH_CERT_VALID ${valid_from} -> ${valid_to}" continue fi fi done | column -t print_if_certs_were_found fi ssh-tools/ssh-diff000077500000000000000000000166611457514604400144660ustar00rootroot00000000000000#!/usr/bin/env bash # +---------------------------------------------------------------------------------------------------+ # | Title : ssh-diff | # | Description : Diff a file over SSH | # | Author : Sven Wick | # | Contributors : Denis Meiswinkel | # | URL : https://codeberg.org/vaporup/ssh-tools | # | Based On : https://gist.github.com/jhqv/dbd59f5838ae8c83f736bfe951bd80ff | # | https://serverfault.com/questions/59140/how-do-diff-over-ssh#comment1027981_216496 | # +---------------------------------------------------------------------------------------------------+ # shellcheck disable=SC2029 # # Some colors for better output # RED='\033[0;91m' BOLD='\033[1m' RESET='\033[0m' # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [OPTIONS] FILE [user@]hostname[:FILE] There is an extra roundtrip to the remote system to check for the existence of the file to be diffed. So if you are not using SSH Keys you may get prompted twice for a password. Use "CHECK_REMOTE_FILE_EXISTS=NO ${0##*/}" to disable that behavior Diff Options: All options your local diff command supports ( except '-r' ). See 'man diff' and 'diff --help' for more information. SSH Options: -4 Use IPv4 only -6 Use IPv6 only -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. Examples: Default: ${0##*/} /etc/hosts 192.168.1.10 ${0##*/} /etc/hosts root@192.168.1.10 ${0##*/} /etc/hosts root@192.168.1.10:/etc/hosts.old Side-by-Side: ${0##*/} -y /etc/hosts 192.168.1.10 ${0##*/} -y /etc/hosts root@192.168.1.10 ${0##*/} -y /etc/hosts root@192.168.1.10:/etc/hosts.old Unified: ${0##*/} -u /etc/hosts 192.168.1.10 ${0##*/} -u /etc/hosts root@192.168.1.10 ${0##*/} -u /etc/hosts root@192.168.1.10:/etc/hosts.old EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi if ! [[ $# -ge 2 ]]; then echo -e "\n ${RED}Error: Not all filenames given${RESET}" >&2 usage exit 1 fi function supports_colordiff() { type colordiff &> /dev/null } function show_header() { echo "" echo -e "Comparing ${BOLD}${remote_host}:${remote_file}${RESET} (<) with ${BOLD}${local_file}${RESET} (>)" echo "" } function login_successful_and_remote_file_exists() { # shellcheck disable=SC2154 if [[ ${CHECK_REMOTE_FILE_EXISTS} == "NO" ]]; then return 0 fi if [[ -z "${username}" ]]; then ssh "${ssh_params[@]}" "${remote_host}" "test -e ${remote_file}" &> /dev/null else ssh "${ssh_params[@]}" "${username}@${remote_host}" "test -e ${remote_file}" &> /dev/null fi RETVAL=$? [[ ${RETVAL} -eq 255 ]] && { echo -e "\n ${RED}Error: Could not connect to remote server${RESET}\n" >&2 ; exit "${RETVAL}"; } [[ ${RETVAL} -ge 1 ]] && { echo -e "\n ${RED}Error: Remote file ${remote_file} not found${RESET}\n" >&2 ; exit "${RETVAL}"; } [[ ${RETVAL} -eq 0 ]] && true } function diff_files() { if [[ -z "${username}" ]]; then if login_successful_and_remote_file_exists; then show_header if supports_colordiff; then ssh "${ssh_params[@]}" "${remote_host}" "cat ${remote_file}" | diff "${diff_params[@]}" --label "${remote_host}:${remote_file}" - "${local_file}" | colordiff else # Pipe the output to cat after diffing # # test.sh fails when colordiff is not installed. # Reason is that a normal diff returns with 1 # when files differ but colordiff changes the return code to 0. ssh "${ssh_params[@]}" "${remote_host}" "cat ${remote_file}" | diff "${diff_params[@]}" --label "${remote_host}:${remote_file}" - "${local_file}" | cat fi fi else if login_successful_and_remote_file_exists; then show_header if supports_colordiff; then ssh "${ssh_params[@]}" "${username}@${remote_host}" "cat ${remote_file}" | diff "${diff_params[@]}" --label "${remote_host}:${remote_file}" - "${local_file}" | colordiff else # Pipe the output to cat after diffing # # test.sh fails when colordiff is not installed. # Reason is that a normal diff returns with 1 # when files differ but colordiff changes the return code to 0. ssh "${ssh_params[@]}" "${username}@${remote_host}" "cat ${remote_file}" | diff "${diff_params[@]}" --label "${remote_host}:${remote_file}" - "${local_file}" | cat fi fi fi } # # MAIN # # # Get all params from command line # params=( "$@" ) # # Get last 2 params, store them away and remove them so only diff params are left # remote_params="${params[ ${#params[@]}-1 ]}" && unset 'params[ ${#params[@]}-1 ]' local_filename="${params[ ${#params[@]}-1 ]}" && unset 'params[ ${#params[@]}-1 ]' diff_params=( "${params[@]}" ) # # Fish within diff params for ssh options and extract them # diff_params_index=0 ssh_params=() ssh_params_indices=() for param in "${diff_params[@]}"; do next_diff_params_index=$(( diff_params_index +1 )) # # find -p # if [[ ${param} == "-p" ]] && [[ -z "${diff_params[${next_diff_params_index}]//[0-9]}" ]]; then ssh_params_indices+=( "${diff_params_index}" "${next_diff_params_index}" ) ssh_params+=( "${param}" "${diff_params[${next_diff_params_index}]}" ) fi # # find -4 or -6 # if [[ ${param} == "-4" ]] || [[ ${param} == "-6" ]]; then ssh_params_indices+=( "${diff_params_index}" ) ssh_params+=( "${param}" ) fi diff_params_index=$(( diff_params_index +1 )) done # shellcheck disable=SC2034 for ssh_param in "${ssh_params_indices[@]}"; do # shellcheck disable=SC2184 # shellcheck disable=SC2102 unset diff_params[$ssh_param] done # # Getting username, hostname and filename from command line without using grep and awk # # user@host:filename -> user gets stored in $username # -> host gets stored in $remote_host # -> filename gets stored in $remote_file # if [[ ${remote_params} == *"@"* ]]; then remote_part="${remote_params##*@}" username="${remote_params%%@*}" else remote_part=${remote_params} fi if [[ ${remote_part} == *":"* ]]; then remote_file="${remote_part##*:}" remote_host="${remote_part%%:*}" else remote_host=${remote_part} fi local_file=$(readlink -f "${local_filename}") # get absolute path to file in case it was relative if [[ -z "${local_file}" ]]; then echo -e "\n ${RED}Error: Given file not found${RESET}\n" >&2 exit 1 fi if [[ ! -f ${local_file} ]]; then echo -e "\n ${RED}Error: Local file ${local_file} not found${RESET}\n" >&2 exit 1 fi if [[ -z "${remote_file}" ]]; then remote_file=${local_file} fi # # Finally diff them! # diff_files ssh-tools/ssh-facts000077500000000000000000000431271457514604400146530ustar00rootroot00000000000000#!/usr/bin/env bash # +-----------------------------------------------------------------------------------------------------+ # | Title : ssh-facts | # | Description : Get some facts about the remote system | # | Author : Sven Wick | # | Contributors : Denis Meiswinkel | # | URL : https://codeberg.org/vaporup/ssh-tools | # | Based On : https://code.ungleich.ch/ungleich-public/cdist/src/branch/master/cdist/conf/explorer | # | https://serverfault.com/a/343678 | # | https://stackoverflow.com/a/8057052 | # +-----------------------------------------------------------------------------------------------------+ # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [user@]hostname For further processing of the data you can use standard shell tools like awk, grep, sed or convert it to JSON with 'jo' (command-line processor to output JSON from a shell) and feed it to 'jq' (lightweight and flexible command-line JSON processor) Examples: ${0##*/} 127.0.0.1 ${0##*/} 127.0.0.1 | grep ^OS_VERSION | awk -F'=' '{ print \$2 }' ${0##*/} 127.0.0.1 | jo -p ${0##*/} 127.0.0.1 | jo | jq ${0##*/} 127.0.0.1 | jo | jq .OS_VERSION EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi ssh "$@" 'bash -s' 2>/dev/null <<'END' | sed 's/[[:space:]]*=[[:space:]]*/=/' function _os() { if grep -q ^Amazon /etc/system-release 2>/dev/null; then echo amazon exit 0 fi if [ -f /etc/arch-release ]; then echo archlinux exit 0 fi if [ -f /etc/cdist-preos ]; then echo cdist-preos exit 0 fi if [ -d /gnu/store ]; then echo guixsd exit 0 fi ### Debian and derivatives if grep -q ^DISTRIB_ID=Ubuntu /etc/lsb-release 2>/dev/null; then echo ubuntu exit 0 fi # devuan ascii has both devuan_version and debian_version, so we need to check devuan_version first! if [ -f /etc/devuan_version ]; then echo devuan exit 0 fi if [ -f /etc/debian_version ]; then echo debian exit 0 fi ### if [ -f /etc/gentoo-release ]; then echo gentoo exit 0 fi if [ -f /etc/openwrt_version ]; then echo openwrt exit 0 fi if [ -f /etc/owl-release ]; then echo owl exit 0 fi ### Redhat and derivatives if grep -q ^Scientific /etc/redhat-release 2>/dev/null; then echo scientific exit 0 fi if grep -q ^CentOS /etc/redhat-release 2>/dev/null; then echo centos exit 0 fi if grep -q ^Fedora /etc/redhat-release 2>/dev/null; then echo fedora exit 0 fi if grep -q ^Mitel /etc/redhat-release 2>/dev/null; then echo mitel exit 0 fi if [ -f /etc/redhat-release ]; then echo redhat exit 0 fi ### if [ -f /etc/SuSE-release ]; then echo suse exit 0 fi if [ -f /etc/slackware-version ]; then echo slackware exit 0 fi # Appliances if grep -q '^Check Point Gaia' /etc/cp-release 2>/dev/null; then echo checkpoint exit 0 fi uname_s="$(uname -s)" # Assume there is no tr on the client -> do lower case ourselves case "$uname_s" in Darwin) echo macosx exit 0 ;; NetBSD) echo netbsd exit 0 ;; FreeBSD) echo freebsd exit 0 ;; OpenBSD) echo openbsd exit 0 ;; SunOS) echo solaris exit 0 ;; esac if [ -f /etc/os-release ]; then # after sles15, suse don't provide an /etc/SuSE-release anymore, but there is almost no difference between sles and opensuse leap, so call it suse # shellcheck disable=SC1091 if (. /etc/os-release && echo "${ID_LIKE}" | grep -q '\(^\|\ \)suse\($\|\ \)') then echo suse exit 0 fi # already lowercase, according to: # https://www.freedesktop.org/software/systemd/man/os-release.html awk -F= '/^ID=/ { if ($2 ~ /^'"'"'(.*)'"'"'$/ || $2 ~ /^"(.*)"$/) { print substr($2, 2, length($2) - 2) } else { print $2 } }' /etc/os-release exit 0 fi echo "Unknown OS" >&2 exit 1 } # # os_version # function rc_getvar() { awk -F= -v varname="$2" ' function unquote(s) { if (s ~ /^".*"$/ || s ~ /^'\''.*'\''$/) return substr(s, 2, length(s) - 2) else return s } $1 == varname { print unquote(substr($0, index($0, "=") + 1)) }' "$1" } function _os_version() { case "$(_os)" in amazon) cat /etc/system-release ;; archlinux) # empty, but well... cat /etc/arch-release ;; checkpoint) awk '{version=$NF; printf("%s\n", substr(version, 2))}' /etc/cp-release ;; debian) debian_version=$(cat /etc/debian_version) case $debian_version in testing/unstable) # previous to Debian 4.0 testing/unstable was used # cf. https://metadata.ftp-master.debian.org/changelogs/main/b/base-files/base-files_11_changelog echo 3.99 ;; */sid) # sid versions don't have a number, so we decode by codename: case $(expr "$debian_version" : '\([a-z]\{1,\}\)/') in trixie) echo 12.99 ;; bookworm) echo 11.99 ;; bullseye) echo 10.99 ;; buster) echo 9.99 ;; stretch) echo 8.99 ;; jessie) echo 7.99 ;; wheezy) echo 6.99 ;; squeeze) echo 5.99 ;; lenny) echo 4.99 ;; *) echo 99.99 ;; esac ;; *) echo "$debian_version" ;; esac ;; devuan) devuan_version=$(cat /etc/devuan_version) case ${devuan_version} in (*/ceres) # ceres versions don't have a number, so we decode by codename: case ${devuan_version} in (daedalus/ceres) echo 4.99 ;; (chimaera/ceres) echo 3.99 ;; (beowulf/ceres) echo 2.99 ;; (ascii/ceres) echo 1.99 ;; (*) exit 1 esac ;; (*) echo "${devuan_version}" ;; esac ;; fedora) cat /etc/fedora-release ;; gentoo) cat /etc/gentoo-release ;; macosx) # NOTE: Legacy versions (< 10.3) do not support options sw_vers | awk -F ':[ \t]+' '$1 == "ProductVersion" { print $2 }' ;; freebsd) # Apparently uname -r is not a reliable way to get the patch level. # See: https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=251743 if command -v freebsd-version >/dev/null 2>&1 then # get userland version freebsd-version -u else # fallback to kernel release for FreeBSD < 10.0 uname -r fi ;; *bsd|solaris) uname -r ;; openwrt) cat /etc/openwrt_version ;; owl) cat /etc/owl-release ;; redhat|centos|mitel|scientific) cat /etc/redhat-release ;; slackware) cat /etc/slackware-version ;; suse) if [ -f /etc/os-release ]; then cat /etc/os-release else cat /etc/SuSE-release fi ;; ubuntu) if command -v lsb_release >/dev/null 2>&1 then lsb_release -sr elif test -r /usr/lib/os-release then # fallback to /usr/lib/os-release if lsb_release is not present (like # on minimized Ubuntu installations) rc_getvar /usr/lib/os-release VERSION_ID elif test -r /etc/lsb-release then # extract DISTRIB_RELEASE= variable from /etc/lsb-release on old # versions without /usr/lib/os-release. rc_getvar /etc/lsb-release DISTRIB_RELEASE fi ;; alpine) cat /etc/alpine-release ;; esac } function _uptime() { if command -v uptime >/dev/null; then uptime | awk -F'( |,|:)+' '{if ($7=="min") m=$6; else {if ($7~/^day/) {d=$6;h=$8;m=$9} else {h=$6;m=$7}}} {print d+0,"days,",h+0,"hours,",m+0,"minutes"}' fi } function _last_reboot() { if command -v last >/dev/null; then last reboot -F | head -1 | awk '{print $6,$7,$8,$9}' fi } function _cpu_cores() { os=$(_os) case "$os" in "macosx") sysctl -n hw.physicalcpu ;; "openbsd") sysctl -n hw.ncpuonline ;; "freebsd"|"netbsd") PATH=$(getconf PATH) sysctl -n hw.ncpu ;; *) if [ -r /proc/cpuinfo ]; then cores="$(grep "core id" /proc/cpuinfo | sort | uniq | wc -l)" if [ "${cores}" -eq 0 ]; then cores="1" fi echo "$cores" fi ;; esac } function _cpu_sockets() { os=$(_os) case "$os" in "macosx") system_profiler SPHardwareDataType | grep "Number of Processors" | awk -F': ' '{print $2}' ;; *) if [ -r /proc/cpuinfo ]; then sockets="$(grep "physical id" /proc/cpuinfo | sort -u | wc -l)" if [ "${sockets}" -eq 0 ]; then sockets="$(grep -c "processor" /proc/cpuinfo)" fi echo "${sockets}" fi ;; esac } function _hostname() { if command -v hostname >/dev/null then hostname else uname -n fi } function _kernel_name() { uname -s } function _machine() { if command -v uname >/dev/null 2>&1 ; then uname -m fi } function _machine_type() { if [ -d "/proc/vz" ] && [ ! -d "/proc/bc" ]; then echo openvz exit fi if [ -e "/proc/1/environ" ] && tr '\000' '\n' < "/proc/1/environ" | grep -Eiq '^container='; then echo lxc exit fi if [ -r /proc/cpuinfo ]; then # this should only exist on virtual guest machines, # tested on vmware, xen, kvm if grep -q "hypervisor" /proc/cpuinfo; then # this file is aviable in xen guest systems if [ -r /sys/hypervisor/type ]; then if grep -q -i "xen" /sys/hypervisor/type; then echo virtual_by_xen exit fi else if [ -r /sys/class/dmi/id/product_name ]; then if grep -q -i 'vmware' /sys/class/dmi/id/product_name; then echo "virtual_by_vmware" exit elif grep -q -i 'bochs' /sys/class/dmi/id/product_name; then echo "virtual_by_kvm" exit elif grep -q -i 'virtualbox' /sys/class/dmi/id/product_name; then echo "virtual_by_virtualbox" exit fi fi if [ -r /sys/class/dmi/id/sys_vendor ]; then if grep -q -i 'qemu' /sys/class/dmi/id/sys_vendor; then echo "virtual_by_kvm" exit fi fi if [ -r /sys/class/dmi/id/chassis_vendor ]; then if grep -q -i 'qemu' /sys/class/dmi/id/chassis_vendor; then echo "virtual_by_kvm" exit fi fi fi echo "virtual_by_unknown" else echo "physical" fi else echo "unknown" fi } function _memory() { os=$(_os) case "$os" in "macosx") echo "$(sysctl -n hw.memsize)/1024" | bc ;; "openbsd") echo "$(sysctl -n hw.physmem) / 1048576" | bc ;; *) if [ -r /proc/meminfo ]; then grep "MemTotal:" /proc/meminfo | awk '{print $2}' fi ;; esac } function _init() { uname_s="$(uname -s)" case "$uname_s" in Linux) (pgrep -P0 -l | awk '/^1[ \t]/ {print $2;}') || true ;; FreeBSD|OpenBSD) ps -o comm= -p 1 || true ;; *) # return a empty string as unknown value echo "" ;; esac } function _lsb_codename() { set +e case "$(_os)" in checkpoint) awk '{printf("%s\n", $(NF-1))}' /etc/cp-release ;; openwrt) # shellcheck disable=SC1091 (. /etc/openwrt_release && echo "$DISTRIB_CODENAME") ;; *) lsb_release=$(command -v lsb_release) if [ -x "$lsb_release" ]; then $lsb_release --short --codename fi ;; esac } function _lsb_description() { set +e case "$(_os)" in checkpoint) cat /etc/cp-release ;; openwrt) # shellcheck disable=SC1091 (. /etc/openwrt_release && echo "$DISTRIB_DESCRIPTION") ;; *) lsb_release=$(command -v lsb_release) if [ -x "$lsb_release" ]; then $lsb_release --short --description fi ;; esac } function _lsb_id() { set +e case "$(_os)" in checkpoint) echo "CheckPoint" ;; openwrt) # shellcheck disable=SC1091 (. /etc/openwrt_release && echo "$DISTRIB_ID") ;; *) lsb_release=$(command -v lsb_release) if [ -x "$lsb_release" ]; then $lsb_release --short --id fi ;; esac } function _lsb_release() { set +e case "$(_os)" in checkpoint) sed /etc/cp-release -e 's/.* R\([1-9][0-9]*\)\.[0-9]*$/\1/' ;; openwrt) # shellcheck disable=SC1091 (. /etc/openwrt_release && echo "$DISTRIB_RELEASE") ;; *) lsb_release=$(command -v lsb_release) if [ -x "$lsb_release" ]; then $lsb_release --short --release fi ;; esac } function _runlevel() { set +e executable=$(command -v runlevel) if [ -x "$executable" ]; then "$executable" | awk '{ print $2 }' fi } function _disks() { uname_s="$(uname -s)" case "$uname_s" in FreeBSD) sysctl -n kern.disks ;; OpenBSD) sysctl -n hw.disknames | grep -Eo '[lsw]d[0-9]+' ;; NetBSD) PATH=$(getconf PATH) sysctl -n hw.disknames | awk -v RS=' ' '/^[lsw]d[0-9]+/' ;; Linux) # list of major device numbers toexclude: # ram disks, floppies, cdroms # https://www.kernel.org/doc/Documentation/admin-guide/devices.txt ign_majors='1 2 11' if command -v lsblk >/dev/null 2>&1 then lsblk -e "$(echo "$ign_majors" | tr ' ' ',')" -dno name elif test -d /sys/block/ then # shellcheck disable=SC2012 ls -1 /sys/block/ \ | awk -v ign_majors="$(echo "$ign_majors" | tr ' ' '|')" ' { devfile = "/sys/block/" $0 "/dev" getline devno < devfile close(devfile) if (devno !~ "^(" ign_majors "):") print }' else echo "Don't know how to list disks on Linux without lsblk and sysfs." >&2 echo 'If you can, please submit a patch.'>&2 fi ;; *) printf "Don't know how to list disks for %s operating system.\n" "${uname_s}" >&2 printf 'If you can please submit a patch\n' >&2 ;; esac \ | xargs } function _interfaces() { if command -v ip >/dev/null then ip -o link show | sed -n 's/^[0-9]\+: \(.\+\): <.*/\1/p' elif command -v ifconfig >/dev/null then ifconfig -a | sed -n -E 's/^(.*)(:[[:space:]]*flags=|Link encap).*/\1/p' fi \ | sort -u \ | xargs } function get_facts() { local function_name=${1} local label=$( echo "${function_name/_/}" | tr '[:lower:]' '[:upper:]' ) local fact="$( ${function_name} )" [[ -n "${fact// }" ]] && echo "${label}=${fact}" } get_facts _os get_facts _os_version get_facts _uptime get_facts _last_reboot get_facts _cpu_cores get_facts _cpu_sockets get_facts _hostname get_facts _kernel_name get_facts _machine get_facts _machine_type get_facts _memory get_facts _init get_facts _lsb_codename get_facts _lsb_description get_facts _lsb_id get_facts _lsb_release get_facts _runlevel get_facts _disks get_facts _interfaces END ssh-tools/ssh-force-password000077500000000000000000000024721457514604400165070ustar00rootroot00000000000000#!/usr/bin/env bash # +---------------------------------------------------------------------------------------------------------------+ # | Title : ssh-force-password | # | Description : Enforces password authentication (as long as the server allows it) | # | It became quite annoying googling the SSH options for this every time | # | Author : Sven Wick | # | URL : https://codeberg.org/vaporup/ssh-tools | # | Based On : https://www.cyberciti.biz/faq/howto-force-ssh-client-login-to-use-only-password-authentication | # +---------------------------------------------------------------------------------------------------------------+ # shellcheck disable=SC2029 ssh_opts=( -o "PreferredAuthentications=password" -o "PubkeyAuthentication=no" ) # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [DEFAULT SSH OPTIONS] hostname Enforces password authentication (for password testing) EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi ssh "${ssh_opts[@]}" "$@" ssh-tools/ssh-hostkeys000077500000000000000000000052211457514604400154150ustar00rootroot00000000000000#!/usr/bin/env bash # +-----------------------------------------------------------------------------------------------+ # | Title : ssh-hostkeys | # | Description : Prints server host keys in several formats | # | Author : Sven Wick | # | Contributors : Geert Stappers | # | URL : https://codeberg.org/vaporup/ssh-tools | # | Based On : https://unix.stackexchange.com/questions/126908/get-ssh-server-key-fingerprint | # +-----------------------------------------------------------------------------------------------+ # shellcheck disable=SC2207 # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [OPTIONS] hostname OPTIONS: -4 Use IPv4 only -6 Use IPv6 only -h Show this message -T timeout Time to wait for a response, in seconds -p port Port to connect to on the remote host. EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi # # Command line Options # SSH_FLAGS=() # shellcheck disable=SC2249 while getopts ":46hp:T:" opt; do case ${opt} in 4 ) SSH_FLAGS+=("-4") ;; 6 ) SSH_FLAGS+=("-6") ;; h ) usage exit 1 ;; p ) [[ ${OPTARG} =~ ^[0-9]+$ ]] && SSH_FLAGS+=("-p") && SSH_FLAGS+=("${OPTARG}") ;; T ) SSH_FLAGS+=("-T") && SSH_FLAGS+=("${OPTARG}") ;; \? ) echo "Invalid option: ${OPTARG}" 1>&2 usage exit 1 ;; esac done shift $((OPTIND - 1)) remote_host=$1 the_hostkeys=$( mktemp /tmp/ssh-hostkeys.XXXXXX ) trap 'rm -f $the_hostkeys' EXIT ssh-keyscan "${SSH_FLAGS[@]}" "${remote_host}" > "${the_hostkeys}" 2>/dev/null fingerprint_hashes=( md5 sha256 ) function get_fingerprints () { hash_type=$1 ssh-keygen -E "${hash_type}" -qlf "${the_hostkeys}" | while IFS= read -r line; do key_data=( $(printf '%s\n' "${line}") ) key_size=${key_data[0]} key_hash=${key_data[1]} #key_remote_host=${key_data[2]} key_type=${key_data[3]} key_hash_type="${key_hash%%:*}" key_hash_data="${key_hash#*:}" printf "%10s%6s%8s %s\n" "${key_type}" "${key_size}" "${key_hash_type}" "${key_hash_data}" done } for fingerprint_hash in "${fingerprint_hashes[@]}"; do get_fingerprints "${fingerprint_hash}" done | sort ssh-tools/ssh-keyinfo000077500000000000000000000025111457514604400152070ustar00rootroot00000000000000#!/usr/bin/env bash # +------------------------------------------------------+ # | Title : ssh-keyinfo | # | Description : Prints keys in several formats | # | Author : Sven Wick | # | URL : https://codeberg.org/vaporup/ssh-tools | # +------------------------------------------------------+ # shellcheck disable=SC2207 # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} FILE [...] Examples: ${0##*/} ~/.ssh/id_rsa.pub ${0##*/} ~/.ssh/*.pub EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi fingerprint_hashes=( md5 sha256 ) function get_fingerprints () { hash_type=$1 key_file=$2 ssh-keygen -E "${hash_type}" -qlf "${key_file}" | while IFS= read -r line; do key_data=( $(printf '%s\n' "${line}") ) key_size=${key_data[0]} key_hash=${key_data[1]} #key_comment=${key_data[2]} key_type=${key_data[-1]} key_hash_type="${key_hash%%:*}" key_hash_data="${key_hash#*:}" printf "%10s%6s%8s %-50s %s\n" "${key_type}" "${key_size}" "${key_hash_type}" "${key_hash_data}" "${key_file}" done } KEYS=( "$@" ) for KEY in "${KEYS[@]}"; do for fingerprint_hash in "${fingerprint_hashes[@]}"; do get_fingerprints "${fingerprint_hash}" "${KEY}" done done ssh-tools/ssh-last000077500000000000000000001373221457514604400145170ustar00rootroot00000000000000#!/usr/bin/env perl # +-------------------------------------------------------+ # | Title : ssh-last | # | Description : like last but for SSH sessions | # | Author : Sven Wick | # | URL : https://codeberg.org/vaporup/ssh-tools | # +-------------------------------------------------------+ # Die Implementierung dieser Software beruht ganz oder in Teilen # auf Konzepten und Ideen, die mit freundlicher Genehmigung der Firma AB+M GmbH # mit Sitz in Karlsruhe (Deutschland) dem firmeninternen Python-Skript ssh_last entnommen wurden. # The implementation of this software is based in whole # or in part on concepts and ideas taken from a Python script called ssh_last, # by courtesy of the company AB+M GmbH, based in Karlsruhe (Germany). # ************************************************************************** # # "You may sometimes find that others have made # more of your ideas than you have yourself" # # -- Tim O'Reilly # # http://radar.oreilly.com/2009/01/work-on-stuff-that-matters-fir.html # # ************************************************************************** # Divergence to the original: # =========================== # # 1) Perl instead of Python # # 2) Works on a broad set of operating systems not only the latest Ubuntu # - Major GNU/Linux distributions # - Niche GNU/Linux distributions like guix, void, etc... # - Major BSD distributions like OpenBSD, FreeBSD, DragonFlyBSD, # works even on Firewall appliances like pfSense and OPNSense # # 3) Uses systemd's journal by default and logfiles only as a fallback # when run on Non-Linux or Non-systemd Linux systems # and you can even pipe in the logs. # # 4) The algorithm to reconstruct SSH sessions works differently: # # Some distributions, especially some BSDs, do different privilege separation # which results in changing the PID during login phase for a normal user connection # # https://security.stackexchange.com/questions/115896/can-someone-explain-how-sshd-does-privilege-separation # # Relying upon PIDs is therefore not very robust # because you can't map login and logout session afterwards anymore # so a different algorithm using TCP ports was used instead # (the port stays the same during the whole session including login phase) # # Also, finding the logout timestamp is implemented in a more precise fashion: # # The original version fetches just the last log of a PID # which sometimes creates a false positive # when a SSH session was not closed cleanly and the PID was recycled for another SSH session. # # This implementation therefore uses a counting algorithm # to piece together a SSH session by its Accepted and Disconnected logline # # More info: https://utcc.utoronto.ca/~cks/space/blog/linux/OpenSSHDisconnectLogging # # 5) The "Known" and "Ignored" mechanics are implemented # in a hierarchical filesystem manner instead of hardcoding them into the script # # 6) The output includes some flags which give a hint about which auth type was used: # # e.g: # # (C) sshd authorized login via (c)ertificate # (K) sshd authorized login via public (k)ey # (?) sshd authorized login via some other type (password, pam) use strict; use warnings; use Memoize; use Pod::Usage; use Getopt::Std; use Data::Dumper; use Time::Piece; use Time::Seconds; use File::Basename; use Term::ANSIColor; $Data::Dumper::Sortkeys = 1; # +-------+ # | USAGE | # +-------+ sub print_usage { pod2usage(); return; } sub print_usage_full { pod2usage(-verbose => 2); return; } if ( defined($ARGV[0]) ) { if ( $ARGV[0] eq '-h' or $ARGV[0] eq '--help' ) { &print_usage; exit; } if ( $ARGV[0] eq '-?' ) { &print_usage_full; exit; } } # +---------+ # | OPTIONS | # +---------+ my %opts; my $show_all = 0; my $colors = 0; my $debug = 0; my $show_fingerprints = 0; my $show_cert_ids = 0; my $show_host_in_clear = 0; my $who_mode = 0; my $use_logfiles = 0; getopts('acdfilnw', \%opts); $show_all = 1 if $opts{a}; $colors = 1 if $opts{c}; $debug = 1 if $opts{d}; $show_fingerprints = 1 if $opts{f}; $show_cert_ids = 1 if $opts{i}; $show_host_in_clear = 1 if $opts{n}; $who_mode = 1 if $opts{w}; $use_logfiles = 1 if $opts{l}; # +---------+ # | REGEXES | # +---------+ # # (default) # # These very likely change further down the code for different operating systems my $matches_login = '^(?\w+\s+\d+\s+\d+:\d+:\d+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Accepted\s+(?\S+)' . '\s+for\s+(?\S+)' . '\s+from\s+(?\S+)' . '\s+port\s+(?\d+)\s+ssh2:?\s*(?
.*)' ; my $matches_logout = '^(?\w+\s+\d+\s+\d+:\d+:\d+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Disconnected' . '\s+from\s+user\s+(?\S+)' . '\s+(?\S+)' . '\s+port\s+(?\d+)' ; my $matches_cert = '^(?\S+-CERT) (?\S+)' . ' ID (?\S+)' ; my $matches_key = '^(?\w+) (?\S+)' ; # +-----------------+ # | DATA STRUCTURES | # +-----------------+ my %session_ids_counter; # Self-created IDs # from network port and count of its occurence # in chronological order from logfiles # # Example with Port 1234 # # - First occurrence in log -> ID = 1234-1 # - Second occurrence in log -> ID = 1234-2 my @ssh_session_ids; # List to store Login IDs in chronological order my %ssh_sessions; # Hash to store all the data we parse from logs my %last_session_at_port; # TCP Ports get recycled after many logins, # so store the last session to a used port # +------------------------------------------+ # | SUBS FOR DATE AND TIME STRING FORMATTING | # +------------------------------------------+ sub str2epoch { my (@args) = @_; my $str = $args[0]; #my $now = localtime; my $now = Time::Piece->new(); my $year = $now->year; # YEAR is missing in syslog timestamp, so add the current year. # # Example: "Aug 23 00:22:05" -> "2022 Aug 23 00:22:05" $str =~ s/^/$year /g; # Parse Timestamp string # # Force localtime instead UTC # https://stackoverflow.com/a/47722347 my $t = localtime->strptime($str, '%Y %b %d %H:%M:%S'); # If the timestamp is in the future, it is from last year. if ( $t > $now ) { $t = $t - ONE_YEAR; } return $t->epoch; } sub str2epoch_opensuse { my (@args) = @_; my $str = $args[0]; my $now = Time::Piece->new(); # Parse Timestamp string # # Force localtime instead UTC # https://stackoverflow.com/a/47722347 my $t = localtime->strptime($str, '%Y-%m-%d %H:%M:%S'); return $t->epoch; } sub format_seconds { # 1 year = 31557600 seconds my (@args) = @_; my $total_seconds = $args[0]; my ($hours, $hourremainder) = (($total_seconds/(60*60)), $total_seconds % (60*60)); my ($minutes, $seconds) = (int $hourremainder / 60, $hourremainder % 60); ($hours, $minutes, $seconds) = (sprintf('%02d', $hours), sprintf('%02d', $minutes), sprintf('%02d', $seconds)); return $hours . ':' . $minutes . ':' . $seconds; } # +-------------------+ # | ignored and known | # +-------------------+ my $matches_data = '\s*(?\S+)\s*(?.*)'; my @ignored_files = ( '/etc/ssh-tools/ssh-last/ignored', glob('~/.config/ssh-tools/ssh-last/ignored'), 'ignored', ); my @known_files = ( '/etc/ssh-tools/ssh-last/known', glob('~/.config/ssh-tools/ssh-last/known'), 'known', ); sub get_file_data { my $data_type = $_[0]; my %file_data; my @data_files; if ( $data_type eq 'ignored' ) { @data_files = @ignored_files; } if ( $data_type eq 'known' ) { @data_files = @known_files; } foreach my $data_file (@data_files) { if ( -r $data_file ) { open( my $file_fh, '<', $data_file ); while ( my $line = <$file_fh> ) { chomp($line); if ($line =~ /^\s*#.*/ ) { next; } # Ignore comments if ($line =~ /$matches_data/ ) { my $key = $+{KEY}; my $value = $+{VALUE}; $value =~ s/#+.*$//g; # Remove comment from rest of the line $value =~ s/\s+$//g; # Remove whitespace from rest of the line $file_data{$key} = $value; } } } } return %file_data; }; my %ignored = get_file_data('ignored'); my %known = get_file_data('known'); # +--------------------------------------------------------------+ # | SUBS FOR MAPPING A FINGERPRINT IN .ssh/authorized_keys | # | TO ITS COMMENT FIELD (using ssh-keygen -lf) | # | TO SHOW THE COMMENT IN THE OUTPUT INSTEAD OF THE FINGERPRINT | # +--------------------------------------------------------------+ sub get_ssh_keygen_data { my $fh = $_[0]; my @lines = `ssh-keygen -lf $fh`; return @lines; } # Caching the result, so the data does not need to be generated again and again. # Saves further unnecessarily calls of ssh-keygen. memoize('get_ssh_keygen_data'); sub detail_from_fingerprint { my $user = $_[0]; my $fp = $_[1]; if ($known{$fp}) { return $known{$fp}; } if ($ignored{$fp}) { return $ignored{$fp}; } # In scalar context, glob iterates through such filename expansions, # returning undef when the list is exhausted. # # So, we use a list first # # https://stackoverflow.com/questions/1274642/why-does-perls-glob-return-undef-for-every-other-call my @authorized_keys_files = glob("~${user}/.ssh/authorized_keys"); my $authorized_keys_file = $authorized_keys_files[0]; if ( $authorized_keys_file ) { if ( -r $authorized_keys_file ) { my @lines = get_ssh_keygen_data($authorized_keys_file); my $data = $fp; foreach my $line (@lines) { chomp $line; my @columns = split(' ', $line); my $fingerprint = $columns[1]; my $comment = $columns[2]; if ( $fp eq $fingerprint ) { $data = $comment; last; } } return $data; } else { return $fp; } } else { return $fp; } } # +--------------+ # | PARSING LOGS | # +--------------+ my $log_cmd_files_dragonfly = 'zgrep -hE "Accepted|Disconnected"' . ' /var/log/auth.log.6.gz' . ' /var/log/auth.log.5.gz' . ' /var/log/auth.log.4.gz' . ' /var/log/auth.log.3.gz' . ' /var/log/auth.log.2.gz' . ' /var/log/auth.log.1' . ' /var/log/auth.log' . ' 2>/dev/null'; my $log_cmd_files = 'zgrep -hE "Accepted|Disconnected"' . ' $(ls /var/log/auth.log* --sort=time --reverse)' . ' prevent-grep-to-wait' . ' 2>/dev/null'; my $log_cmd_files_secure = 'zgrep -hE "Accepted|Disconnected"' . ' $(ls /var/log/secure* --sort=time --reverse)' . ' prevent-grep-to-wait' . ' 2>/dev/null'; my $log_cmd_files_messages = 'zgrep -hE "Accepted|Disconnected"' . ' $(ls /var/log/messages* --sort=time --reverse)' . ' prevent-grep-to-wait' . ' 2>/dev/null'; my $log_cmd_files_alpine = 'grep -hE "Accepted|Disconnected"' . ' /var/log/messages.0' . ' /var/log/messages' . ' 2>/dev/null'; my $log_cmd_files_openbsd = 'zgrep -hE "Accepted|Disconnected"' . ' /var/log/authlog.6.gz' . ' /var/log/authlog.5.gz' . ' /var/log/authlog.4.gz' . ' /var/log/authlog.3.gz' . ' /var/log/authlog.2.gz' . ' /var/log/authlog.1.gz' . ' /var/log/authlog.0.gz' . ' /var/log/authlog' . ' 2>/dev/null'; my $log_cmd_files_freebsd = 'zgrep -hE "Accepted|Disconnected"' . ' /var/log/auth.log.6.bz2' . ' /var/log/auth.log.5.bz2' . ' /var/log/auth.log.4.bz2' . ' /var/log/auth.log.3.bz2' . ' /var/log/auth.log.2.bz2' . ' /var/log/auth.log.1.bz2' . ' /var/log/auth.log.0.bz2' . ' /var/log/auth.log' . ' 2>/dev/null'; my $log_cmd_files_pfsense = 'grep -hE "Accepted|Disconnected"' . ' /var/log/auth.log.6.bz2' . ' /var/log/auth.log.5.bz2' . ' /var/log/auth.log.4.bz2' . ' /var/log/auth.log.3.bz2' . ' /var/log/auth.log.2.bz2' . ' /var/log/auth.log.1.bz2' . ' /var/log/auth.log.0.bz2' . ' /var/log/auth.log' . ' 2>/dev/null'; my $log_cmd_files_opnsense = 'grep -hE "Accepted|Disconnected"' . ' /var/log/audit/latest.log' . ' 2>/dev/null'; my $log_cmd_journal = 'LC_TIME=C journalctl _COMM=sshd --no-pager -g "Accepted|Disconnected"'; my $log_cmd_journal_grep = 'LC_TIME=C journalctl _COMM=sshd --no-pager | grep -E "Accepted|Disconnected"'; # # Try first via journalctl # my $log_cmd = $log_cmd_journal; # # or via logfiles if requested by the user # if ( $use_logfiles ) { $log_cmd = $log_cmd_files; } # # Try different methods depending on operating system # my %os_data; $os_data{TYPE} = $^O; $os_data{ID} = '-'; if ( -e '/etc/pfSense-rc' ) { $os_data{ID} = 'pfsense'; } if ( -e '/usr/local/sbin/opnsense-shell' ) { $os_data{ID} = 'opnsense'; } if ( -r '/etc/os-release' ) { open( my $os_release_fh, '<', '/etc/os-release' ); while ( my $line = <$os_release_fh> ) { chomp($line); if ($line) { my @cols = split('=', $line) ; my $key = $cols[0]; my $value = $cols[1]; $value =~ s/"//g; # Remove all quotes: "10" -> 10 $os_data{$key} = $value; } } } if ( $debug ) { print Dumper \%os_data; } if ( $os_data{TYPE} eq 'linux' ) { if ( $os_data{ID} eq 'debian' ) { # Debian Buster misses grep support in journalctl # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=890265 if ( $os_data{VERSION_CODENAME} && $os_data{VERSION_CODENAME} eq 'buster' ) { $log_cmd = $log_cmd_journal_grep; $log_cmd = $log_cmd_files if $use_logfiles; } } if ( $os_data{ID} eq 'pureos' ) { # Misses grep support in journalctl # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=890265 if ( $os_data{VERSION_CODENAME} eq 'amber' ) { $log_cmd = $log_cmd_journal_grep; $log_cmd = $log_cmd_files if $use_logfiles; } } if ( $os_data{ID} eq 'ubuntu' ) { if ( $os_data{VERSION_CODENAME} eq 'xenial' ) { # Ubuntu Xenial misses grep support in journalctl $log_cmd = $log_cmd_journal_grep; $log_cmd = $log_cmd_files if $use_logfiles; # Xenial logs Disconnects differently # # Normal: Disconnected from user root 192.168.1.101 port 48356 # Xenial: Disconnected from 192.168.1.101 port 48356 $matches_logout = '^(?\w+\s+\d+\s+\d+:\d+:\d+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Disconnected' . '\s+from' . '\s+(?\S+)' . '\s+port\s+(?\d+)' ; # Ubuntu Xenial does not log Fingerprint in CERT Details $matches_cert = '^(?\S+-CERT)' . ' ID (?\S+)' ; } if ( $os_data{VERSION_CODENAME} eq 'bionic' ) { # Ubuntu Bionic misses grep support in journalctl $log_cmd = $log_cmd_journal_grep; $log_cmd = $log_cmd_files if $use_logfiles; # Ubuntu Bionic does not log Fingerprint in CERT Details $matches_cert = '^(?\S+-CERT)' . ' ID (?\S+)' ; } } if ( $os_data{ID} eq 'mageia' ) { # Mageia 8 misses grep support in journalctl if ( $os_data{VERSION_ID} eq '8' ) { $log_cmd = $log_cmd_journal_grep; } } if ( $os_data{ID} eq 'opensuse-leap' ) { # OpenSUSE Leap 15.2 misses grep support in journalctl if ( $os_data{VERSION_ID} eq '15.2' ) { $log_cmd = $log_cmd_journal_grep; } # OpenSUSE Leap 15.4 grep support in journalctl does not work if ( $os_data{VERSION_ID} eq '15.4' ) { $log_cmd = $log_cmd_journal_grep; } if ( $use_logfiles ) { $log_cmd = $log_cmd_files_messages; $matches_login = '^(?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})' . '\.(?\S+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Accepted\s+(?\S+)' . '\s+for\s+(?\S+)' . '\s+from\s+(?\S+)' . '\s+port\s+(?\d+)\s+ssh2:?\s*(?
.*)' ; $matches_logout = '^(?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})' . '\.(?\S+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Disconnected' . '\s+from\s+user\s+(?\S+)' . '\s+(?\S+)' . '\s+port\s+(?\d+)' ; } } if ( $os_data{ID} eq 'alpine' ) { # Alpine uses OpenRC so we have to use logfiles $log_cmd = $log_cmd_files_alpine; $matches_login = '^(?\w+\s+\d+\s+\d+:\d+:\d+)' . '\s+(?\S+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Accepted\s+(?\S+)' . '\s+for\s+(?\S+)' . '\s+from\s+(?\S+)' . '\s+port\s+(?\d+)\s+ssh2:?\s*(?
.*)' ; $matches_logout = '^(?\w+\s+\d+\s+\d+:\d+:\d+)' . '\s+(?\S+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Disconnected' . '\s+from\s+user\s+(?\S+)' . '\s+(?\S+)' . '\s+port\s+(?\d+)' ; } if ( $os_data{ID} eq 'devuan' ) { # Devuan uses other Init systems so we have to use logfiles $log_cmd = $log_cmd_files; if ( $os_data{PRETTY_NAME} =~ /ascii\s*$/ ) { # Devuan 2 ASCII logs Disconnects differently # # Normal: Disconnected from user root 192.168.1.101 port 48356 # Devuan: Disconnected from 192.168.1.101 port 48356 $matches_logout = '^(?\w+\s+\d+\s+\d+:\d+:\d+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Disconnected' . '\s+from' . '\s+(?\S+)' . '\s+port\s+(?\d+)' ; # Devuan 2 ASCII does not log Fingerprint in CERT Details $matches_cert = '^(?\S+-CERT)' . ' ID (?\S+)' ; } } if ( $os_data{ID} eq 'trisquel' ) { # Misses grep support in journalctl # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=890265 if ( $os_data{VERSION_CODENAME} && $os_data{VERSION_CODENAME} eq 'etiona' ) { $log_cmd = $log_cmd_journal_grep; $log_cmd = $log_cmd_files if $use_logfiles; } } if ( $os_data{ID_LIKE} && $os_data{ID_LIKE} =~ /rhel|centos|fedora/ ) { $log_cmd = $log_cmd_files_secure if $use_logfiles; } if ( $os_data{ID} eq 'void' ) { $log_cmd = $log_cmd_files_messages; $matches_login = '^(?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})' . '\.(?\S+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Accepted\s+(?\S+)' . '\s+for\s+(?\S+)' . '\s+from\s+(?\S+)' . '\s+port\s+(?\d+)\s+ssh2:?\s*(?
.*)' ; $matches_logout = '^(?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})' . '\.(?\S+)' . '\s+(?\S+)' . '\s+sshd\[(?\d+)\]:' . '\s+Disconnected' . '\s+from\s+user\s+(?\S+)' . '\s+(?\S+)' . '\s+port\s+(?\d+)' ; } if ( $os_data{ID} eq 'slackware' ) { $log_cmd = $log_cmd_files_messages; } if ( $os_data{ID} eq 'guix' ) { $log_cmd = $log_cmd_files_messages; } } if ( $os_data{TYPE} eq 'openbsd' ) { $log_cmd = $log_cmd_files_openbsd; } if ( $os_data{TYPE} eq 'freebsd' ) { $log_cmd = $log_cmd_files_freebsd; if ( $os_data{ID} && $os_data{ID} eq 'pfsense' ) { # pfSense announces itself as freebsd # but ships with an old zgrep version # that ignores -h and still shows filenames $log_cmd = $log_cmd_files_pfsense; } if ( $os_data{ID} && $os_data{ID} eq 'opnsense' ) { # pfSense announces itself as freebsd $log_cmd = $log_cmd_files_opnsense; $matches_login = '^<.*>\d+\s*(?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})' . '\+(?\S+)' . '\s+(?\S+)' . '\s+sshd (?\d+)' . '\s+\-\s+\[meta.*\]' . '\s+Accepted\s+(?\S+)' . '\s+for\s+(?\S+)' . '\s+from\s+(?\S+)' . '\s+port\s+(?\d+)\s+ssh2:?\s*(?
.*)' ; $matches_logout = '^<.*>\d+\s*(?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})' . '\+(?\S+)' . '\s+(?\S+)' . '\s+sshd (?\d+)' . '\s+\-\s+\[meta.*\]' . '\s+Disconnected' . '\s+from\s+user\s+(?\S+)' . '\s+(?\S+)' . '\s+port\s+(?\d+)' ; } } if ( $os_data{TYPE} eq 'dragonfly' ) { $log_cmd = $log_cmd_files_dragonfly; } my $logs_h; # If ssh-last was called from a terminal, get data via log_cmd. # If data comes via STDIN pipe, get it from there. if ( -t STDIN ) { open( $logs_h, '-|', $log_cmd); } else { $logs_h = *STDIN; } my $log_count = 0; while (my $log = <$logs_h>) { print STDERR "Parsing log entries... ($log_count)\r"; $log_count = $log_count + 1; chomp($log); if ( $log =~ /$matches_login/ ) { my $timestamp = $+{TS} ; my $hostname = $+{HOSTNAME} ; my $pid = $+{PID} ; my $user = $+{USER} ; my $host = $+{HOST} ; my $port = $+{PORT} ; my $auth_type = $+{AUTH_TYPE} ; my $details = $+{DETAILS} ; if ( $os_data{ID} eq 'opensuse-leap' && $use_logfiles ) { $timestamp =~ s/T/ /g; } if ( $os_data{ID} eq 'void' ) { $timestamp =~ s/T/ /g; } if ( $os_data{ID} eq 'opnsense' ) { $timestamp =~ s/T/ /g; } $session_ids_counter{$port}{login_count}++; my $session_id = $port . '-' . $session_ids_counter{$port}{login_count}; push @ssh_session_ids, $session_id; $last_session_at_port{$port} = $session_id; $ssh_sessions{$session_id}{login} = $timestamp ; $ssh_sessions{$session_id}{logout} = '-' ; $ssh_sessions{$session_id}{hostname} = $hostname ; $ssh_sessions{$session_id}{pid} = $pid ; $ssh_sessions{$session_id}{user} = $user ; $ssh_sessions{$session_id}{host} = $host ; $ssh_sessions{$session_id}{port} = $port ; $ssh_sessions{$session_id}{auth_type} = $auth_type ; $ssh_sessions{$session_id}{details} = $details ; $ssh_sessions{$session_id}{auth_id} = '-' ; $ssh_sessions{$session_id}{session_id} = $session_id; unless ( $show_host_in_clear ) { if ( $known{$host} ) { $ssh_sessions{$session_id}{host} = $known{$host} ; } } if ( $auth_type eq 'publickey' ) { $ssh_sessions{$session_id}{auth_id} = '(-) ' . $auth_type ; } else { $ssh_sessions{$session_id}{auth_id} = '(?) ' . $auth_type ; } if ( $debug ) { print "\n"; print('> LOG: ' , "$log" , "\n"); print('> TS: ' , "$timestamp" , "\n"); print('> HOSTNAME: ' , "$hostname" , "\n"); print('> PID: ' , "$pid" , "\n"); print('> USER: ' , "$user" , "\n"); print('> HOST: ' , "$host" , "\n"); print('> PORT: ' , "$port" , "\n"); print('> AUTH_TYPE: ' , "$auth_type" , "\n"); print('> DETAILS: ' , "$details" , "\n"); print('> SESSION_ID: ' , "$session_id" , "\n"); } # Set flag to ignore unwanted hosts in output if ( exists $ignored{$host}) { $ssh_sessions{$session_id}{ignore} = 'true'; } my $known_host = $known{$host}; if ( $known_host && exists $ignored{$known_host}) { $ssh_sessions{$session_id}{ignore} = 'true'; } # Set flag to ignore unwanted users in output if ( exists $ignored{$user}) { $ssh_sessions{$session_id}{ignore} = 'true'; } if ( $details ) { if ( $details =~ /$matches_key/ ) { my $key_type = $+{KEY_TYPE} ; my $fingerprint = $+{FINGERPRINT} ; # Set flag to ignore unwanted fingerprints in output if ( exists $ignored{$fingerprint}) { $ssh_sessions{$session_id}{ignore} = 'true'; } $ssh_sessions{$session_id}{key_type} = $key_type; if ( $show_fingerprints ) { $ssh_sessions{$session_id}{auth_id} = '(K) ' . $fingerprint; } else { $ssh_sessions{$session_id}{auth_id} = '(K) ' . detail_from_fingerprint($user ,$fingerprint); } if ( $debug ) { print('> DETAILS: ' , 'KEY_FOUND' , "\n"); print('> KEY_TYPE: ' , "$key_type" , "\n"); print('> FINGERPRINT: ' , "$fingerprint" , "\n"); } } if ( $details =~ /$matches_cert/ ) { my $key_type = $+{KEY_TYPE} ; my $fingerprint = $+{FINGERPRINT} ; my $auth_id = $+{AUTH_ID} ; unless ( $fingerprint ) { $fingerprint = '-'; } # Set flag to ignore unwanted fingerprints in output if ( exists $ignored{$fingerprint}) { $ssh_sessions{$session_id}{ignore} = 'true'; } # Set flag to ignore unwanted cert ids in output if ( exists $ignored{$auth_id}) { $ssh_sessions{$session_id}{ignore} = 'true'; } $ssh_sessions{$session_id}{key_type} = $key_type; if ( $show_fingerprints ) { $ssh_sessions{$session_id}{auth_id} = '(C) ' . $fingerprint; } else { if ( $known{$auth_id} ) { if ( $show_cert_ids ) { $ssh_sessions{$session_id}{auth_id} = '(C) ' . $auth_id; } else { $ssh_sessions{$session_id}{auth_id} = '(C) ' . $known{$auth_id} ; } } else { $ssh_sessions{$session_id}{auth_id} = '(C) ' . $auth_id; } } if ( $debug ) { print('> DETAILS: ' , 'CERT_FOUND' , "\n"); print('> KEY_TYPE: ' , "$key_type" , "\n"); print('> FINGERPRINT: ' , "$fingerprint" , "\n"); print('> AUTH_ID: ' , "$auth_id" , "\n"); } } } } if ( $log =~ /$matches_logout/ ) { my $timestamp = $+{TS} ; my $hostname = $+{HOSTNAME} ; my $user = $+{USER} ; my $pid = $+{PID} ; my $host = $+{HOST} ; my $port = $+{PORT} ; if ( $os_data{ID} eq 'opensuse-leap' && $use_logfiles ) { $timestamp =~ s/T/ /g; } if ( $os_data{ID} eq 'void' ) { $timestamp =~ s/T/ /g; } if ( $os_data{ID} eq 'opnsense' ) { $timestamp =~ s/T/ /g; } my $session_id; if ( $session_ids_counter{$port}{login_count} ) { $session_id = $port . '-' . $session_ids_counter{$port}{login_count}; } else { # If there is no previous login # to this port in log, skip this logline. # # Example: Login line was rolled over by logration # and "Disconnect" is still in log # but the "Accepted" entry was discarded. next; } $ssh_sessions{$session_id}{logout} = $timestamp; if ( $debug ) { print "\n"; print("< $log", "\n"); unless ( $user ) { $user = '-'; } print('< TS: ' , "$timestamp" , "\n"); print('< HOSTNAME: ' , "$hostname" , "\n"); print('< PID: ' , "$pid" , "\n"); print('< USER: ' , "$user" , "\n"); print('< HOST: ' , "$host" , "\n"); print('< PORT: ' , "$port" , "\n"); print('< SESSION_ID: ' , "$session_id" , "\n"); } } } # +----------------+ # | PRINT SESSIONS | # +----------------+ my $output_format = "%-15s %-15s %-10s %-15s %-15s %-5s %-15s\n"; if ( $os_data{ID} && $os_data{ID} eq 'opensuse-leap' && $use_logfiles ) { $output_format = "%-20s %-20s %-10s %-15s %-15s %-5s %-15s\n"; } if ( $os_data{ID} && $os_data{ID} eq 'void' ) { $output_format = "%-20s %-20s %-10s %-15s %-15s %-5s %-15s\n"; } if ( $os_data{ID} && $os_data{ID} eq 'opnsense' ) { $output_format = "%-20s %-20s %-10s %-15s %-15s %-5s %-15s\n"; } print "\n"; if ( $debug ) { print Dumper \%ssh_sessions; } # # HEADER # if ( $colors ) { print color 'bold white'; printf( $output_format, 'LOGIN', 'LOGOUT', 'DURATION', 'USER', 'HOST', 'PORT', 'AUTH_ID', ); print color 'reset'; } else { printf( $output_format, 'LOGIN', 'LOGOUT', 'DURATION', 'USER', 'HOST', 'PORT', 'AUTH_ID', ); } # # SESSIONS # foreach my $session ( @ssh_session_ids ) { # # ignore unwanted data in output # if ( $ssh_sessions{$session}{ignore} ) { # # but not if user insists on seeing them (-a) # unless ( $show_all ) { next; } } my $port = $ssh_sessions{$session}{port}; if ( $ssh_sessions{$session}{logout} eq '-' ) { $ssh_sessions{$session}{duration} = '-'; my $command = "LANG=C ss -tnp state ESTABLISHED | grep -q :\"${port}\\s*users.*sshd\""; if ( $os_data{TYPE} eq 'openbsd' ) { $command = "LANG=C fstat | grep -q \"sshd.*internet.*tcp.*:${port}\""; } if ( $os_data{TYPE} eq 'freebsd' ) { $command = "LANG=C sockstat -c | grep -q \"sshd.*tcp.*:${port}\""; } if ( $os_data{TYPE} eq 'dragonfly' ) { $command = "LANG=C sockstat -c | grep -q \"sshd.*tcp.*:${port}\""; } if ( $os_data{TYPE} eq 'linux' ) { if ( $os_data{ID} eq 'alpine' ) { $command = "LANG=C netstat -n -t | grep -qE \":${port} +ESTABLISHED\""; } } my $error = system $command; if ( $error ) { # That is actually not an error, # it just means that grep did not find # a TCP Session with that port # so we can assume the user is not logged in anymore } else { if ( $last_session_at_port{$port} eq $session ) { $ssh_sessions{$session}{logout} = 'still logged in'; } my $login_epoch; if ( $os_data{ID} && $os_data{ID} eq 'opensuse-leap' && $use_logfiles ) { $login_epoch = str2epoch_opensuse($ssh_sessions{$session}{login}); } elsif ( $os_data{ID} && $os_data{ID} eq 'void' ) { $login_epoch = str2epoch_opensuse($ssh_sessions{$session}{login}); } elsif ( $os_data{ID} && $os_data{ID} eq 'opnsense' ) { $login_epoch = str2epoch_opensuse($ssh_sessions{$session}{login}); } else { $login_epoch = str2epoch($ssh_sessions{$session}{login}); } my $current_time = time(); my $duration = $current_time - $login_epoch; $ssh_sessions{$session}{duration} = format_seconds($duration); } } else { my $login_epoch; my $logout_epoch; if ( $os_data{ID} && $os_data{ID} eq 'opensuse-leap' && $use_logfiles ) { $login_epoch = str2epoch_opensuse($ssh_sessions{$session}{login}); $logout_epoch = str2epoch_opensuse($ssh_sessions{$session}{logout}); } elsif ( $os_data{ID} eq 'void' ) { $login_epoch = str2epoch_opensuse($ssh_sessions{$session}{login}); $logout_epoch = str2epoch_opensuse($ssh_sessions{$session}{logout}); } elsif ( $os_data{ID} eq 'opnsense' ) { $login_epoch = str2epoch_opensuse($ssh_sessions{$session}{login}); $logout_epoch = str2epoch_opensuse($ssh_sessions{$session}{logout}); } else { $login_epoch = str2epoch($ssh_sessions{$session}{login}); $logout_epoch = str2epoch($ssh_sessions{$session}{logout}); } my $duration = $logout_epoch - $login_epoch; $ssh_sessions{$session}{duration} = format_seconds($duration); } if ( $ssh_sessions{$session}{logout} =~ /still/ ) { if ( $colors ) { print color 'bright_cyan'; printf( $output_format, $ssh_sessions{$session}{login}, $ssh_sessions{$session}{logout}, $ssh_sessions{$session}{duration}, $ssh_sessions{$session}{user}, $ssh_sessions{$session}{host}, $ssh_sessions{$session}{port}, $ssh_sessions{$session}{auth_id}, ); print color 'reset'; } else { printf( $output_format, $ssh_sessions{$session}{login}, $ssh_sessions{$session}{logout}, $ssh_sessions{$session}{duration}, $ssh_sessions{$session}{user}, $ssh_sessions{$session}{host}, $ssh_sessions{$session}{port}, $ssh_sessions{$session}{auth_id}, ); } } else { if ( $who_mode ) { next; } else { printf( $output_format, $ssh_sessions{$session}{login}, $ssh_sessions{$session}{logout}, $ssh_sessions{$session}{duration}, $ssh_sessions{$session}{user}, $ssh_sessions{$session}{host}, $ssh_sessions{$session}{port}, $ssh_sessions{$session}{auth_id}, ); } } } __END__ =head1 NAME ssh-last - list last SSH sessions =head1 SYNOPSIS ssh-last [OPTIONS] ssh_logs | ssh-last [OPTIONS] =head2 Options -a show all sessions (show data which is hidden by the 'ignored' file) -c colored output (highlight active SSH sessions) -d debug -f force showing fingerprints (no mapping from 'known' file) -h show this help message -i force showing certificate ids (no mapping from 'known' file, not together with -f) -l try to use logfiles instead of journalctl (may be even faster on some systems) -n show host/ip in cleartext (no mapping from 'known' file) -w show only active SSH sessions -? show complete manual with more detailed information (usually needs perl-doc installed to work properly) =head2 Examples ssh-last ssh-last -c | more ssh-last -c | less -R # keeps colored output in less ssh-last -cw # Logs from yesterday LC_TIME=C journalctl _COMM=sshd -g 'Accepted|Disconnected' --since yesterday | ssh-last # Logs from three days ago LC_TIME=C journalctl _COMM=sshd -g 'Accepted|Disconnected' --since -3d --until -2d | ssh-last # Logs from the last hour LC_TIME=C journalctl _COMM=sshd -g 'Accepted|Disconnected' --since -1h | ssh-last # Logs until a specific date LC_TIME=C journalctl _COMM=sshd -g 'Accepted|Disconnected' --until "2022-03-12 07:00:00" | ssh-last # From logfiles (order must be from oldest to newest) zgrep -hE 'Accepted|Disconnected' auth.log.2.gz auth.log.1 auth.log | ssh-last zgrep -hE 'Accepted|Disconnected' $(ls /var/log/auth.log* --sort=time --reverse) | ssh-last zgrep -hE 'Accepted|Disconnected' $(ls /var/log/messages* --sort=time --reverse) | ssh-last zgrep -hE 'Accepted|Disconnected' $(ls /var/log/secure* --sort=time --reverse) | ssh-last =head1 DESCRIPTION ssh-last is like last but for SSH sessions =head2 Output Flags +--------------------------------------------------------------------------+ | | | AUTH_ID | | | | (C) sshd authorized login via (c)ertificate | | (K) sshd authorized login via public (k)ey | | (?) sshd authorized login via some other type (password, pam) | | | +--------------------------------------------------------------------------+ =head2 Algorithm Milling through sshd logs in chronological order: 1) Finding login (Accepted) and logout (Disconnected) lines. 2) Storing info from the lines like username, auth_type, fingerprint, ... 3) Using the used network port to check for active sessions and piecing together old sessions by remembering logged network ports 4) Using mainly /etc/os-release to adapt for different systems which differ in logfile names, logging patterns, etc... =head1 FILES =head2 Ignored /etc/ssh-tools/ssh-last/ignored ~/.config/ssh-tools/ssh-last/ignored ./ignored These data will be hidden in output unless forced with -a option +--------------------------------------------------------------------------+ |# Fingerprints | | | |SHA256:ElgyEn5xPe4VlK5jJkqauRdAKNRHdh2tGHfo0m9/IwW Jenkins | |SHA256:5xPe4JkqaElKNRHGHfxPe4RdAKdh2tlK5AKNRHn5xK5 foo # comment | |SHA256:nmKL5s7/fs45312nvjhFSRTREa44r2hfgJHJG54353R bar@gmx.de | | | |# Hosts | | | |127.0.0.1 localhost # local ssh logins | |192.168.1.50 nas # more comments | |webserver # alias from the 'known' file | | | |# Cert IDs | | | |user1@company.com | |user2@company.com with some info | |user3@company.com with some info # and a comment | | | |# Users | | | |git # gitlab | +--------------------------------------------------------------------------+ =head2 Known /etc/ssh-tools/ssh-last/known ~/.config/ssh-tools/ssh-last/known ./known For these keys the mapped value will be shown instead of its key, unless forced with -f (fingerprints) and -n (hosts) or -i (certificate ids) option +--------------------------------------------------------------------------+ |# Fingerprints | | | |SHA256:WwI/9m0ofHGt2hdHRNKAdRuaqkJj5KlV4ePx5nEyglE Sven Wick | |SHA256:xyk5ZZZWZKnmKL5mYdk8Poy5eds7/CD/JEwqykMnlQQ root@n40l # comment | |SHA256:G7h9i5+NDU72Ae40gCkxyvDz/8BH+KETw7sXHCYr5w0 sven.wick@gmx.de | | | |# Hosts | | | |127.0.0.1 localhost # local ssh logins | |192.168.1.50 nas # more comments | |192.168.50.100 webserver | | | |# Cert IDs | | | |user1@company.com vaporup | +--------------------------------------------------------------------------+ =head1 BUGS AND LIMITATIONS =head2 JumpHosts Using a JumpHost with ProxyCommand oder ProxyJump, may often result in an unclean disconnect with nothing logged, so LOGOUT and DURATION can not be displayed. =head2 Unprivileged users If possible, run ssh-last as root or via sudo 1) Logfiles and systemd's journal usually can't be read by a normal user 2) ssh-last -w works only reliably as root, since ss and netstat do not show process info when invoked as normal user 3) ssh-last tries to map the fingerprint from a user's authorized_keys file but users usually are not allowed to look into each others files =head2 OS Upgrades If you do an in-place upgrade like dist-upgrade on Debian/Ubuntu, depending on the version difference, it can happen that sshd logs differently from that point on and you may have a mix of logs in new and old format which results in ssh-last showing only the latest ones correctly =head2 Log inconsistency I have seen cases where some sshd "Disconnect" log messages were missing in systemd's journal but existed in /var/log/auth.log. So, if ssh-last is not showing a logout and duration but the log lines exist in the logfile, check if the log message really reached systemd's journal since ssh-last defaults to journald =head1 NOTES =head2 Helper Scripts For convenience you can create little wrapper scripts like the following which avoids parsing too many logs by limiting the data only to the last week my-ssh-last +--------------------------------------------------------------------------+ | #!/usr/bin/env bash | | | | LC_TIME=C journalctl _COMM=sshd --since -1week \ | | | grep -E 'Accepted|Disconnected' \ | | | ssh-last "$@" | | | +--------------------------------------------------------------------------+ =head1 SEE ALSO ssh-keyinfo(1), ssh-certinfo(1) =head1 AUTHOR Sven Wick =cut ssh-tools/ssh-ping000077500000000000000000000303361457514604400145060ustar00rootroot00000000000000#!/usr/bin/env bash # +--------------------------------------------------------------------------------------+ # | Title : ssh-ping | # | Description : Check if host is reachable using ssh_config | # | Outputs 'Reply from' when server is reachable but login failed | # | Outputs 'Pong from' when server is reachable and login was successful | # | Author : Sven Wick | # | Contributors : Denis Meiswinkel | # | URL : https://codeberg.org/vaporup/ssh-tools | # | Based On : https://unix.stackexchange.com/a/30146/247383 | # | https://stackoverflow.com/a/33277226 | # +--------------------------------------------------------------------------------------+ # trap CTRL-C and call print_statistics() trap print_statistics SIGINT # # Some colors for better output # RED='\033[0;91m' GREEN='\033[0;92m' YELLOW='\033[0;93m' BLUE='\033[0;94m' MAGENTA='\033[0;95m' CYAN='\033[0;96m' WHITE='\033[0;97m' BOLD='\033[1m' RESET='\033[0m' # # Default SSH Options # SSH_OPTS=( -o "BatchMode=yes" -o "CheckHostIP=no" -o "StrictHostKeyChecking=no" ) # # SSH Flags which get populated later # SSH_FLAGS=() # # Defaults # ping_count=0 # How many requests to do ping_interval=1 # Seconds to wait between sending each request connect_timeout=16 # Seconds to wait for a response ssh_seq=1 # Request Counter requests_transmitted=0 # Count how often we sent a request requests_received=0 # Count how often we got an answer requests_lost=0 # Count how often we lost an answer quiet="no" # Do not suppress output # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [OPTIONS] [user@]hostname OPTIONS: -4 Use IPv4 only -6 Use IPv6 only -c count Stop after sending request packets -C Connect as soon as the host responds and try reconnecting after a SSH session ends (e.g. rebooting). Useful also for IDRAC, IPMI, ILO devices, Switches, etc... which don't have a full shell environment. CTRL+C stops reconnect attempts. -E Exit immediately after first successful ping (can be used to trigger a follow up task like rsync) -F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file ( /etc/ssh/ssh_config ) will be ignored. The default for the per-user configuration file is ~/.ssh/config. -h Show this message -i interval Wait seconds between sending each request. The default is 1 second. -l user Try login with as username. The default is the current value of \$USER. -D Print timestamp (unix time + microseconds as in gettimeofday) before each line -H Print timestamp (human readable) before each line -W timeout Time to wait for a response, in seconds -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. -q Quiet output. Nothing is displayed except the summary lines at startup time and when finished -n No colors. (e.g. for black on white terminals) -v Verbose output TAB_COMPLETIONS: Ubuntu (and maybe other distros) already ship shell completions for ssh which can be used: Bash : complete -F _known_hosts ssh-ping Zsh : compdef _ssh_hosts ssh-ping Fish : complete -c ssh-ping -a "(__fish_print_hostnames)" ENVIRONMENT_VARIABLES: SSH_PING_NO_COLORS if set, no colors are shown (like -n) Example: SSH_PING_NO_COLORS=true ${0##*/} -c 1 hostname EXIT_CODES: 0 No requests lost 1 More than 1 request lost 2 All requests lost Example: ${0##*/} -q -c 1 hostname >/dev/null && echo "Host is up!" ${0##*/} -q -c 1 hostname >/dev/null || echo "Host is down!" EXAMPLES: ${0##*/} -E hostname && echo "First successful ping. Starting rsync..." EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi function command_exists() { command -v "${1}" >/dev/null 2>&1 } function get_timestamp() { if [[ "${print_timestamp_human_readable}" == "yes" ]]; then date else if [[ "${OSTYPE}" == "linux-gnu" ]] && command_exists date; then date +%s.%6N else command_exists perl && perl -MTime::HiRes=time -e 'printf "%.6f", time' fi fi } function get_request_timestamp() { if [[ "${OSTYPE}" == "linux-gnu" ]] && command_exists date; then date +%s%3N else command_exists perl && perl -MTime::HiRes=time -e 'printf "%i", time * 1000' fi } function print_statistics() { [[ ${requests_transmitted} -eq 0 ]] && exit requests_loss=$(( 100 * requests_lost / requests_transmitted )) echo "" echo -e "${WHITE}---${RESET} ${YELLOW}${host}${RESET} ${WHITE}ping statistics${RESET} ${WHITE}---${RESET}" statistics_ok="${GREEN}${requests_transmitted}${RESET} ${WHITE}requests transmitted${RESET}, " statistics_ok+="${GREEN}${requests_received}${RESET} ${WHITE}requests received${RESET}, " statistics_ok+="${GREEN}${requests_loss}%${RESET} ${WHITE}request loss${RESET}" statistics_warn="${YELLOW}${requests_transmitted}${RESET} ${WHITE}requests transmitted${RESET}, " statistics_warn+="${YELLOW}${requests_received}${RESET} ${WHITE}requests received${RESET}, " statistics_warn+="${YELLOW}${requests_loss}%${RESET} ${WHITE}request loss${RESET}" statistics_crit="${RED}${requests_transmitted}${RESET} ${WHITE}requests transmitted${RESET}, " statistics_crit+="${RED}${requests_received}${RESET} ${WHITE}requests received${RESET}, " statistics_crit+="${RED}${requests_loss}%${RESET} ${WHITE}request loss${RESET}" [[ ${requests_loss} -eq 100 ]] && echo -e "${statistics_crit}" && exit 2 [[ ${requests_loss} -gt 1 ]] && echo -e "${statistics_warn}" && exit 1 [[ ${requests_loss} -eq 0 ]] && echo -e "${statistics_ok}" && exit } # # Command line Options # # shellcheck disable=SC2249 while getopts ":46c:CEF:hi:l:DHp:vW:qn" opt; do case ${opt} in 4 ) SSH_FLAGS+=("-4") ;; 6 ) SSH_FLAGS+=("-6") ;; c ) [[ ${OPTARG} =~ ^[0-9]+$ ]] && ping_count=${OPTARG} ;; C ) connect="yes" ;; E ) exit_first_success="yes" ;; F ) SSH_FLAGS+=("-F") SSH_FLAGS+=("${OPTARG}") ;; h ) usage exit 1 ;; i ) ping_interval=${OPTARG} ;; l ) SSH_FLAGS+=("-l") && SSH_FLAGS+=("${OPTARG}") ;; D ) print_timestamp="yes" ;; H ) print_timestamp="yes" print_timestamp_human_readable="yes" ;; p ) [[ ${OPTARG} =~ ^[0-9]+$ ]] && SSH_FLAGS+=("-p") && SSH_FLAGS+=("${OPTARG}") ;; v ) verbose="yes" ;; W ) [[ ${OPTARG} =~ ^[0-9]+$ ]] && connect_timeout=${OPTARG} ;; q ) quiet="yes" ;; n ) colors="no" ;; \? ) echo "Invalid option: ${OPTARG}" 1>&2 usage exit 1 ;; esac done shift $((OPTIND - 1)) SSH_OPTS+=( -o "ConnectTimeout=${connect_timeout}" ) # # Getting username and host from command line without using grep and awk # # user@host -> user gets stored in $username # -> host gets stored in $host # # If no user@ was given on the command line # we just store the last argument as hostname # if [[ $1 == *"@"* ]]; then host="${1##*@}" username="${1%%@*}" else host=${1} fi # # Colors are counter productive # on black on white terminals # # shellcheck disable=SC2154 if [[ -n "${SSH_PING_NO_COLORS}" ]]; then colors="no" fi if [[ ${colors} == no ]]; then unset -v RED GREEN YELLOW BLUE MAGENTA CYAN WHITE BOLD fi [[ -z "${host}" ]] && { echo -e "\n ${RED}Error: No target host given${RESET}" ; usage; exit 1; } # # Output header with optional debugging output # echo -e "${BOLD}SSHPING${RESET} ${YELLOW}${host}${RESET}" if [[ ${verbose} == yes ]]; then echo -e -n "${BLUE}" echo "SSH_FLAGS:" "${SSH_FLAGS[@]}" echo "SSH_OPTS:" "${SSH_OPTS[@]}" echo -e -n "${RESET}" fi if [[ ! "${OSTYPE}" == "linux-gnu" ]]; then command_exists perl || echo -e "${YELLOW}WARNING:${RESET} No perl found, time measure probably fails (${WHITE}time${RESET}=${RED}0${RESET} ms)" >&2 fi while true; do # # ping only $count times or forever if $count = 0 # [[ ${ping_count} -gt 0 ]] && [[ ${ssh_seq} -gt ${ping_count} ]] && break # # used for -D and or -H option # timestamp=$( get_timestamp ) # # Doing the actual request and measure its execution time # start_request=$( get_request_timestamp ) if [[ -z "${username}" ]]; then if [[ "${connect}" == "yes" ]]; then status=$(ssh "${SSH_FLAGS[@]}" "${SSH_OPTS[@]}" "sshping@${host}" echo pong 2>&1 | grep -oE 'pong|denied|sftp') else status=$(ssh "${SSH_FLAGS[@]}" "${SSH_OPTS[@]}" "${host}" echo pong 2>&1 | grep -oE 'pong|denied|sftp') fi else if [[ "${connect}" == "yes" ]]; then status=$(ssh "${SSH_FLAGS[@]}" "${SSH_OPTS[@]}" "sshping@${host}" echo pong 2>&1 | grep -oE 'pong|denied|sftp') else status=$(ssh "${SSH_FLAGS[@]}" "${SSH_OPTS[@]}" "${username}@${host}" echo pong 2>&1 | grep -oE 'pong|denied|sftp') fi fi end_request=$( get_request_timestamp ) time_request=$((end_request-start_request)) # # Output "Pong" if request succeeded by login in and echoing back our string # Output "Reply" if the SSH server is at least talking to us but login was denied # if [[ ${status} == pong ]]; then requests_received=$(( requests_received + 1 )) [[ ${quiet} == no ]] && [[ ${print_timestamp} == yes ]] && echo -e -n "${WHITE}[${RESET}${MAGENTA}${timestamp}${RESET}${WHITE}]${RESET} " [[ ${quiet} == no ]] && echo -e "${GREEN}Pong${RESET} ${WHITE}from${RESET} ${YELLOW}${host}${RESET}${WHITE}: ssh_seq${RESET}=${RED}${ssh_seq}${RESET} ${WHITE}time${RESET}=${RED}${time_request}${RESET} ms" elif [[ ${status} == denied || ${status} == sftp ]]; then requests_received=$(( requests_received + 1 )) [[ ${quiet} == no ]] && [[ ${print_timestamp} == yes ]] && echo -e -n "${WHITE}[${RESET}${MAGENTA}${timestamp}${RESET}${WHITE}]${RESET} " [[ ${quiet} == no ]] && echo -e "${CYAN}Reply${RESET} ${WHITE}from${RESET} ${YELLOW}${host}${RESET}${WHITE}: ssh_seq${RESET}=${RED}${ssh_seq}${RESET} ${WHITE}time${RESET}=${RED}${time_request}${RESET} ms" else requests_lost=$(( requests_lost + 1 )) fi requests_transmitted=${ssh_seq} ssh_seq=$(( ssh_seq + 1 )) if [[ "${connect}" == "yes" ]]; then if [[ -z "${username}" ]]; then ssh "${SSH_FLAGS[@]}" -o "BatchMode=no" "${SSH_OPTS[@]}" "${host}" else ssh "${SSH_FLAGS[@]}" -o "BatchMode=no" "${SSH_OPTS[@]}" "${username}@${host}" fi echo -e "Reconnecting... (Press CTRL+C to abort)" fi # # Don't sleep if we do just 1 request # [[ ${ping_count} -eq 1 ]] || sleep "${ping_interval}" # # Exit after first successful ping # [[ "${exit_first_success}" == "yes" ]] && [[ $requests_received -gt 0 ]] && exit done print_statistics ssh-tools/ssh-pwd000077500000000000000000000043331457514604400143410ustar00rootroot00000000000000#!/usr/bin/env bash # +-------------------------------------------------------------+ # | Title : ssh-pwd | # | Description : quickly echo path to use for scp, rsync | # | Author : Sven Wick | # | Contributors : Florian Sager | # | URL : https://codeberg.org/vaporup/ssh-tools | # | Based On : https://github.com/usrflo/scpwd | # +-------------------------------------------------------------+ # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [PATH] Files: /etc/ssh-tools/ssh-pwd/targets ~/.config/ssh-tools/ssh-pwd/targets Just pust some IPs, FQDNs in there and they will be shown in the output as well EOF } if [[ $1 == "-h" || $1 == "--help" ]]; then usage exit 1 fi SSH_PWD_USER=${USER} SSH_PWD_PATH=${PWD} function get_target_config() { if [[ -e /etc/ssh-tools/ssh-pwd/targets ]]; then sed 's/[[:space:]]*//g' /etc/ssh-tools/ssh-pwd/targets fi if [[ -e ~/.config/ssh-tools/ssh-pwd/targets ]]; then sed 's/[[:space:]]*//g' ~/.config/ssh-tools/ssh-pwd/targets fi } function get_target_ssh_connection() { if [[ -n ${SSH_CONNECTION} ]];then echo "${SSH_CONNECTION}" | awk '{ print $3 }' fi } function get_targets_hostname() { hostname &>/dev/null && hostname hostname -A &>/dev/null && hostname -A hostname -f &>/dev/null && hostname -f hostname -I &>/dev/null && hostname -I hostname -s &>/dev/null && hostname -s } function get_targets() { { get_target_config get_target_ssh_connection get_targets_hostname } | tr ' ' '\n' | sed '/^$/d' | grep -v localhost | sort -u } while read -r target ; do SSH_PWD_TARGET=${target} # # Check for IPv6 # if [[ ${target} =~ : ]]; then SSH_PWD_TARGET="[${target}]" fi # # Get optional path parameter # default: current working dir # if [[ -n "$1" ]]; then realpath -m "$1" &>/dev/null && SSH_PWD_PATH=$(realpath -m "$1") || SSH_PWD_PATH="$1" echo "${SSH_PWD_USER}@${SSH_PWD_TARGET}:${SSH_PWD_PATH}" else echo "${SSH_PWD_USER}@${SSH_PWD_TARGET}:${SSH_PWD_PATH}" fi done < <( get_targets ) ssh-tools/ssh-version000077500000000000000000000027201457514604400152320ustar00rootroot00000000000000#!/usr/bin/env bash # +-----------------------------------------------------------------------------------------------------------+ # | Title : ssh-version | # | Description : Shows version of the SSH server you are connecting to | # | Author : Sven Wick | # | Contributors : Denis Meiswinkel | # | URL : https://codeberg.org/vaporup/ssh-tools | # | Based On : http://www.commandlinefu.com/commands/view/1809/get-the-version-of-sshd-on-a-remote-system | # +-----------------------------------------------------------------------------------------------------------+ ssh_opts=( -o "BatchMode=yes" -o "CheckHostIP=no" -o "StrictHostKeyChecking=no" -o "ConnectTimeout=16" -o "PasswordAuthentication=no" -o "PubkeyAuthentication=no" ) # # Usage/Help message # function usage() { cat << EOF Usage: ${0##*/} [OPTIONS] hostname Examples: ${0##*/} 127.0.0.1 ${0##*/} -p 35007 127.0.0.1 EOF } if [[ -z $1 || $1 == "--help" ]]; then usage exit 1 fi SSH_VERSION=$(ssh -vN "${ssh_opts[@]}" "$@" -l ssh-version 2>&1 | grep "remote software version") echo "${SSH_VERSION#debug1: }"