Set utf-8 in decode and encode calls
[functest.git] / functest / opnfv_tests / vnf / router / vnf_controller / ssh_client.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 Okinawa Open Laboratory and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """ssh client module for vrouter testing"""
11
12 import logging
13 import time
14 import yaml
15
16 import paramiko
17
18 from functest.opnfv_tests.vnf.router.utilvnf import Utilvnf
19
20 RECEIVE_ROOP_WAIT = 1
21
22 DEFAULT_CONNECT_TIMEOUT = 10
23 DEFAULT_CONNECT_RETRY_COUNT = 10
24 DEFAULT_SEND_TIMEOUT = 10
25
26
27 class SshClient(object):  # pylint: disable=too-many-instance-attributes
28     """ssh client class for vrouter testing"""
29
30     logger = logging.getLogger(__name__)
31
32     def __init__(self, ip_address, user, password=None, key_filename=None):
33         self.ip_address = ip_address
34         self.user = user
35         self.password = password
36         self.key_filename = key_filename
37         self.connected = False
38         self.shell = None
39
40         self.logger.setLevel(logging.INFO)
41
42         self.ssh = paramiko.SSHClient()
43         self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
44
45         self.util = Utilvnf()
46         with open(self.util.test_env_config_yaml) as file_fd:
47             test_env_config_yaml = yaml.safe_load(file_fd)
48         file_fd.close()
49
50         self.ssh_revieve_buff = test_env_config_yaml.get("general").get(
51             "ssh_receive_buffer")
52
53     def connect(self, time_out=DEFAULT_CONNECT_TIMEOUT,
54                 retrycount=DEFAULT_CONNECT_RETRY_COUNT):
55         # pylint: disable=missing-docstring
56         while retrycount > 0:
57             try:
58                 self.logger.info("SSH connect to %s.", self.ip_address)
59                 self.ssh.connect(self.ip_address,
60                                  username=self.user,
61                                  password=self.password,
62                                  key_filename=self.key_filename,
63                                  timeout=time_out,
64                                  look_for_keys=False,
65                                  allow_agent=False)
66
67                 self.logger.info("SSH connection established to %s.",
68                                  self.ip_address)
69
70                 self.shell = self.ssh.invoke_shell()
71
72                 while not self.shell.recv_ready():
73                     time.sleep(RECEIVE_ROOP_WAIT)
74
75                 self.shell.recv(self.ssh_revieve_buff)
76                 break
77             except Exception:  # pylint: disable=broad-except
78                 self.logger.info("SSH timeout for %s...", self.ip_address)
79                 time.sleep(time_out)
80                 retrycount -= 1
81
82         if retrycount == 0:
83             self.logger.warn(
84                 "Cannot establish connection to IP '%s'", self.ip_address)
85             self.connected = False
86             return self.connected
87
88         self.connected = True
89         return self.connected
90
91     def send(self, cmd, prompt, timeout=DEFAULT_SEND_TIMEOUT):
92         # pylint: disable=missing-docstring
93         if self.connected is True:
94             self.shell.settimeout(timeout)
95             self.logger.debug("Commandset : '%s'", cmd)
96
97             try:
98                 self.shell.send(cmd + '\n')
99             except Exception:  # pylint: disable=broad-except
100                 self.logger.error("ssh send timeout : Command : '%s'", cmd)
101                 return None
102
103             res_buff = ''
104             while not res_buff.endswith(prompt):
105                 time.sleep(RECEIVE_ROOP_WAIT)
106                 try:
107                     res = self.shell.recv(self.ssh_revieve_buff)
108                 except Exception:  # pylint: disable=broad-except
109                     self.logger.error("ssh receive timeout : Command : '%s'",
110                                       cmd)
111                     break
112
113                 res_buff += res.decode("utf-8")
114
115             self.logger.debug("Response : '%s'", res_buff)
116             return res_buff
117         self.logger.error("Cannot connected to IP '%s'.", self.ip_address)
118         return None
119
120     def close(self):
121         # pylint: disable=missing-docstring
122         if self.connected is True:
123             self.ssh.close()
124
125     @staticmethod
126     def error_check(response, err_strs=None):
127         # pylint: disable=missing-docstring
128         if err_strs is None:
129             err_strs = ["error", "warn", "unknown command", "already exist"]
130         for err in err_strs:
131             if err in response:
132                 return False
133
134         return True