Debian Codegraph @

contrib/automation/hgautomation/ssh.py

raw
1 # ssh.py - Interact with remote SSH servers
2 #
3 # Copyright 2019 Gregory Szorc <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 # no-check-code because Python 3 native.
9
10 import socket
11 import time
12 import warnings
13
14 from cryptography.utils import CryptographyDeprecationWarning
15 import paramiko
16
17
18 def wait_for_ssh(hostname, port, timeout=60, username=None, key_filename=None):
19 """Wait for an SSH server to start on the specified host and port."""
20
21 class IgnoreHostKeyPolicy(paramiko.MissingHostKeyPolicy):
22 def missing_host_key(self, client, hostname, key):
23 return
24
25 end_time = time.time() + timeout
26
27 # paramiko triggers a CryptographyDeprecationWarning in the cryptography
28 # package. Let's suppress
29 with warnings.catch_warnings():
30 warnings.filterwarnings(
31 'ignore', category=CryptographyDeprecationWarning
32 )
33
34 while True:
35 client = paramiko.SSHClient()
36 client.set_missing_host_key_policy(IgnoreHostKeyPolicy())
37 try:
38 client.connect(
39 hostname,
40 port=port,
41 username=username,
42 key_filename=key_filename,
43 timeout=5.0,
44 allow_agent=False,
45 look_for_keys=False,
46 )
47
48 return client
49 except OSError:
50 pass
51 except paramiko.AuthenticationException:
52 raise
53 except paramiko.SSHException:
54 pass
55
56 if time.time() >= end_time:
57 raise Exception('Timeout reached waiting for SSH')
58
59 time.sleep(1.0)
60
61
62 def exec_command(client, command):
63 """exec_command wrapper that combines stderr/stdout and returns channel"""
64 chan = client.get_transport().open_session()
65
66 chan.exec_command(command)
67 chan.set_combine_stderr(True)
68
69 stdin = chan.makefile('wb', -1)
70 stdout = chan.makefile('r', -1)
71
72 return chan, stdin, stdout