项目中遇到,记录一下。
依赖
<dependency
>
<groupId
>com
.jcraft
</groupId
>
<artifactId
>jsch
</artifactId
>
<version
>0.1.53</version
>
</dependency
>
代码
package com
.sptit
.isv
.utils
;
import com
.jcraft
.jsch
.ChannelShell
;
import com
.jcraft
.jsch
.JSch
;
import com
.jcraft
.jsch
.JSchException
;
import com
.jcraft
.jsch
.Session
;
import java
.io
.*;
import java
.util
.ArrayList
;
import java
.util
.List
;
public class SSHClient {
public static String
execCommandByShell(Session session
, String shell
, String endShell
) {
String result
= "";
ChannelShell channelShell
;
try {
channelShell
= (ChannelShell
) session
.openChannel("shell");
InputStream inputStream
= channelShell
.getInputStream();
channelShell
.setPty(true);
channelShell
.connect();
OutputStream outputStream
= channelShell
.getOutputStream();
PrintWriter printWriter
= new PrintWriter(outputStream
);
Thread
.sleep(1000);
printWriter
.println(shell
);
printWriter
.println(endShell
);
printWriter
.flush();
result
= getTemplateContent(inputStream
);
outputStream
.close();
inputStream
.close();
channelShell
.disconnect();
session
.disconnect();
} catch (JSchException js
) {
js
.printStackTrace();
} catch (IOException io
) {
io
.printStackTrace();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
return result
;
}
public static String
getTemplateContent(InputStream inputStream
) {
StringBuffer str
= new StringBuffer("");
InputStreamReader isr
= new InputStreamReader(inputStream
);
BufferedReader
in = new BufferedReader(isr
);
String line
= null;
try {
while ((line
= in.readLine()) != null) {
str
.append(line
+ "\r\n");
}
in.close();
} catch (IOException io
) {
io
.printStackTrace();
}
return str
.toString();
}
public static Session
getSession(String userName
, String password
, String
IP) {
JSch jsch
= new JSch();
Session session
= null;
try {
session
= jsch
.getSession(userName
, IP, 22);
session
.setPassword(password
);
session
.setConfig("StrictHostKeyChecking", "no");
session
.connect();
} catch (JSchException js
) {
js
.printStackTrace();
}
return session
;
}
}
分页问题
如果返回结果是:
---- More
---- 结尾,说明还有数据需要翻页查看,但是这部分代码不能模拟空格翻页的操作,
可以修改一下交换机的全局设置,设置成不分页。
(华为交换机为例):
<Huawei
> system
-view
[Huawei
] user
-interface vty 0 4
[user
-interface vty 0 4] screen
-length
0
[user
-interface vty 0 4] quit