自动化测试shell交互代码示例
Java代码通过JSch库实现ssh连接以及shell命令交互
public class ShellUtil {
private static Session session = null;
private static JSch jsch = null;
private static Vector stdout = null;
private static ChannelShell channel = null;
private static PrintWriter printWriter = null;
private static BufferedReader input = null;
private static int port = 22;
private static int TIMEOUT = 3000;
//执行命令,实现shell交互
public static int execute(String command1, String command2,String command3) {
int returnCode = 0;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
InputStreamReader inputStreamReader = new InputStreamReader(channel.getInputStream());
input = new BufferedReader(inputStreamReader);
printWriter = new PrintWriter(channel.getOutputStream());
printWriter.println("shell");
printWriter.println(command1);
printWriter.println(command2);
printWriter.println(command3);
//通过exit 退出当前shell交互界面,防止阻塞
printWriter.println("exit");
printWriter.flush();
printWriter.println("exit");
printWriter.flush();
// log.info("The remote command is: ");
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
System.out.println(line);
}
input.close();
printWriter.close();
} catch (Exception e) {
e.printStackTrace();
return -1;
}finally {
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
public static void close(){
if (session != null) {
session.disconnect();
}
}
//创建连接
public static void connect(String name,String IP,String password) {
try {
JSch jsch = new JSch();
session = jsch.getSession(name, IP, port);
session.setPassword(password);
if (session == null) {
throw new Exception("session is null");
}
session.setConfig("StrictHostKeyChecking", "no");
session.connect(TIMEOUT);
} catch (Exception e) {
e.printStackTrace();
}
}
}