1,通过ssh协议用scp命令拷贝
1.1 windows安装freeSSHD(使用密码登录)见博文https://blog.csdn.net/u014296316/article/details/88616023
1.2 安装git
配置windows免密登录到linux,这样从linux上scp文件时就不用输入密码了:
git 生成密钥对,gitbash命令行输入命令ssh-keygen
将生成的公钥id_rsa.pub拷贝到linux服务器上
将windows拷贝来的文件追加至authorized_keys文件中,cat /windows公钥拷贝文件所在目录/id_rsa.pub >> authorized_keys

SSHUtil工具类,用于建立远程ssh连接并执行命令

public class SSHUtil {    private static Logger logger = LoggerFactory.getLogger(SSHUtil.class);    private static int timeout = 20 * 1000; // 超时时间改成20s , 有的服务器10s 连接不上 ...    public static Session getJSchSession(String username, String host, String password, Integer port) throws JSchException {        JSch jsch = new JSch();        Session session = jsch.getSession(username, host, port);        session.setPassword(password);        session.setConfig("StrictHostKeyChecking", "no");//第一次访问服务器不用输入yes        session.setTimeout(timeout);        session.connect();        return session;    }    public static String execCommandByJSch(Session session, String command, String  resultEncoding) throws IOException,JSchException {        logger.info("执行命令:" + command);        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");        channelExec.setCommand(command);        channelExec.connect();        InputStream in = channelExec.getInputStream();        InputStream err = channelExec.getErrStream();        String result = IOUtils.toString(in, resultEncoding);        String error = IOUtils.toString(err, resultEncoding);        logger.info("返回结果:" + result);        logger.info("错误结果:" + error);        channelExec.disconnect();        return result + error;    }    //上传文件    public static void uploadFile(Session session, String directory, String uploadFile) throws Exception{        Channel channel = session.openChannel("sftp");        channel.connect();        ChannelSftp sftp = (ChannelSftp) channel;        upload(directory,uploadFile,sftp);        channel.disconnect();    }    //上传文件    public static void deleteFile(Session session, String directory) throws Exception{        Channel channel = session.openChannel("sftp");        channel.connect();        ChannelSftp sftp = (ChannelSftp) channel;        delete(directory,sftp);        channel.disconnect();    }    public static void delete(String directory,ChannelSftp sftp) throws SftpException {        directory=directory.replace('\\','/');        if (!directory.endsWith("/")){            directory+="/";        }        Vector<?> content= sftp.ls(directory);        for (Iterator<?> it = content.iterator(); it.hasNext();) {            ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();            if (entry.getFilename().equals(".")){                continue;            }            if (entry.getFilename().equals("..")){                continue;            }            SftpATTRS sftpATTRS= sftp.lstat(directory+entry.getFilename());            if (sftpATTRS.isDir()){                delete(directory+entry.getFilename(),sftp);            }else{                sftp.rm(directory+entry.getFilename());            }        }        sftp.rmdir(directory);    }    //上传文件    public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{        File file = new File(uploadFile);        if(file.exists()){            try {                Vector content = sftp.ls(directory);                if(content == null){                    sftp.mkdir(directory);                }            } catch (SftpException e) {                logger.info("出现异常!!");                logger.error(e.getMessage(),e);                sftp.mkdir(directory);            }            //进入目标路径            sftp.cd(directory);            if(file.isFile()){                InputStream ins = null;                try {                    ins = new FileInputStream(file);                    //中文名称的                    sftp.put(ins, new String(file.getName().getBytes(),"UTF-8"));                } catch (Exception e) {                    logger.error(e.getMessage() , e);                } finally {                    if (ins != null) {                        ins.close();                    }                }                //sftp.setFilenameEncoding("UTF-8");            }else{                File[] files = file.listFiles();                for (File file2 : files) {                    String uploadFilePath2 = file2.getAbsolutePath();                    String directory2 = directory + "";                    if(file2.isDirectory()){                        String str = uploadFilePath2.substring(uploadFilePath2.lastIndexOf(file2.separator));                        if(file2.separator.equals("\\")){                            str = str.replaceAll("\\\\","/");                        }                        directory2 += str;                    }                    upload(directory2,uploadFilePath2,sftp);                }            }        }    }}

 private void uploadWindowsAgent () throws Exception{//workspace 为windows上的路径        String workspace = server.getWorkspace();        String directory = workspace + "/atp-agent";        directory=directory.replace('/','\\');        logger.info("删除旧版本的agent开始...");        String deleteFileCommand = "cmd /c call rd \\s \\q "+ directory;        SSHUtil.execCommandByJSch(session,deleteFileCommand,"gbk");        logger.info("删除旧版本的agent完成...");        String mkdirCommand = "cmd /c call mkdir "+ directory;        logger.info("-> " + mkdirCommand);        SSHUtil.execCommandByJSch(session,mkdirCommand,"gbk");//        SSHUtil.deleteFile(session,directory);        logger.info("上传最新的agent到服务器...");        String uploadFileCommand = "cmd /c call scp -r root@"+ip+":"+targetPath+" "+ workspace;        SSHUtil.execCommandByJSch(session,uploadFileCommand,"gbk");//        SSHUtil.uploadFile(session, directory, targetPath);        logger.info("上传agent完成");        FileUtil.deleteDir(targetPath);    }

Windows批处理call和start的区别 参考博文 https://blog.csdn.net/sinat_34439107/article/details/79023866

2,通过http协议下载
客户端发送请求

//客户端代码downloadUtil.download(appConfig.getTestPlatformUrl()+"/api/download",workspace,"atp-agent.zip");public void download(final String requestUrl, final String destFileDir, final String destFileName) throws Exception{        FileOutputStream out = null;        InputStream in = null;        try{            URL url = new URL(requestUrl);            URLConnection urlConnection = url.openConnection();            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;            // true -- will setting parameters            httpURLConnection.setDoOutput(true);            // true--will allow read in from            httpURLConnection.setDoInput(true);            // will not use caches            httpURLConnection.setUseCaches(false);            // setting serialized            httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");            // default is GET            httpURLConnection.setRequestMethod("POST");            httpURLConnection.setRequestProperty("connection", "Keep-Alive");            httpURLConnection.setRequestProperty("Charsert", "UTF-8");            // 1 min            httpURLConnection.setConnectTimeout(60000);            // 1 min            httpURLConnection.setReadTimeout(60000);            // connect to server (tcp)            httpURLConnection.connect();            in = httpURLConnection.getInputStream();// send request to            // server            File dir  = new File(destFileDir);            if(!dir.exists()){                dir.mkdirs();            }            File file = new File(destFileDir, destFileName);            out = new FileOutputStream(file);            byte[] buffer = new byte[4096];            int readLength;            while ((readLength=in.read(buffer)) > 0) {//                byte[] bytes = new byte[readLength];//                System.arraycopy(buffer, 0, bytes, 0, readLength);                out.write(buffer,0,readLength);            }            out.flush();        }finally{            try {                if(in != null){                    in.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(out != null){                    out.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }//服务端代码@RequestMapping(value = "/api/download",method = RequestMethod.POST)    public void processDownload(HttpServletRequest request, HttpServletResponse response){        int bufferSize = 4096;        InputStream in = null;        OutputStream out = null;        try{            request.setCharacterEncoding("utf-8");            response.setCharacterEncoding("utf-8");            response.setContentType("application/octet-stream");            String agentPath= appConfig.getAgentPath();            File file = new File(agentPath+".zip");            response.setContentLength((int) file.length());            response.setHeader("Accept-Ranges", "bytes");            int readLength;            in = new BufferedInputStream(new FileInputStream(file), bufferSize);            out = new BufferedOutputStream(response.getOutputStream());            byte[] buffer = new byte[bufferSize];            while ((readLength=in.read(buffer)) > 0) {//                byte[] bytes = new byte[readLength];//                System.arraycopy(buffer, 0, bytes, 0, readLength);                out.write(buffer,0,readLength);            }            out.flush();        }catch(Exception e){            logger.error(e.getMessage(),e);        }finally {            if (in != null) {                try {                    in.close();                } catch (IOException e) {                    logger.error(e.getMessage(),e);                }            }            if (out != null) {                try {                    out.close();                } catch (IOException e) {                    logger.error(e.getMessage(),e);                }            }        }    }

 

©著作权归作者所有:来自51CTO博客作者遗梦江湖的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. Linux下通过受限bash创建指定权限的账号
  2. java解压压缩包工具类
  3. python异常处理
  4. DenyHosts阻止SSH暴力***
  5. 执行git push出现
  6. 复制远程服务器文件命令scp的使用
  7. 关于word导出功能的一些技巧步骤提高效率很实用!!!
  8. 如何在 指定文件夹 快速打开 jupyter notebook
  9. 【MOS】如何利用RMAN可传输表空间迁移数据库到不同字节序的平台(

随机推荐

  1. 使用delphi 开发多层应用(十三)使用Basic4a
  2. (转载)Android下Affinities和Task
  3. Android中称为四大组件
  4. activity 生命周期
  5. 开源阅读器FBReader Android版本的编译
  6. android瀑布流
  7. android bionic缺失pthread_cancel的解决
  8. Android四大组件之Activity---生命周期那
  9. Android(安卓)3D旋转动画之Camera 和 Mat
  10. Android中的动画有哪几类?各自的特点和区