forked from karatelabs/karate-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSshSession.java
60 lines (53 loc) · 1.8 KB
/
SshSession.java
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
package karate;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class SshSession {
private final Channel channel;
private final Session session;
private final PrintStream terminal;
public SshSession(Map<String, Object> map) {
try {
String user = (String) map.get("user");
String host = (String) map.get("host");
String privateKey = (String) map.get("privateKey");
Integer port = (Integer) map.get("port");
if (port == null) {
port = 22;
}
JSch jsch = new JSch();
jsch.addIdentity(privateKey);
session = jsch.getSession(user, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("shell");
OutputStream channelInput = channel.getOutputStream();
terminal = new PrintStream(channelInput, true);
channel.setOutputStream(System.out, true);
((ChannelShell) channel).setPty(true);
channel.connect();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void input(String line) {
terminal.println(line);
}
public void close() {
try {
do {
TimeUnit.SECONDS.sleep(1);
} while (!channel.isEOF());
session.disconnect();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}