java代码端连接远程服务器

添加远程连接服务器依赖。

		<!--  远程连接服务器-->
		<dependency>
			<groupId>ch.ethz.ganymed</groupId>
			<artifactId>ganymed-ssh2</artifactId>
			<version>build210</version>
		</dependency>

部署服务器上使用直接连接使用,单条命令执行,返回执行后的结果

    /**(部署服务器上使用)
     * 单条命令执行,返回执行后的结果
     * command可拼接多条命令
     * @param command 输入的命令
     * @return 执行结果
     */
    public static String executeOneCommand(String command) {
        //String finalCommand = command;
        String[] finalCommand = new String[]{"/bin/sh","-c",command};
        StringBuilder stringBuilder = new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(finalCommand);
            process.waitFor();
            //读取屏幕输出
            BufferedReader strCon = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = strCon.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            System.out.println("stringBuilder===>"+stringBuilder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

本地代码端连接服务器使用。

  /**
     * 获得连接(本地连接服务器直接使用)
     * @param ip
     * @param userName
     * @param pwd
     * @param port
     * @return
     */
    public static Connection getConn(String ip, String userName, String pwd, int port){
        Connection conn = new Connection(ip,port);
        boolean blag = false;
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(userName, pwd);
            //session = conn.openSession();
            //client = new SCPClient(conn);
            if (isAuthenticated) {
                blag = true;
            }
            if (isAuthenticated == false) {
                throw new IOException("Authentication failed.文件scp到数据服务器时发生异常");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (blag) {
            return conn;
        }else {
            return null;
        }
    }

    public static String parseResult(InputStream inputStream) throws IOException{
        //读取输出流内容
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,DEFAULT_CHARSET));
        StringBuffer resultSB = new StringBuffer();
        String line;
        while((line = br.readLine()) != null){
            resultSB.append(line + "\n");
        }
        //替换换行符
        //String result = resultSB.toString().replaceAll("[\\t\\n\\r]", "");
        return resultSB.toString();
    }

    /**
     * 执行命令(本地连接服务器直接使用,测试使用)
     * @param command 命令语句
     * @return 执行结果
     */
    public static String execCommand(String command){
        String dataServerIp = "192.168.12.xxx";//服务器IP
        String dataServerUsername = "root";//服务器用户名
        String dataServerPassword = "xxxxx";//服务器登录密码
        Integer port = 22;//端口号
        Connection connection = getConn(dataServerIp, dataServerUsername, dataServerPassword, port);
        Session session = null;
        String result = "";
        try{
            session = connection.openSession();
            //执行命令
            session.execCommand(command);
            //解析结果
            result = parseResult(session.getStdout());
            //解析结果为空,则表示执行命令发生了错误,尝试解析错误处输出
            if (result == null || result.length() == 0){
                result = parseResult(session.getStderr());
                System.out.println("result===>"+result);
            }else {
                System.out.println("result===>"+result);
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值