0%

Java 使用 JSch 远程执行 Shell 命令

最近需要使用远程执行 Shell 命令,网上也有很多教程,但一般都是远程分发文件或者需要实现 UserInfo 接口,感觉都不够简介或者不满足我的需求。经过上网查询、翻阅官网终于发现可以实现我想要的功能了。

参考:http://wiki.jsch.org/index.php?Manual%2FExamples%2FJschExecExample

添加Maven依赖

1
2
3
4
5
<dependency>
<groupId>com.jcraft</groupId>
>artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>

代码

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
package quartz;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.InputStream;

/**
* Created by chenxl on 2017/5/26.
*/
public class Samplejsch {

public static void main(String[] args) {

try{
JSch jsch=new JSch();

String host=System.getProperty("user.name") + "@localhost";
if(args.length>0){
host=args[0];
}
String user=host.substring(0, host.indexOf('@'));

host=host.substring(host.indexOf('@')+1);

user = "chenxl";
host = "localhost";
Session session=jsch.getSession(user, host, 22);

//jsch.setKnownHosts("/home/anand/.ssh/known_hosts");
//jsch.addIdentity("/home/anand/.ssh/id_rsa");

// If two machines have SSH passwordless logins setup, the following line is not needed:
session.setPassword("12345678");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();

String command="ps -a\n";
// command=args[1];

Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);

//channel.setInputStream(System.in);
channel.setInputStream(null);

((ChannelExec)channel).setErrStream(System.err);

InputStream in=channel.getInputStream();

channel.connect();
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()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee) {ee.printStackTrace();}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
} //end main

}

结果

如果觉得我的文章对您有用,请查看广告(Google Ads)或扫码。您的支持将鼓励我继续创作!