1 #!/usr/bin/env python2.7
4 ## Copyright (c) 2019 Intel Corporation
6 ## Licensed under the Apache License, Version 2.0 (the "License");
7 ## you may not use this file except in compliance with the License.
8 ## You may obtain a copy of the License at
10 ## http://www.apache.org/licenses/LICENSE-2.0
12 ## Unless required by applicable law or agreed to in writing, software
13 ## distributed under the License is distributed on an "AS IS" BASIS,
14 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 ## See the License for the specific language governing permissions and
16 ## limitations under the License.
23 """Wrapper class for paramiko module to connect via SSH
29 _rsa_private_key = None
37 def __init__(self, ip=None, user=None, rsa_private_key=None, timeout=15, logger_name=None):
40 self._rsa_private_key = rsa_private_key
41 self._timeout = timeout
43 if (logger_name is not None):
44 self._log = logging.getLogger(logger_name)
46 self._connected = False
48 def set_credentials(self, ip, user, rsa_private_key):
51 self._rsa_private_key = rsa_private_key
55 if (self._log is not None):
56 self._log.debug("Already connected!")
59 if ((self._ip is None) or (self._user is None) or
60 (self._rsa_private_key is None)):
61 if (self._log is not None):
62 self._log.error("Wrong parameter! IP %s, user %s, RSA private key %s"
63 % (self._ip, self._user, self._rsa_private_key))
64 self._connected = False
67 self._ssh = paramiko.SSHClient()
68 self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
69 private_key = paramiko.RSAKey.from_private_key_file(self._rsa_private_key)
72 self._ssh.connect(hostname = self._ip, username = self._user, pkey = private_key)
73 except Exception as e:
74 if (self._log is not None):
75 self._log.error("Failed to connect to the host! IP %s, user %s, RSA private key %s\n%s"
76 % (self._ip, self._user, self._rsa_private_key, e))
77 self._connected = False
81 self._connected = True
85 self._connected = False
88 def run_cmd(self, cmd):
91 if self._connected is not True:
96 _stdin, stdout, stderr = self._ssh.exec_command(cmd, timeout = self._timeout)
97 self._output = stdout.read()
98 self._error = stderr.read()
99 except Exception as e:
100 if (self._log is not None):
101 self._log.error("Failed to execute command! IP %s, cmd %s\n%s"
102 % (self._ip, cmd, e))
109 def get_output(self):