2 ## Copyright (c) 2019 Intel Corporation
4 ## Licensed under the Apache License, Version 2.0 (the "License");
5 ## you may not use this file except in compliance with the License.
6 ## You may obtain a copy of the License at
8 ## http://www.apache.org/licenses/LICENSE-2.0
10 ## Unless required by applicable law or agreed to in writing, software
11 ## distributed under the License is distributed on an "AS IS" BASIS,
12 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ## See the License for the specific language governing permissions and
14 ## limitations under the License.
21 """Wrapper class for paramiko module to connect via SSH
27 _rsa_private_key = None
35 def __init__(self, ip=None, user=None, rsa_private_key=None, timeout=15, logger_name=None):
38 self._rsa_private_key = rsa_private_key
39 self._timeout = timeout
41 if (logger_name is not None):
42 self._log = logging.getLogger(logger_name)
44 self._connected = False
46 def set_credentials(self, ip, user, rsa_private_key):
49 self._rsa_private_key = rsa_private_key
53 if (self._log is not None):
54 self._log.debug("Already connected!")
57 if ((self._ip is None) or (self._user is None) or
58 (self._rsa_private_key is None)):
59 if (self._log is not None):
60 self._log.error("Wrong parameter! IP %s, user %s, RSA private key %s"
61 % (self._ip, self._user, self._rsa_private_key))
62 self._connected = False
65 self._ssh = paramiko.SSHClient()
66 self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
67 private_key = paramiko.RSAKey.from_private_key_file(self._rsa_private_key)
70 self._ssh.connect(hostname = self._ip, username = self._user, pkey = private_key)
71 except Exception as e:
72 if (self._log is not None):
73 self._log.error("Failed to connect to the host! IP %s, user %s, RSA private key %s\n%s"
74 % (self._ip, self._user, self._rsa_private_key, e))
75 self._connected = False
79 self._connected = True
83 self._connected = False
86 def run_cmd(self, cmd):
89 if self._connected is not True:
94 _stdin, stdout, stderr = self._ssh.exec_command(cmd, timeout = self._timeout)
95 self._output = stdout.read()
96 self._error = stderr.read()
97 except Exception as e:
98 if (self._log is not None):
99 self._log.error("Failed to execute command! IP %s, cmd %s\n%s"
100 % (self._ip, cmd, e))
107 def get_output(self):