Coverage for .tox/coverage/lib/python3.11/site-packages/wuttamess/ssh.py: 100%
14 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-21 07:00 -0600
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-21 07:00 -0600
1# -*- coding: utf-8; -*-
2################################################################################
3#
4# WuttaMess -- Fabric Automation Helpers
5# Copyright © 2024 Lance Edgar
6#
7# This file is part of Wutta Framework.
8#
9# Wutta Framework is free software: you can redistribute it and/or modify it
10# under the terms of the GNU General Public License as published by the Free
11# Software Foundation, either version 3 of the License, or (at your option) any
12# later version.
13#
14# Wutta Framework is distributed in the hope that it will be useful, but
15# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17# more details.
18#
19# You should have received a copy of the GNU General Public License along with
20# Wutta Framework. If not, see <http://www.gnu.org/licenses/>.
21#
22################################################################################
23"""
24SSH Utilities
25"""
28def cache_host_key(c, host, port=None, user=None):
29 """
30 Cache the SSH host key for the given host, for the given user.
32 :param c: Fabric connection.
34 :param host: Name or IP of the host whose key should be cached.
36 Note that you can specify a username along with the hostname if
37 needed, e.g. any of these works:
39 * ``1.2.3.4``
40 * ``foo@1.2.3.4``
41 * ``example.com``
42 * ``foo@example.com``
44 :param port: Optional SSH port for the ``host``; default is 22.
46 :param user: User on the fabric target whose SSH key cache should
47 be updated to include the given ``host``.
48 """
49 port = f'-p {port} ' if port else ''
51 # first try to run a basic command over ssh
52 cmd = f'ssh {port}{host} whoami'
53 if user and user != 'root':
54 result = c.sudo(cmd, user=user, warn=True)
55 else:
56 result = c.run(cmd, warn=True)
58 # no need to update cache if command worked okay
59 if not result.failed:
60 return
62 # basic command failed, but in some cases that is simply b/c
63 # normal commands are not allowed, although the ssh connection
64 # itself was established okay. so here we check for that.
65 if "Disallowed command" in result.stderr:
66 return
68 # okay then we now think that the ssh connection itself
69 # was not made, which presumably means we *do* need to
70 # cache the host key, so try that now
71 cmd = f'ssh -o StrictHostKeyChecking=no {port}{host} whoami'
72 if user and user != 'root':
73 c.sudo(cmd, user=user, warn=True)
74 else:
75 c.run(cmd, warn=True)