您的位置:首页 > 运维架构 > Shell

JSch:纯JAVA实现远程执行SSH2主机的SHELL命令

2014-04-16 17:41 411 查看
上篇文章我编写了利用JSch实现SFTP的文件上传和下载/article/3501143.html,在本篇文章中,我将描述如何利用JSch实现执行远程SSH2主机的SHELL命令,不说了,直接上代码和详细的代码说明:

view
source

print?

01
/**
02
*
利用JSch包实现远程主机SHELL命令执行
03
*
@paramip主机IP
04
*
@paramuser主机登陆用户名
05
*
@parampsw主机登陆密码
06
*
@paramport主机ssh2登陆端口,如果取默认值,传-1
07
*
@paramprivateKey密钥文件路径
08
*
@parampassphrase密钥的密码
09
*/
10
public
static
void
sshShell(String
ip,Stringuser,Stringpsw
11
,
int
port
,StringprivateKey,Stringpassphrase)
throws
Exception{
12
Session
session=
null
;
13
Channel
channel=
null
;
14
15
16
JSch
jsch=
new
JSch();
17
18
//设置密钥和密码
19
if
(privateKey
!=
null
&&
!
""
.equals(privateKey))
{
20
if
(passphrase
!=
null
&&
""
.equals(passphrase))
{
21
//设置带口令的密钥
22
jsch.addIdentity(privateKey,
passphrase);
23
}
else
{
24
//设置不带口令的密钥
25
jsch.addIdentity(privateKey);
26
}
27
}
28
29
if
(port
<=
0
){
30
//连接服务器,采用默认端口
31
session
=jsch.getSession(user,ip);
32
}
else
{
33
//采用指定的端口连接服务器
34
session
=jsch.getSession(user,ip,port);
35
}
36
37
//如果服务器连接不上,则抛出异常
38
if
(session
==
null
)
{
39
throw
new
Exception(
"session
isnull"
);
40
}
41
42
//设置登陆主机的密码
43
session.setPassword(psw);
//设置密码
44
//设置第一次登陆的时候提示,可选值:(ask
|yes|no)
45
session.setConfig(
"StrictHostKeyChecking"
,
"no"
);
46
//设置登陆超时时间
47
session.connect(
30000
);
48
49
try
{
50
//创建sftp通信通道
51
channel
=(Channel)session.openChannel(
"shell"
);
52
channel.connect(
1000
);
53
54
//获取输入流和输出流
55
InputStream
instream=channel.getInputStream();
56
OutputStream
outstream=channel.getOutputStream();
57
58
//发送需要执行的SHELL命令,需要用\n结尾,表示回车
59
String
shellCommand=
"ls
\n"
;
60
outstream.write(shellCommand.getBytes());
61
outstream.flush();
62
63
64
//获取命令执行的结果
65
if
(instream.available()
>
0
)
{
66
byte
[]
data=
new
byte
[instream.available()];
67
int
nLen
=instream.read(data);
68
69
if
(nLen
<
0
)
{
70
throw
new
Exception(
"network
error."
);
71
}
72
73
//转换输出结果并打印出来
74
String
temp=
new
String(data,
0
,
nLen,
"iso8859-1"
);
75
System.out.println(temp);
76
}
77
outstream.close();
78
instream.close();
79
}
catch
(Exception
e){
80
e.printStackTrace();
81
}
finally
{
82
session.disconnect();
83
channel.disconnect();
84
}
85
}
利用JSch实现执行远程SSH2主机的SHELL命令,见我的博文:/article/3501144.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: