-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathDevice.java
More file actions
1698 lines (1568 loc) · 67.5 KB
/
Device.java
File metadata and controls
1698 lines (1568 loc) · 67.5 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2013 Juniper Networks, Inc.
All Rights Reserved
Use is subject to license terms.
*/
package net.juniper.netconf;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSubsystem;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import net.juniper.netconf.element.Datastore;
import net.juniper.netconf.element.Hello;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* A <code>Device</code> is used to define a Netconf server.
* <p>
* A new device is created using the Device.Builder.build()
* <p>
* Example:
* <pre>
* {@code}
* Device device = Device.builder().hostName("hostname")
* .userName("username")
* .password("password")
* .hostKeysFileName("hostKeysFileName")
* .build();
* </pre>
* <ol>
* <li>creates a {@link Device} object.</li>
* <li>perform netconf operations on the Device object.</li>
* <li>If needed, call the method createNetconfSession() to create another
* NetconfSession.</li>
* <li>Finally, one must close the Device and release resources with the
* {@link #close() close()} method.</li>
* </ol>
*/
public class Device implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(Device.class);
private static final int DEFAULT_NETCONF_PORT = 830;
private static final int DEFAULT_TIMEOUT = 5000;
private static final long SHELL_READ_POLL_INTERVAL_MILLIS = 10L;
private static final List<String> DEFAULT_CLIENT_CAPABILITIES = Arrays.asList(
NetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
NetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0 + "#candidate",
NetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0 + "#confirmed-commit",
NetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0 + "#validate",
NetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0 + "#url?protocol=http,ftp,file"
);
private final JSch sshClient;
private final String hostName;
private final int port;
private final int connectionTimeout;
private final int commandTimeout;
private final String userName;
private final String password;
private final boolean keyBasedAuthentication;
private final String pemKeyFile;
private final boolean strictHostKeyChecking;
private final String hostKeysFileName;
private final DocumentBuilder xmlBuilder;
private final List<String> netconfCapabilities;
private final List<String> advertisedNetconfCapabilities;
private final String helloRpc;
private ChannelSubsystem sshChannel;
private Session sshSession;
private NetconfSession netconfSession;
/**
* Returns a new {@link Builder} for constructing {@link Device} instances.
*
* @return fresh {@link Builder}
*/
public static Builder builder() {
return new Builder();
}
/**
* Fluent builder for {@link Device}. Configure desired fields and call
* {@link #build()} to obtain an immutable instance.
*/
public static final class Builder {
/**
* Creates an empty {@code Builder}.
*/
private Builder() {
}
private JSch sshClient = new JSch();
private String hostName;
private int port = DEFAULT_NETCONF_PORT;
private int timeout = DEFAULT_TIMEOUT;
private Integer connectionTimeout;
private Integer commandTimeout;
private String userName;
private String password;
private boolean keyAuth = false;
private String pemKeyFile;
private boolean strictHostKeyChecking = true;
private String hostKeysFileName;
private List<String> netconfCapabilities = DEFAULT_CLIENT_CAPABILITIES;
/**
* Replaces the default {@link JSch} instance with a caller‑supplied one.
* <p>
* Supplying your own {@code JSch} lets you pre‑configure global settings
* like proxies or identity repositories before a {@link Device} is built.
*
* @param sshClient pre‑configured {@link JSch} instance (must not be {@code null})
* @return this {@code Builder} for fluent chaining
* @throws NullPointerException if {@code sshClient} is {@code null}
*/
public Builder sshClient(JSch sshClient) {
this.sshClient = Objects.requireNonNull(sshClient);
return this;
}
/**
* Sets the DNS host name or IP address of the Netconf server.
*
* @param hostName server host name or IP
* @return this {@code Builder} for fluent chaining
*/
public Builder hostName(String hostName) {
this.hostName = hostName;
return this;
}
/**
* Specifies the TCP port on which the Netconf SSH subsystem listens.
* <p>
* Defaults to {@code 830} if not set.
*
* @param port TCP port number
* @return this {@code Builder} for fluent chaining
*/
public Builder port(int port) {
this.port = port;
return this;
}
/**
* Sets a default timeout (in milliseconds) that is used when a more
* specific {@link #connectionTimeout(int)} or {@link #commandTimeout(int)}
* value has not been provided.
*
* @param ms timeout in milliseconds
* @return this {@code Builder} for fluent chaining
*/
public Builder timeout(int ms) {
this.timeout = ms;
return this;
}
/**
* Overrides the default SSH connection timeout.
*
* @param ms timeout in milliseconds for establishing the SSH session
* @return this {@code Builder} for fluent chaining
*/
public Builder connectionTimeout(int ms) {
this.connectionTimeout = ms;
return this;
}
/**
* Sets the per‑command timeout that applies to individual NETCONF RPCs
* (distinct from the SSH connection timeout).
*
* @param ms timeout in milliseconds
* @return this {@code Builder} for fluent chaining
*/
public Builder commandTimeout(int ms) {
this.commandTimeout = ms;
return this;
}
/**
* Specifies the login user name for the SSH/NETCONF session.
*
* @param userName user name string
* @return this {@code Builder} for fluent chaining
*/
public Builder userName(String userName) {
this.userName = userName;
return this;
}
/**
* Sets the password used for password‑based SSH authentication.
* <p>
* Ignored if {@link #keyBasedAuth(String)} is used instead.
*
* @param password login password
* @return this {@code Builder} for fluent chaining
*/
public Builder password(String password) {
this.password = password;
return this;
}
/**
* Enables key‑based SSH authentication and sets the path to the PEM
* private‑key file.
*
* @param pem absolute or relative path to the PEM‑formatted private key
* @return this {@code Builder} for fluent chaining
*/
public Builder keyBasedAuth(String pem) {
this.keyAuth = true;
this.pemKeyFile = pem;
return this;
}
/**
* Specifies the path to the PEM‑formatted private key that will be used
* for key‑based SSH authentication.
* <p>
* Note: calling this method alone does <em>not</em> switch the builder
* to key‑authentication mode; be sure to also invoke
* {@link #keyBasedAuth(String)} or set {@link #keyAuth} explicitly.
*
* @param pemKeyFile absolute or relative path to the PEM key file
* @return this {@code Builder} for fluent chaining
*/
public Builder pemKeyFile(String pemKeyFile) {
this.pemKeyFile = pemKeyFile;
return this;
}
/**
* Disables strict host‑key checking so every host key is trusted
* (equivalent to {@code StrictHostKeyChecking=no} in OpenSSH).
* <p>
* <strong>Security note:</strong> Accepting all host keys makes the
* connection vulnerable to man‑in‑the‑middle attacks. Use this only in
* development or other low‑risk environments.
*
* @return this {@code Builder} for fluent chaining
*/
public Builder trustAllHostKeys() {
this.strictHostKeyChecking = false;
return this;
}
/**
* Enables or disables strict host‑key checking for the SSH session.
* <p>
* When set to {@code true} the underlying JSch session will verify the
* server's host key against the known‑hosts file and refuse the
* connection if it is unknown. When {@code false} the connection will
* proceed even if the server's host key is not listed.
*
* @param strictHostKeyChecking whether to enforce host‑key checking
* @return this {@code Builder} for fluent chaining
*/
public Builder strictHostKeyChecking(boolean strictHostKeyChecking) {
this.strictHostKeyChecking = strictHostKeyChecking;
return this;
}
/**
* Specifies the path to the SSH known‑hosts file used when
* {@link #strictHostKeyChecking(boolean)} is enabled.
*
* @param hostKeysFileName absolute or relative path to the known‑hosts file
* @return this {@code Builder} for fluent chaining
*/
public Builder hostKeysFileName(String hostKeysFileName) {
this.hostKeysFileName = hostKeysFileName;
return this;
}
/**
* Replaces the default list of client‑side Netconf capabilities that
* will be advertised in the initial {@code <hello>} message.
* <p>
* The supplied list is defensively copied and wrapped in an
* unmodifiable view, so subsequent modifications to the original list
* do not affect the builder.
*
* @param caps list of capability URIs; must not be {@code null}
* @return this {@code Builder} for fluent chaining
* @throws NullPointerException if {@code caps} is {@code null}
*/
public Builder netconfCapabilities(List<String> caps) {
this.netconfCapabilities = java.util.Collections.unmodifiableList(new java.util.ArrayList<>(caps));
return this;
}
/**
* Validates all required fields and constructs an immutable {@link Device}.
* <p>
* Mandatory parameters include host name, user credentials (or key), and
* host‑key settings when strict checking is enabled. If any of these are
* missing or inconsistent, a {@link NetconfException} is thrown.
*
* @return a fully‑configured {@link Device} instance
* @throws NetconfException if validation fails or if an internal error
* occurs while initialising auxiliary resources
*/
public Device build() throws NetconfException {
// Validation logic moved from Device constructor
if (hostName == null) throw new NetconfException("hostName is required");
if (userName == null) throw new NetconfException("userName is required");
if (!keyAuth && password == null)
throw new NetconfException("Password is required for password auth");
if (strictHostKeyChecking && hostKeysFileName == null)
throw new NetconfException("hostKeysFileName required when strictHostKeyChecking=true");
if (keyAuth && pemKeyFile == null)
throw new NetconfException("pemKeyFile required when keyAuth=true");
try {
return new Device(this);
} catch (NetconfException e) {
throw e;
}
}
}
/* ------------------------------------------------------------------
* Private constructor used by Builder
* ------------------------------------------------------------------ */
private Device(Builder b) throws NetconfException {
this.sshClient = b.sshClient;
this.hostName = b.hostName;
this.port = b.port;
this.connectionTimeout = b.connectionTimeout != null ? b.connectionTimeout : b.timeout;
this.commandTimeout = b.commandTimeout != null ? b.commandTimeout : b.timeout;
this.userName = b.userName;
this.password = b.password;
this.keyBasedAuthentication = b.keyAuth;
this.pemKeyFile = b.pemKeyFile;
this.strictHostKeyChecking = b.strictHostKeyChecking;
this.hostKeysFileName = b.hostKeysFileName;
this.netconfCapabilities = b.netconfCapabilities;
try {
this.xmlBuilder = createSecureDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new NetconfException("Cannot create XML Parser", e);
}
Hello hello = createHello(this.netconfCapabilities);
this.advertisedNetconfCapabilities = hello.getCapabilities();
this.helloRpc = createHelloRPC(hello);
}
/**
* Get the client capabilities that are advertised to the Netconf server by default.
* RFC 6241 describes the standard netconf capabilities.
* <a href="https://tools.ietf.org/html/rfc6241#section-8">...</a>
*
* @return List of default client capabilities.
*/
protected List<String> getDefaultClientCapabilities() {
return createHello(DEFAULT_CLIENT_CAPABILITIES).getCapabilities();
}
/**
* Given a list of netconf capabilities, generate the netconf hello rpc message.
* <a href="https://tools.ietf.org/html/rfc6241#section-8.1">...</a>
*
* @param capabilities A list of netconf capabilities
* @return the hello RPC that represents those capabilities.
*/
private Hello createHello(List<String> capabilities) {
return Hello.builder()
.capabilities(capabilities)
.build();
}
private String createHelloRPC(Hello hello) {
return hello.getXml() + NetconfConstants.DEVICE_PROMPT;
}
/**
* Create a new Netconf session.
*
* @return NetconfSession
* @throws NetconfException if there are issues communicating with the Netconf server.
*/
private NetconfSession createNetconfSession() throws NetconfException {
Session session = sshSession;
ChannelSubsystem channel = null;
boolean disconnectSessionOnFailure = false;
if (!isConnected()) {
try {
if (strictHostKeyChecking) {
if (hostKeysFileName == null) {
throw new NetconfException("Cannot do strictHostKeyChecking if hostKeysFileName is null");
}
sshClient.setKnownHosts(hostKeysFileName);
}
} catch (JSchException e) {
throw new NetconfException(String.format("Error loading known hosts file: %s", e.getMessage()), e);
}
sshClient.setHostKeyRepository(sshClient.getHostKeyRepository());
log.info("Connecting to host {} on port {}.", hostName, port);
if (keyBasedAuthentication) {
loadPrivateKey();
session = loginWithPrivateKey(connectionTimeout);
} else {
session = loginWithUserPass(connectionTimeout);
}
disconnectSessionOnFailure = true;
try {
session.setTimeout(connectionTimeout);
} catch (JSchException e) {
cleanupFailedSessionInitialization(channel, session, disconnectSessionOnFailure);
throw new NetconfException(String.format("Error setting session timeout: %s", e.getMessage()), e);
}
if (session.isConnected()) {
log.info("Connected to host {} - Timeout set to {} msecs.", hostName, session.getTimeout());
} else {
cleanupFailedSessionInitialization(channel, session, disconnectSessionOnFailure);
throw new NetconfException("Failed to connect to host. Unknown reason");
}
}
try {
channel = (ChannelSubsystem) session.openChannel("subsystem");
channel.setSubsystem("netconf");
NetconfSession establishedSession =
new NetconfSession(channel, connectionTimeout, commandTimeout,
advertisedNetconfCapabilities, helloRpc, xmlBuilder);
sshSession = session;
sshChannel = channel;
return establishedSession;
} catch (JSchException | IOException e) {
cleanupFailedSessionInitialization(channel, session, disconnectSessionOnFailure);
throw new NetconfException("Failed to create Netconf session:" +
e.getMessage(), e);
}
}
private void cleanupFailedSessionInitialization(ChannelSubsystem channel, Session session,
boolean disconnectSessionOnFailure) {
if (channel != null) {
channel.disconnect();
}
if (disconnectSessionOnFailure && session != null) {
session.disconnect();
}
}
private Session loginWithUserPass(int timeoutMilliSeconds) throws NetconfException {
try {
Session session = sshClient.getSession(userName, hostName, port);
session.setConfig("userauth", "password");
session.setConfig("StrictHostKeyChecking", isStrictHostKeyChecking() ? "yes" : "no");
session.setPassword(password);
session.connect(timeoutMilliSeconds);
return session;
} catch (JSchException e) {
throw new NetconfException(String.format("Error connecting to host: %s - Error: %s",
hostName, e.getMessage()), e);
}
}
private Session loginWithPrivateKey(int timeoutMilliSeconds) throws NetconfException {
try {
Session session = sshClient.getSession(userName, hostName, port);
session.setConfig("userauth", "publickey");
session.setConfig("StrictHostKeyChecking", isStrictHostKeyChecking() ? "yes" : "no");
session.connect(timeoutMilliSeconds);
return session;
} catch (JSchException e) {
throw new NetconfException(String.format("Error using key pair file: %s to connect to host: %s - Error: %s",
pemKeyFile, hostName, e.getMessage()), e);
}
}
/**
* Connect to the Device, and establish a default NETCONF session.
*
* @throws NetconfException if there are issues communicating with the Netconf server.
*/
public void connect() throws NetconfException {
if (hostName == null || userName == null || (password == null &&
pemKeyFile == null)) {
throw new NetconfException("Login parameters of Device can't be " +
"null.");
}
netconfSession = this.createNetconfSession();
}
private void loadPrivateKey() throws NetconfException {
try {
sshClient.addIdentity(pemKeyFile);
} catch (JSchException e) {
throw new NetconfException(String.format("Error parsing the pemKeyFile: %s", e.getMessage()), e);
}
}
private static DocumentBuilder createSecureDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setExpandEntityReferences(false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
return documentBuilderFactory.newDocumentBuilder();
}
/**
* Reboot the device.
*
* @return RPC reply sent by Netconf server.
* @throws java.io.IOException If there are issues communicating with the Netconf server.
*/
public String reboot() throws IOException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.reboot();
}
/**
* Indicates whether both the SSH {@link Session} and {@link ChannelSubsystem}
* are currently connected.
*
* @return {@code true} if the device is connected
*/
public boolean isConnected() {
return (isChannelConnected() && isSessionConnected());
}
private boolean isChannelConnected() {
if (sshChannel == null) {
return false;
}
return sshChannel.isConnected();
}
private boolean isSessionConnected() {
if (sshSession == null) {
return false;
}
return sshSession.isConnected();
}
/**
* Close the connection to the Netconf server. All associated Netconf
* sessions will be closed, too. Can be called at any time. Don't forget to
* call this once you don't need the device anymore.
*/
@Override
public void close() {
if (isChannelConnected()) {
sshChannel.disconnect();
}
if (isSessionConnected()) {
sshSession.disconnect();
}
}
/**
* Execute a command in shell mode.
*
* @param command The command to be executed in shell mode.
* @return Result of the command execution, as a String. Waiting for
* command output is bounded by {@link #getCommandTimeout()}.
* @throws IOException if there are issues communicating with the Netconf server.
*/
public String runShellCommand(String command) throws IOException {
if (!isConnected()) {
return "Could not find open connection.";
}
try (BufferedReader bufferReader = openExecChannelReader(command)) {
StringBuilder reply = new StringBuilder();
while (true) {
String line = bufferReader.readLine();
if (line == null || line.equals(NetconfConstants.EMPTY_LINE))
break;
reply.append(line).append(NetconfConstants.LF);
}
return reply.toString();
}
}
/**
* Execute a command in shell mode.
*
* @param command The command to be executed in shell mode.
* @return Result of the command execution, as a BufferedReader. This is
* useful if we want continuous stream of output, rather than wait
* for whole output till command execution completes. Closing the returned
* reader also disconnects the underlying SSH exec channel. Each blocking
* read waits at most {@link #getCommandTimeout()} for additional output.
* @throws IOException if there are issues communicating with the Netconf server.
*/
public BufferedReader runShellCommandRunning(String command)
throws IOException {
if (!isConnected()) {
throw new IOException("Could not find open connection");
}
return openExecChannelReader(command);
}
private BufferedReader openExecChannelReader(String command) throws IOException {
ChannelExec channel;
try {
channel = (ChannelExec) sshSession.openChannel("exec");
} catch (JSchException e) {
throw new NetconfException(String.format("Failed to open exec session: %s", e.getMessage()), e);
}
try {
channel.setCommand(command);
InputStream stdout = channel.getInputStream();
channel.connect(connectionTimeout);
return new BufferedReader(new InputStreamReader(
new TimeoutAwareChannelInputStream(stdout, channel, commandTimeout),
Charset.defaultCharset())) {
@Override
public void close() throws IOException {
try {
super.close();
} finally {
channel.disconnect();
}
}
};
} catch (JSchException e) {
channel.disconnect();
throw new NetconfException(String.format("Failed to start exec session: %s", e.getMessage()), e);
} catch (IOException e) {
channel.disconnect();
throw e;
}
}
private static final class TimeoutAwareChannelInputStream extends InputStream {
private final InputStream delegate;
private final ChannelExec channel;
private final int timeoutMillis;
private TimeoutAwareChannelInputStream(InputStream delegate, ChannelExec channel, int timeoutMillis) {
this.delegate = delegate;
this.channel = channel;
this.timeoutMillis = timeoutMillis;
}
@Override
public int read() throws IOException {
byte[] oneByte = new byte[1];
int bytesRead = read(oneByte, 0, 1);
if (bytesRead < 0) {
return -1;
}
return oneByte[0] & 0xFF;
}
@Override
public int read(byte[] buffer, int off, int len) throws IOException {
Objects.requireNonNull(buffer, "buffer");
if (off < 0 || len < 0 || len > buffer.length - off) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return 0;
}
if (timeoutMillis <= 0) {
return delegate.read(buffer, off, len);
}
long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
while (true) {
int available = delegate.available();
if (available > 0) {
int bytesRead = delegate.read(buffer, off, Math.min(len, available));
if (bytesRead != 0) {
return bytesRead;
}
} else if (channel.isClosed()) {
return delegate.read(buffer, off, len);
}
long remainingNanos = deadlineNanos - System.nanoTime();
if (remainingNanos <= 0) {
throw new SocketTimeoutException("Command timeout limit was exceeded: " + timeoutMillis);
}
sleepForAvailableData(remainingNanos);
}
}
@Override
public void close() throws IOException {
delegate.close();
}
@Override
public int available() throws IOException {
return delegate.available();
}
private void sleepForAvailableData(long remainingNanos) throws InterruptedIOException {
long sleepMillis = Math.min(SHELL_READ_POLL_INTERVAL_MILLIS,
Math.max(1L, TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
InterruptedIOException interrupted = new InterruptedIOException(
"Interrupted while waiting for shell command output.");
interrupted.initCause(e);
throw interrupted;
}
}
}
/**
* Send an RPC(as String object) over the default Netconf session and get the
* response as an XML object.
* <p>Convenience overload for raw‑string payloads.</p>
*
* @param rpcContent RPC content to be sent. For example, to send an rpc
* <rpc><get-chassis-inventory/></rpc>, the
* String to be passed can be
* "<get-chassis-inventory/>" OR
* "get-chassis-inventory" OR
* "<rpc><get-chassis-inventory/></rpc>"
* @return RPC reply sent by Netconf server
* @throws java.io.IOException If there are errors communicating with the netconf server.
* @throws org.xml.sax.SAXException If there are errors parsing the XML reply.
*/
public XML executeRPC(String rpcContent) throws SAXException, IOException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return netconfSession.executeRPC(rpcContent);
}
/**
* Send an RPC(as XML object) over the Netconf session and get the response
* as an XML object.
* <p>Use when the payload is already assembled as an {@link XML} helper object.</p>
*
* @param rpc RPC to be sent. Use the XMLBuilder to create RPC as an
* XML object.
* @return RPC reply sent by Netconf server
* @throws java.io.IOException If there are errors communicating with the netconf server.
* @throws org.xml.sax.SAXException If there are errors parsing the XML reply.
*/
public XML executeRPC(XML rpc) throws SAXException, IOException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.executeRPC(rpc);
}
/**
* Send an RPC(as Document object) over the Netconf session and get the
* response as an XML object.
* <p>Accepts a DOM {@link org.w3c.dom.Document} that represents the full
* <rpc> element.</p>
*
* @param rpcDoc RPC content to be sent, as a org.w3c.dom.Document object.
* @return RPC reply sent by Netconf server
* @throws java.io.IOException If there are errors communicating with the netconf server.
* @throws org.xml.sax.SAXException If there are errors parsing the XML reply.
*/
public XML executeRPC(Document rpcDoc) throws SAXException, IOException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.executeRPC(rpcDoc);
}
/**
* Sends an RPC (as a raw XML string) over the default Netconf session and
* returns a {@link BufferedReader} for streaming the reply.
*
* @param rpcContent XML payload to send (content of the <rpc> element)
* @return RPC reply as a {@link BufferedReader}
* @throws IOException if communication with the server fails
* @throws IllegalStateException if no Netconf connection exists
*/
public BufferedReader executeRPCRunning(String rpcContent) throws IOException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.executeRPCRunning(rpcContent);
}
/**
* Send an RPC(as XML object) over the Netconf session and get the response
* as a BufferedReader.
* <p>Streams the reply incrementally, suitable for large responses.</p>
*
* @param rpc RPC to be sent. Use the XMLBuilder to create RPC as an
* XML object.
* @return RPC reply sent by Netconf server as a BufferedReader. This is
* useful if we want continuous stream of output, rather than wait
* for whole output till command execution completes.
* @throws java.io.IOException if there are errors communicating with the Netconf server.
*/
public BufferedReader executeRPCRunning(XML rpc) throws IOException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.executeRPCRunning(rpc);
}
/**
* Sends an RPC (as a DOM {@link Document}) over the active NETCONF session
* and returns a {@link BufferedReader} for streaming the reply.
* <p>
* Use this variant when you need to consume the server response
* <em>incrementally</em> — for example, when the RPC produces a
* large dataset or when you want to start processing output before the
* device finishes sending the final <code>]]>]]></code> prompt.
* </p>
*
* @param rpcDoc the complete <rpc> element encoded as a DOM
* {@link Document}; must not be {@code null}
*
* @return a {@link BufferedReader} connected to the server’s reply stream
*
* @throws IOException if an I/O error occurs while sending the
* request or reading the reply
* @throws IllegalStateException if no NETCONF connection is established
*/
public BufferedReader executeRPCRunning(Document rpcDoc) throws IOException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.executeRPCRunning(rpcDoc);
}
/**
* Get the session ID of the Netconf session.
*
* @return Session ID
* @throws IllegalStateException if the connection is not established
*/
public String getSessionId() {
if (netconfSession == null) {
throw new IllegalStateException("Cannot get session ID, you need " +
"to establish a connection first.");
}
return this.netconfSession.getSessionId();
}
/**
* Returns the negotiated capability view for the active NETCONF session.
*
* @return immutable capability snapshot
* @throws IllegalStateException if the connection is not established
*/
public NegotiatedCapabilities getNegotiatedCapabilities() {
if (netconfSession == null) {
throw new IllegalStateException("Cannot get negotiated capabilities, you need "
+ "to establish a connection first.");
}
return this.netconfSession.getNegotiatedCapabilities();
}
/**
* Check if the last RPC reply returned from Netconf server has any error.
*
* @return true if any errors are found in last RPC reply.
* @throws SAXException if there are issues parsing XML from the device.
* @throws IOException if there are issues communicating with the device.
* @throws IllegalStateException if the connection is not established
*/
public boolean hasError() throws SAXException, IOException {
if (netconfSession == null) {
throw new IllegalStateException("No RPC executed yet, you need to" +
" establish a connection first.");
}
return this.netconfSession.hasError();
}
/**
* Check if the last RPC reply returned from Netconf server has any warning.
*
* @return true if any errors are found in last RPC reply.
* @throws SAXException if there are issues parsing XML from the device.
* @throws IOException if there are issues communicating with the device.
*/
public boolean hasWarning() throws SAXException, IOException {
if (netconfSession == null) {
throw new IllegalStateException("No RPC executed yet, you need to " +
"establish a connection first.");
}
return this.netconfSession.hasWarning();
}
/**
* Check if the last RPC reply returned from Netconf server, contains
* <ok/> tag.
*
* @return true if <ok/> tag is found in last RPC reply.
* @throws IllegalStateException if the connection is not established
*/
public boolean isOK() {
if (netconfSession == null) {
throw new IllegalStateException("No RPC executed yet, you need to " +
"establish a connection first.");
}
return this.netconfSession.isOK();
}
/**
* Locks the candidate configuration.
*
* @return true if successful.
* @throws java.io.IOException If there are errors communicating with the netconf server.
* @throws org.xml.sax.SAXException If there are errors parsing the XML reply.
* @throws IllegalStateException if the connection is not established
*/
public boolean lockConfig() throws IOException, SAXException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.lockConfig();
}
/**
* Unlocks the candidate configuration.
*
* @return true if successful.
* @throws java.io.IOException If there are errors communicating with the netconf server.
* @throws org.xml.sax.SAXException If there are errors parsing the XML reply.
*/
public boolean unlockConfig() throws IOException, SAXException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
return this.netconfSession.unlockConfig();
}
/**
* Loads the candidate configuration, Configuration should be in XML format.
*
* @param configuration Configuration,in XML format, to be loaded. For example,
* "<configuration><system><services><ftp/>
* <services/></system></configuration/>"
* will load 'ftp' under the 'systems services' hierarchy.
* @param loadType You can choose "merge" or "replace" as the loadType.
* @throws java.io.IOException If there are errors communicating with the netconf server.
* @throws org.xml.sax.SAXException If there are errors parsing the XML reply.
*/
public void loadXMLConfiguration(String configuration, String loadType)
throws IOException, SAXException {
if (netconfSession == null) {
throw new IllegalStateException("Cannot execute RPC, you need to " +
"establish a connection first.");
}
this.netconfSession.loadXMLConfiguration(configuration, loadType);
}
/**