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); } } } }