Connector/Role.pm untested

filter: Statementstmt 0.0% 0 / 115 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 184 CC 17 SCAR 44.9
CC
17
Cov
0%
login
156.0
connect
42.0
send
2.0
CRAP 89.0
1 package PDK::Connector::Role;
2
3 use utf8;
4 use v5.30;
5 use Moose::Role;
6 use Carp;
7 use Expect;
8
9 # 设备连接属性定义
10 has host => (
11 is => 'ro', # 只读属性
12 required => 1, # 必需属性
13 );
14
15 # 用户名属性
16 has username => (
17 is => 'ro',
18 required => 0,
19 default => 'read', # 默认用户名
20 );
21
22 # 密码属性
23 has password => (
24 is => 'ro',
25 required => 0,
26 default => '', # 默认空密码
27 );
28
29 # 密码短语属性
30 has passphrase => (
31 is => 'ro',
32 required => 0,
33 default => '', # 默认空密码短语
34 );
35
36 # 特权模式密码属性
37 has enPassword => (
38 is => 'ro',
39 required => 0,
40 );
41
42 # 连接协议属性
43 has proto => (
44 is => 'ro',
45 required => 0,
46 default => 'ssh', # 默认使用SSH协议
47 );
48
49 # 登录成功提示符
50 has prompt => (
51 is => 'ro',
52 required => 0,
53 default => '^\s*\S+[>\]]\s*$', # 默认提示符
54 );
55
56 # 登录特权模式提示符
57 has enPrompt => (
58 is => 'ro',
59 required => 0,
60 );
61
62 # 会话超时时间
63 has timeout => (
64 is => 'ro',
65 required => 0,
66 default => 30, # 默认30秒
67 );
68
69 # 调试模式
70 has debug => (
71 is => 'ro',
72 required => 0,
73 default => 2, # 默认不打印日志
74 );
75
76 # 日志记录文件
77 has log_file => (
78 is => 'ro',
79 lazy => 1,
80 default => sub {
81 my $self = shift;
82
83 # 获取用户家目录(跨平台方式)
84 my $home = $ENV{PDK_LOG_DIR};
85 $home ||= $ENV{HOME} || $ENV{USERPROFILE} || (getpwuid($<))[7];
86
87 # 创建 logs 目录(如果不存在)
88 my $log_dir = "$home/logs";
89 mkdir $log_dir unless -d $log_dir;
90
91 # 构建日志文件路径,使用设备IP
92 my $host = $self->host;
93 return "$log_dir/$host.log";
94 },
95 );
96
97 # 登录状态标志(内部使用)
98 has _login_ => (
99 is => 'ro',
100 required => 0,
101 default => 0, # 默认未登录
102 );
103
104 # 特权模式状态标志(内部使用)
105 has _enable_ => (
106 is => 'ro',
107 required => 0,
108 default => 0, # 默认未进入特权模式
109 );
110
111 # 登录设备方法
112 sub login {
113 my $self = shift;
114 # 如果已登录,直接返回成功
115 return { success => $self->{_login_} } if $self->{_login_};
116
117 # 尝试连接设备
118 eval {
119 $self->connect() if not defined $self->{exp};
120 };
121
122 # 处理连接过程中可能出现的异常
123 if ($@) {
124 # 处理RSA密钥太小的问题
125 if ($@ =~ /RSA modulus too small/) {
126 eval {
127 $self->connect(' -1 '); # 使用SSHv1协议重试
128 };
129 if ($@) {
130 return { success => 0, reason => $@ };
131 }
132 }
133 # 处理不支持的加密算法问题
134 elsif ($@ =~ /Selected cipher type <unknown> not supported by server/i) {
135 eval {
136 $self->connect('-c des '); # 使用DES加密算法重试
137 };
138 if ($@) {
139 return { success => 0, reason => $@ };
140 }
141 }
142 # 处理连接被拒绝的情况(可能是SSH端口关闭)
143 elsif ($@ =~ /Connection refused/i) {
144 eval {
145 $self->{proto} = 'telnet'; # 切换到Telnet协议
146 $self->connect();
147 };
148 if ($@) {
149 return { success => 0, reason => $@ };
150 }
151 }
152 # 处理主机密钥变更的情况
153 elsif ($@ =~ /IDENTIFICATION CHANGED/i) {
154 # 清除已知主机中的旧密钥
155 system("/usr/bin/ssh-keygen -R $self->{host}");
156 eval {
157 $self->connect(); # 重试连接
158 };
159 if ($@) {
160 return { success => 0, reason => $@ };
161 }
162 }
163 # 处理其他未知错误
164 else {
165 return { success => 0, reason => $@ };
166 }
167 }
168
169 # 返回登录结果
170 return { success => $self->{_login_} };
171 }
172
173 # 建立设备连接的实际实现
174 sub connect {
175 my ($self, $args) = @_;
176 $args = $args // "";
177
178 my $host = $self->{host};
179 my $username = $self->{username};
180 my $password = $self->{password};
181 my $timeout = $self->{timeout};
182 my $debug = $self->{debug};
183 my $prompt = $self->{prompt};
184 my $exp = Expect->new;
185 my $login = 0;
186
187 $self->{exp} = $exp; # 保存Expect对象实例
188 $exp->raw_pty(1); # 启用原始PTY模式
189 $exp->restart_timeout_upon_receive(1); # 收到数据时重置超时
190 $exp->log_stdout($debug); # 不记录标准输出到STDOUT
191
192 # 构建连接命令
193 my $command = $self->{proto} . " $args" . " -l $username $host";
194 $exp->spawn($command) or die "[设备登录异常] 无法执行 $command: $!\n";
195
196 my $log_file = $self->log_file;
197 $exp->log_file($log_file) if $debug > 1; # 记录会话日志
198
199 # 处理连接过程中的各种提示
200 my @ret = $exp->expect($timeout,
201 # 处理SSH密钥确认提示
202 [ qr/Are you sure you want to continue/i => sub {
203 $exp->send("yes\n"); # 自动确认
204 exp_continue; # 继续等待其他提示
205 } ],
206 # 处理密码输入提示
207 [ qr/assword:\s*$/ => sub {
208 $exp->send("$password\n") if defined $password;
209 } ],
210 # 处理登录名提示
211 [ qr/login:\s*$/ => sub {
212 $exp->send("$username\n");
213 exp_continue;
214 } ],
215 # 处理用户名提示(不区分大小写)
216 [ qr/name:\s*$/i => sub {
217 $exp->send("$username\n");
218 exp_continue;
219 } ],
220 # 处理主机身份验证变更错误
221 [ qr/REMOTE HOST IDEN/ => sub {croak("[设备登录异常] IDENTIFICATION CHANGED!");} ],
222 # 成功登录,匹配命令提示符
223 [ qr/$prompt/m => sub {$login = 1;} ],
224 );
225
226 # 检查Expect操作是否出错
227 if (defined $ret[1]) {
228 croak("[设备登录异常]" . $ret[3] . $ret[1]);
229 }
230
231 # 再次检查,确保登录成功
232 @ret = $exp->expect($timeout,
233 [ qr/assword:\s*$/ => sub {croak("用户名或密码错误!");} ],
234 [ qr/$prompt/m => sub {$login = 1;} ],
235 );
236
237 # 检查第二次Expect操作是否出错
238 if (defined $ret[1]) {
239 croak("[设备登录异常]" . $ret[3] . $ret[1]);
240 }
241
242 # 检查是否已处于特权模式(提示符表示特权模式)
243 my $enPrompt = $self->{enPrompt} || $self->{prompt};
244 if ($exp->match() =~ /$enPrompt/) {
245 $self->{_enable_} = 1;
246 }
247
248 # 更新登录状态
249 $self->{_login_} = $login;
250 return 1;
251 }
252
253 # 发送命令到设备
254 sub send {
255 my ($self, $command) = @_;
256 my $exp = $self->{exp};
257 $exp->send($command);
258 }
259
260 # 等待设备响应,处理各种交互提示
261 requires 'waitfor';
262
263 # 执行多个命令
264 requires 'execCommands';
265
266 # 获取设备运行配置
267 requires 'getConfig';
268
269 1;
270
271 # 模块文档
272 =encoding utf8
273 =head1 NAME
274
275 PDK::Connector::Role - 设备连接器通用角色
276
277 =head1 SYNOPSIS
278
279 with 'PDK::Connector::Role';
280
281 # 在连接器类中使用该角色
282 has '+host' => (default => '192.168.1.1');
283 has '+username' => (default => 'admin');
284
285 =head1 DESCRIPTION
286
287 设备连接器的通用 Moose 角色,定义了网络设备连接的基本属性和方法。
288 所有具体的设备连接器类都应该使用这个角色,以确保统一的接口和行为。
289
290 =head1 ATTRIBUTES
291
292 =head2 host
293
294 设备主机名或IP地址,必需属性。
295
296 =head2 username
297
298 登录用户名,默认为 'read'。
299
300 =head2 password
301
302 登录密码,默认为空。
303
304 =head2 passphrase
305
306 密码短语,用于某些需要额外认证的设备。
307
308 =head2 enPassword
309
310 特权模式密码,用于进入特权模式。
311
312 =head2 proto
313
314 连接协议,默认为 'ssh',支持 ssh 和 telnet。
315
316 =head2 prompt
317
318 登录成功提示符的正则表达式模式。
319
320 =head2 enPrompt
321
322 特权模式提示符的正则表达式模式。
323
324 =head2 timeout
325
326 会话超时时间(秒),默认为30秒。
327
328 =head2 debug
329
330 调试模式级别,默认为2(不打印日志)。
331
332 =head2 log_file
333
334 日志文件路径,自动生成在用户目录的 logs 子目录下。
335
336 =head2 _login_
337
338 内部使用的登录状态标志。
339
340 =head2 _enable_
341
342 内部使用的特权模式状态标志。
343
344 =head1 METHODS
345
346 =head2 login
347
348 my $result = $conn->login;
349
350 登录设备方法。自动处理各种连接异常:
351 - RSA密钥太小问题
352 - 不支持的加密算法
353 - 连接被拒绝(自动切换协议)
354 - 主机密钥变更
355
356 返回包含登录结果的结构化数据。
357
358 =head2 connect
359
360 $conn->connect($args);
361
362 建立设备连接的实际实现。处理SSH密钥确认、密码输入、用户名提示等交互过程。
363
364 =head2 send
365
366 $conn->send($command);
367
368 发送命令到设备。
369
370 =head2 waitfor
371
372 my $output = $conn->waitfor($prompt);
373
374 等待设备响应,需要由具体连接器类实现。
375
376 =head2 execCommands
377
378 my $result = $conn->execCommands(\@commands);
379
380 执行多个命令序列,需要由具体连接器类实现。
381
382 =head2 getConfig
383
384 my $config = $conn->getConfig;
385
386 获取设备配置,需要由具体连接器类实现。
387
388 =head1 SEE ALSO
389
390 L<Moose::Role>, L<Expect>
391
392 =head1 AUTHOR
393
394 WENWU YAN E<lt>968828@gmail.comE<gt>
395
396 =head1 LICENSE AND COPYRIGHT
397
398 版权所有 2025 WENWU YAN。
399
400 本软件按Perl自身许可条款发布。
401
402 =cut