自动化测试总结

自动化测试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();
          }

       }


}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值