SSHExec.java
1.96 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
package org.emercit.sshexec;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.log4j.Logger;
public class SSHExec {
private static final Logger log = Logger.getLogger(SSHExec.class);
Properties config = new Properties();
private String login;
private String password;
private String host;
private int port;
private String cmd;
public SSHExec() {
config.put("StrictHostKeyChecking", "no");
}
public void setLogin(String value) {
this.login=value;
}
public void setPassword(String value) {
this.password=value;
}
public void setHost(String value) {
this.host=value;
}
public void setPort(int value){
this.port=value;
}
public void setCmd(String value) {
this.cmd=value;
}
public void Exec() throws Exception {
JSch jsch = new JSch();
Session session=jsch.getSession(this.login, this.host, this.port);
session.setPassword(password);
session.setConfig(config);
session.connect();
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand("sudo -S -p '' "+cmd);
InputStream in=channel.getInputStream();
OutputStream out=channel.getOutputStream();
((ChannelExec)channel).setErrStream(System.err);
channel.connect();
out.write((password+"\n").getBytes());
out.flush();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
}