1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
| import re
import time
from paramiko import SSHClient, AutoAddPolicy
from func_timeout import func_set_timeout, exceptions
class RemoteCMD():
"""执行远程命令
"""
def _init_connection(self,
ip: str,
port: int,
user: str,
passwd: str,
timeout: int = 5):
"""初始化连接(这里单独抽出可以避免 func 超时未关闭 session)
Args:
ip (str): IP 地址
port (int): SSH 端口
user (str): 用户名
passwd (str): 密码
timeout (int, optional): 超时时长(秒). Defaults to 5.
Returns:
paramiko object: paramiko 客户端对象
"""
client = SSHClient()
# client.load_system_host_keys()
client.set_missing_host_key_policy(AutoAddPolicy())
client.connect(hostname=ip,
port=int(port),
username=user,
password=passwd,
timeout=timeout,
allow_agent=False,
look_for_keys=False)
client = client.invoke_shell()
return client
def _match_prompt(self, content: str, regex: str):
"""结束提示符匹配
Args:
content (str): 需要匹配的字符串
regex (str): 需要匹配的关键词或正则表达式
Returns:
bool: True/False
"""
if re.search(regex, content):
return True
return False
@func_set_timeout(5)
def _send_cmd(self,
client: object,
cmd: str,
recv_end_prompt: str,
recv_size: int = 512):
"""发送命令、拉取结果
Args:
client (object): paramiko 客户端对象
cmd (str): 要执行的命令
recv_size (int, optional): 单次拉取结果数据的大小. Defaults to 512.
Returns:
string: 执行结果
"""
client.send(f"{str(cmd).strip()}\n")
# 等待就绪
while not client.recv_ready():
time.sleep(0.2)
result = ""
while not self._match_prompt(result, recv_end_prompt):
result += client.recv(recv_size).decode()
return result
def command(self,
ip: str,
port: int,
user: str,
passwd: str,
cmd: str,
end_prompt: str=r"#\s$",
timeout: int = 5):
"""执行远程命令
Args:
ip (str): IP 地址
port (int): SSH 端口
user (port): 用户名
passwd (str): 密码
cmd (str): 要执行的命令
timeout (int, optional): 超时时长(秒). Defaults to 5.
Returns:
tuple: (True/False, 执行结果或报错)
"""
client = None
try:
client = self._init_connection(ip, port, user, passwd, timeout)
except Exception as err: # pylint: disable=broad-except
return False, f"SSH 连接出现异常:{err}"
try:
return True, self._send_cmd(client, cmd, end_prompt)
except exceptions.FunctionTimedOut:
return False, "SSH 执行出现超时错误!"
except Exception as err: # pylint: disable=broad-except
return False, f"SSH 执行出现其他异常:{err}"
finally:
if client:
client.close()
|