首页

通过jsch连接Linux服务器创建目录并授权代码示例

标签:jsch     发布时间:2023-10-30   

一、前言

通过jsch依赖包连接Linux服务器,java使用com.jcraft.jsch.ChannelExec代码提交"mkdir"创建目录,并 channel.chmod进行目录授权,具体参考下面代码示例。

二、代码示例

 import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.InputStream;@b@import java.util.Properties;@b@import java.util.Vector;@b@@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@@b@import com.iss.pms.util.PropertieFileReader;@b@import com.jcraft.jsch.Channel;@b@import com.jcraft.jsch.ChannelExec;@b@import com.jcraft.jsch.ChannelSftp;@b@import com.jcraft.jsch.JSch;@b@import com.jcraft.jsch.Session;@b@import com.jcraft.jsch.SftpException;@b@  @b@public class SftpClient{ @b@	@b@	private static Log log = LogFactory.getLog(SftpClient.class);@b@	@b@	//off-关闭;on-打开@b@	private  static  String  sftp_mode="off";@b@	@b@	private  static  String sftp_host="127.0.0.1";@b@	@b@	private  static  Integer  sftp_port=22;@b@	@b@	private  static  String  sftp_loginuser="root";@b@	@b@	private  static  String  sftp_loginpassword="123456";@b@	 @b@	@b@	static{@b@		 sftp_mode=PropertieFileReader.getString("sftp_mode");@b@		 sftp_host=PropertieFileReader.getString("sftp_host");@b@		 sftp_port=Integer.parseInt(PropertieFileReader.getString("sftp_port"));@b@		 sftp_loginuser=PropertieFileReader.getString("sftp_loginuser");@b@		 sftp_loginpassword=PropertieFileReader.getString("sftp_loginpassword"); @b@	}@b@	@b@	/**@b@	 * 判断sftp开关是否打开@b@	 * @return@b@	 */@b@	public  static  boolean isOk(){@b@		if("off".equalsIgnoreCase(sftp_mode)){@b@			return false;@b@		}else{@b@			return true;@b@		}@b@	}@b@	@b@	/**@b@	 * 上传指定文件到服务器目录@b@	 * @param directory 服务器目录 如"/home/tmp/", @b@	 * @param uploadFile 本地文件"C:\\logs\\dps-engine_error.log"@b@	 */@b@	public  static  void  upload(String directory, String uploadFile){@b@		@b@		ChannelSftp  login_channel=connect(sftp_host,sftp_port,sftp_loginuser,sftp_loginpassword);@b@		try {@b@			upload("/home/xwood/www"+directory,uploadFile,login_channel);@b@		} catch (Exception e) {@b@			e.printStackTrace();@b@			System.out.println("upload cause error:"+e.getMessage());@b@		}@b@	}@b@	@b@    /** @b@     * 链接sftp @b@     * @param host  主机 @b@     * @param port    端口 @b@     * @param username   用户名 @b@     * @param password  密码 @b@     * @return @b@     */  @b@    public  static ChannelSftp connect(String host, int port, String username,String password) {  @b@    	@b@        ChannelSftp sftp = null;  @b@        try {  @b@            JSch jsch = new JSch();  @b@            jsch.getSession(username, host, port);  @b@            Session sshSession = jsch.getSession(username, host, port);   @b@            System.out.println("Session创建成功");  @b@            sshSession.setPassword(password); @b@            System.out.println("密码输入成功");@b@            Properties sshConfig = new Properties();  @b@            sshConfig.put("StrictHostKeyChecking", "no");@b@            System.out.println("链接参数设置成功");@b@            sshSession.setConfig(sshConfig);  @b@            sshSession.connect();  @b@            System.out.println("Session已连接");  @b@            Channel channel = sshSession.openChannel("sftp");  @b@            channel.connect();  @b@            sftp = (ChannelSftp) channel;  @b@            System.out.println("连接到主机" + host + ".");  @b@        } catch (Exception e) {  @b@            e.printStackTrace();  @b@            return null;@b@        }  @b@        return sftp;  @b@    }  @b@  @b@    /** @b@     * 文件重命名 @b@     * @param directory 目录 @b@     * @param oldname 旧文件名   @b@     * @param newname 新文件名 @b@     * @param sftp @b@     */  @b@    public  static  void renameFile(String directory, String oldname, String newname,  @b@            ChannelSftp sftp) {  @b@        try {  @b@            try {@b@				sftp.cd(directory);@b@			} catch (Exception e) {@b@				sftp.mkdir(directory);@b@        		sftp.cd(directory);@b@			}  @b@            sftp.rename(oldname, newname);  @b@        } catch (Exception e) {  @b@            e.printStackTrace();  @b@        }  @b@        @b@    }  @b@  @b@    /** @b@     * 文件上传 @b@     * @param directory 目录 @b@     * @param uploadFile 要上传的文件名 @b@     * @param sftp @b@     */  @b@    public  static  void upload(String directory, String uploadFile, ChannelSftp sftp) throws  Exception{  @b@    	Session sftpSession=null;@b@    	ChannelExec channel=null;@b@    	try {  @b@        	log.info("directory:"+directory+"@uploadFile:"+uploadFile);@b@        	File existFile=new File(directory);@b@        	if(!existFile.exists()){@b@        		existFile.mkdirs();@b@        	}@b@        	@b@        	try{ @b@        		if(sftp==null){@b@        			sftp=connect(sftp_host,sftp_port,sftp_loginuser,sftp_loginpassword);@b@        		}@b@        		sftp.cd(directory);  @b@        	}catch(Exception ee){@b@        		if(sftp==null){@b@        			sftp=connect(sftp_host,sftp_port,sftp_loginuser,sftp_loginpassword);@b@        		}   @b@        		try{@b@	        		sftp.mkdir(directory);@b@	        		sftp.cd(directory);@b@        		}catch(Exception eee){@b@        			sftpSession=sftp.getSession();@b@        			channel=(ChannelExec)sftpSession.openChannel("exec");@b@        			channel.setCommand("mkdir "+directory);@b@        			chmod(directory, "777", sftpSession);   @b@        		}@b@        	}  @b@            File file = new File(uploadFile);  @b@            sftp.put(new FileInputStream(file), file.getName());  @b@        } catch (Exception e) {  @b@            e.printStackTrace();  @b@            log.error("directory:"+directory+"@uploadFile:"+uploadFile,e);@b@        }finally{@b@        	if(channel!=null)@b@        		channel.disconnect();@b@        	if(sftpSession!=null)@b@        		sftpSession.disconnect();@b@        	sftp.disconnect();@b@        	@b@        }  @b@    }  @b@    @b@    @b@    public  static  void upload(String directory,String sftpFileName,InputStream input, ChannelSftp sftp) throws SftpException{@b@    	try {@b@    		sftp.cd(directory);@b@		} catch (Exception e) {@b@			sftp.mkdir(directory);@b@    		sftp.cd(directory);@b@		}@b@    	sftp.put(input, sftpFileName);@b@    }@b@  @b@    /** @b@     * 文件下载 @b@     * @param directory 目录 @b@     * @param downloadFile 要下载文件名 @b@     * @param saveFile 保持的文件名 @b@     * @param sftp @b@     */  @b@    public  static void download(String directory, String downloadFile,  @b@            String saveFile, ChannelSftp sftp) {  @b@        try {  @b@            sftp.cd(directory);  @b@            File file = new File(saveFile);  @b@            sftp.get(downloadFile, new FileOutputStream(file));  @b@        } catch (Exception e) {  @b@            e.printStackTrace();  @b@        }  @b@    }  @b@  @b@    /** @b@     * 文件删除 @b@     * @param directory 目录 @b@     * @param deleteFile 要删除的文件名 @b@     * @param sftp @b@     */  @b@    public  static  void delete(String directory, String deleteFile, ChannelSftp sftp) {  @b@        try {  @b@            sftp.cd(directory);  @b@            sftp.rm(deleteFile);  @b@            System.out.println("删除成功");  @b@        } catch (Exception e) {  @b@            System.out.println("删除失败");  @b@            e.printStackTrace();  @b@        }  @b@    }  @b@  @b@    /** @b@     * 列出目录下的文件 @b@     * @param directory 目录 @b@     * @param sftp @b@     * @return @b@     * @throws SftpException @b@     */  @b@    public  static  Vector listFiles(String directory, ChannelSftp sftp)  @b@            throws SftpException {  @b@        return sftp.ls(directory);  @b@    }  @b@  @b@    @b@    //批量删除文件@b@	public  static void delete(String directory, String[] fileNames, ChannelSftp aa) {@b@		for (String fileName : fileNames) {@b@			 delete(directory, fileName, aa);@b@		}@b@	}@b@	@b@	/**@b@	 * 创建目录文件夹@b@	 * @param directory  要创建文件夹的位置路径@b@	 * @param fileName  要创建文件夹的名称@b@	 * @param sftp   sftp连接@b@	 */@b@	public  static  void mkdir(String directory,String fileName,ChannelSftp sftp){@b@        try {  @b@            try {@b@				sftp.cd(directory);@b@			} catch (Exception e) {@b@				sftp.mkdir(directory);@b@	    		sftp.cd(directory);@b@			}  @b@            sftp.mkdir(fileName);  @b@            System.out.println("文件夹创建成功");  @b@        } catch (Exception e) {  @b@            System.out.println("文件夹创建失败");  @b@            e.printStackTrace();  @b@        }  @b@	}@b@	@b@	public static void chmod(String fileLinux, String chmod, Session session) throws   Exception { @b@	     ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); @b@	     channel.connect(); @b@	     chmod(fileLinux, chmod, channel); @b@	     channel.disconnect(); @b@@b@	    } @b@@b@	    private static void chmod(String fileLinux, String chmod, ChannelSftp channel) throws SftpException { @b@	     int chmodInt = Integer.parseInt(chmod, 8); @b@	      channel.chmod(chmodInt, fileLinux); @b@	    } @b@@b@	@b@ @b@@b@	    @b@	@b@	@b@	public  static  void  main(String[] args) throws  Exception{ @b@		@b@		SftpClient.upload("/_site_domain_/_root/5870/5874/", "C:/temp/t_c279528.html");@b@		@b@	}@b@	@b@	@b@	@b@	@b@	@b@	@b@	@b@}

主要代码说明;没有文件夹执行创建并授权

sftpSession=sftp.getSession();@b@channel=(ChannelExec)sftpSession.openChannel("exec");@b@channel.setCommand("mkdir "+directory);@b@chmod(directory, "777", sftpSession);
<<推荐下载>>
  • (1) 常用Java开源技术库依赖包&源码包
  • (2) 软件工程全生命周期的完整材料样例(56个样例文档)
  • (3) java初级代码100例示例demo代码
  • (4) 115个java完整项目源代码大全
  • (5) 阿里巴巴Java开发手册8种不同版本
  • (6) Web前端开发视频教程
  • (7) 30+明星讲师PPT课件分享一线大厂架构实战经验
  • (8) java开发_架构篇_视频资源分享_v2208
  • (9) java开发_高级篇_视频资源分享_v2208
  • (10) java开发_进阶篇(中级)_视频资源分享_v2208
  • (11) java开发_入门篇_视频资源分享_v2208
  • (12) 微信小程序开发视频1+167源码+实战demo等下载
  • (13) easy-shopping电子商务java源码(附脚本和安装文档说明)下载
  • (14) java常用的72份知名实用的电子书下载
  • (15) java开发性能优化资料整理大全(8份电子文档+3份实战优化)下载
  • (16) 9个常用的算法设计资料和100以上视频课件内容下载
  • (17) vue开发必备常用手册16件下载
  • (18) 21种不同技术集群方案(es、flink、redis、nginx、zk、lvs、kafka、mysql、k8s等)参考资料下载
  • (19) 20种技术代码规范(js/java/dba/阿里/华为/oracle/mysql等)参考资料下载
  • (20) 微服务五套资料(0-1,架构设计,springcloud,nacos等)下载
  • (21) 架构师(28知识图谱+3套简历模板+6套架构实战文档等)完整资料整理下载
  • (22) 大数据18套实战基础知识+8套简历模板下载
  • (23) 并发编程全套(7套+阿里巴巴+亿级实战等)实战资料下载
  • (24) Kafka九套学习整理知识点全套(面试+笔记+代码api+命令+容备等)资料下载
  • (25) java全套9个不同方向类型的面试题(基础+核心+大厂+架构师+近万套题库等)下载
  • (26) JAVA开发常用API帮助文档大全(超52种以上技术资料,高手必备)下载
  • (27) springcloud超详细139件全套学习实战资料( 视频课件+源码demo+文档资料等)下载
  • 更多推荐>>
  • <<热门文章>>