Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_stormssh.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is based on
3 # the config parser from here: https://github.com/emre/storm/blob/master/storm/parsers/ssh_config_parser.py
4 # Copyright (C) <2013> <Emre Yilmaz>
5 # SPDX-License-Identifier: MIT
6
7 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
8 # Do not use this from other collections or standalone plugins/modules!
9
10 from __future__ import annotations
11
12 import os
13 import re
14 import traceback
15 from operator import itemgetter
16
17 PARAMIKO_IMPORT_ERROR: str | None
18 try:
19 from paramiko.config import SSHConfig
20 except ImportError:
21 SSHConfig = object # type: ignore
22 HAS_PARAMIKO = False
23 PARAMIKO_IMPORT_ERROR = traceback.format_exc()
24 else:
25 HAS_PARAMIKO = True
26 PARAMIKO_IMPORT_ERROR = None
27
28
29 class StormConfig(SSHConfig):
30 def parse(self, file_obj):
31 """
32 Read an OpenSSH config from the given file object.
33 @param file_obj: a file-like object to read the config file from
34 @type file_obj: file
35 """
36 order = 1
37 host = {
38 "host": ["*"],
39 "config": {},
40 }
41 for line in file_obj:
42 line = line.rstrip("\n").lstrip()
43 if line == "":
44 self._config.append(
45 {
46 "type": "empty_line",
47 "value": line,
48 "host": "",
49 "order": order,
50 }
51 )
52 order += 1
53 continue
54
55 if line.startswith("#"):
56 self._config.append(
57 {
58 "type": "comment",
59 "value": line,
60 "host": "",
61 "order": order,
62 }
63 )
64 order += 1
65 continue
66
67 if "=" in line:
68 # Ensure ProxyCommand gets properly split
69 if line.lower().strip().startswith("proxycommand"):
70 proxy_re = re.compile(r"^(proxycommand)\s*=*\s*(.*)", re.I)
71 match = proxy_re.match(line)
72 key, value = match.group(1).lower(), match.group(2)
73 else:
74 key, value = line.split("=", 1)
75 key = key.strip().lower()
76 else:
77 # find first whitespace, and split there
78 i = 0
79 while (i < len(line)) and not line[i].isspace():
80 i += 1
81 if i == len(line):
82 raise Exception(f"Unparsable line: {line!r}")
83 key = line[:i].lower()
84 value = line[i:].lstrip()
85 if key == "host":
86 self._config.append(host)
87 value = value.split()
88 host = {key: value, "config": {}, "type": "entry", "order": order}
89 order += 1
90 elif key in ["identityfile", "localforward", "remoteforward"]:
91 if key in host["config"]:
92 host["config"][key].append(value)
93 else:
94 host["config"][key] = [value]
95 elif key not in host["config"]:
96 host["config"].update({key: value})
97 self._config.append(host)
98
99
100 class ConfigParser:
101 """
102 Config parser for ~/.ssh/config files.
103 """
104
105 def __init__(self, ssh_config_file=None):
106 if not ssh_config_file:
107 ssh_config_file = self.get_default_ssh_config_file()
108
109 self.defaults = {}
110
111 self.ssh_config_file = ssh_config_file
112
113 if not os.path.exists(self.ssh_config_file):
114 if not os.path.exists(os.path.dirname(self.ssh_config_file)):
115 os.makedirs(os.path.dirname(self.ssh_config_file))
116 open(self.ssh_config_file, "w+").close()
117 os.chmod(self.ssh_config_file, 0o600)
118
119 self.config_data = []
120
121 def get_default_ssh_config_file(self):
122 return os.path.expanduser("~/.ssh/config")
123
124 def load(self):
125 config = StormConfig()
126
127 with open(self.ssh_config_file) as fd:
128 config.parse(fd)
129
130 for entry in config.__dict__.get("_config"):
131 if entry.get("host") == ["*"]:
132 self.defaults.update(entry.get("config"))
133
134 if entry.get("type") in ["comment", "empty_line"]:
135 self.config_data.append(entry)
136 continue
137
138 host_item = {
139 "host": entry["host"][0],
140 "options": entry.get("config"),
141 "type": "entry",
142 "order": entry.get("order", 0),
143 }
144
145 if len(entry["host"]) > 1:
146 host_item.update(
147 {
148 "host": " ".join(entry["host"]),
149 }
150 )
151 # minor bug in paramiko.SSHConfig that duplicates
152 # "Host *" entries.
153 if entry.get("config") and len(entry.get("config")) > 0:
154 self.config_data.append(host_item)
155
156 return self.config_data
157
158 def add_host(self, host, options):
159 self.config_data.append(
160 {
161 "host": host,
162 "options": options,
163 "order": self.get_last_index(),
164 }
165 )
166
167 return self
168
169 def update_host(self, host, options, use_regex=False):
170 for index, host_entry in enumerate(self.config_data):
171 if host_entry.get("host") == host or (use_regex and re.match(host, host_entry.get("host"))):
172 if "deleted_fields" in options:
173 deleted_fields = options.pop("deleted_fields")
174 for deleted_field in deleted_fields:
175 del self.config_data[index]["options"][deleted_field]
176
177 self.config_data[index]["options"].update(options)
178
179 return self
180
181 def search_host(self, search_string):
182 results = []
183 for host_entry in self.config_data:
184 if host_entry.get("type") != "entry":
185 continue
186 if host_entry.get("host") == "*":
187 continue
188
189 searchable_information = host_entry.get("host")
190 for value in host_entry.get("options").values():
191 if isinstance(value, list):
192 value = " ".join(value)
193 if isinstance(value, int):
194 value = str(value)
195
196 searchable_information += f" {value}"
197
198 if search_string in searchable_information:
199 results.append(host_entry)
200
201 return results
202
203 def delete_host(self, host):
204 found = 0
205 for index, host_entry in enumerate(self.config_data):
206 if host_entry.get("host") == host:
207 del self.config_data[index]
208 found += 1
209
210 if found == 0:
211 raise ValueError("No host found")
212 return self
213
214 def delete_all_hosts(self):
215 self.config_data = []
216 self.write_to_ssh_config()
217
218 return self
219
220 def dump(self):
221 if len(self.config_data) < 1:
222 return
223
224 file_content = ""
225 self.config_data = sorted(self.config_data, key=itemgetter("order"))
226
227 for host_item in self.config_data:
228 if host_item.get("type") in ["comment", "empty_line"]:
229 file_content += f"{host_item.get('value')}\n"
230 continue
231 host_item_content = f"Host {host_item.get('host')}\n"
232 for key, value in host_item.get("options").items():
233 if isinstance(value, list):
234 sub_content = ""
235 for value_ in value:
236 sub_content += f" {key} {value_}\n"
237 host_item_content += sub_content
238 else:
239 host_item_content += f" {key} {value}\n"
240 file_content += host_item_content
241
242 return file_content
243
244 def write_to_ssh_config(self):
245 with open(self.ssh_config_file, "w+") as f:
246 data = self.dump()
247 if data:
248 f.write(data)
249 return self
250
251 def get_last_index(self):
252 last_index = 0
253 indexes = []
254 for item in self.config_data:
255 if item.get("order"):
256 indexes.append(item.get("order"))
257 if len(indexes) > 0:
258 last_index = max(indexes)
259
260 return last_index