首页

通过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);