Debian Codegraph @

lib/jnpr/junos/utils/ssh_client.py

raw
1 import paramiko
2
3
4 def open_ssh_client(dev):
5 """
6 This function is used to return a new paramiko SSH client that uses the same login method &
7 credentials as the original Junos device instance. The purpose of this function is to provide
8 the caller with the complete paramiko library of functionality based on the returned SSH client.
9 :param dev: jnpr.junos.Device instance
10 :return: paramiko.SSHClient instance
11 """
12
13 # note, the following code was extracted from the scp module, and then the scp module
14 # was refactored to use this function
15 ssh_client = paramiko.SSHClient()
16 ssh_client.load_system_host_keys()
17 ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
18
19 # use junos._hostname since this will be correct if we are going
20 # through a jumphost.
21
22 config = {}
23 kwargs = {}
24 ssh_config = getattr(dev, "_sshconf_path")
25 if ssh_config:
26 config = paramiko.SSHConfig()
27 with open(ssh_config) as open_ssh_config:
28 config.parse(open_ssh_config)
29 config = config.lookup(dev._hostname)
30
31 sock = None
32 if config.get("proxycommand"):
33 sock = paramiko.proxy.ProxyCommand(config.get("proxycommand"))
34
35 if dev._ssh_private_key_file is not None:
36 kwargs["key_filename"] = dev._ssh_private_key_file
37
38 # pick hostname from .ssh config if any
39 hostname = config.get("hostname", dev._hostname)
40
41 # Assign the port value
42 port = int(dev.port) if dev._port is not None else 22
43 port = 22 if hostname == "localhost" or dev._port == 830 else port
44
45 ssh_client.connect(
46 hostname=hostname,
47 port=port,
48 username=dev._auth_user,
49 password=dev._auth_password,
50 sock=sock,
51 **kwargs
52 )
53 return ssh_client