Java执行linux命令及shell脚本

1.工具类

import java.io.*;
import java.util.Properties;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.jcraft.jsch.*;
import com.mvs.model.HostAddress;

public class SshServerUtils {
		
	private static final Logger log = Logger.getLogger(SshServerUtils.class);
	private static Session session = null;
	 
    //连接服务器
    public static void connect(String username, String passwd, String host, int port) {
        try {
            JSch jsch = new JSch();
            //获取sshSession
            session = jsch.getSession(username, host, port);
            //添加密码
            session.setPassword(passwd);
            Properties sshConfig = new Properties();
            //严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            //开启sshSession连接
            session.connect();
            log.info("Server connection successful.");
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }
    //远程文件上传
    public static boolean putFile(HostAddress host, File file) {
    	boolean result = false;
		try {
	    	//connect(host.getUsername(), host.getPasswd(), host.getHost(), host.getPort());
			ChannelSftp  channelSftp = (ChannelSftp)session.openChannel("sftp");
			channelSftp.connect();
			ChannelSftp sftp = (ChannelSftp) channelSftp;
			 boolean isFile = true;
			try {
				sftp.cd(host.getDir());
				isFile = true;
			} catch (SftpException e) {
				isFile = false;
			}
			if(isFile == false) {
				try {
					sftp.mkdir(host.getDir());
					sftp.cd(host.getDir());
				} catch (SftpException e) {
					e.printStackTrace();
				}
			}
			if (file != null) {
				sftp.put(new FileInputStream(file), file.getName());
				result = true;
			} else {
				result = false;
			}
			channelSftp.disconnect();
    		sftp.disconnect();
    		channelSftp.exit();
    		sftp.exit();
		} catch (Exception e) {
			log.info("上传失败!",e);
			result = false;
		}finally {
			//closeSession();
			if (file.exists() && file.isFile()) {
				file.delete();
			}
		}
		return result;
    }
    
    /**
     * 删除文件
     * 
     * @param directory
    *            要删除文件所在目录
    * @param deleteFile
    *            要删除的文件
    * @param sftp
    */
    public static boolean delete(HostAddress host, String deleteFile) {
    	boolean result = false;
    	try {
	    	//connect(host.getUsername(), host.getPasswd(), host.getHost(), host.getPort());
			ChannelSftp  channelSftp = (ChannelSftp)session.openChannel("sftp");
			channelSftp.connect();
			ChannelSftp sftp = (ChannelSftp) channelSftp;
    		sftp.cd(host.getDir());
    		sftp.rm(deleteFile);
    		result = true;
    		channelSftp.disconnect();
    		sftp.disconnect();
    		channelSftp.exit();
    	} catch (Exception e) {
    		result = false;
    		log.info("删除失败!", e);
    	}finally {
            //closeSession();
        }
    	return result;
    }
 
    //执行相关命令
    public static String execCmd(String command, HostAddress host) {
        String resultJson = null;
        ChannelExec channelExec = null;
        if (command != null) {
            try {
            	//connect(host.getUsername(), host.getPasswd(), host.getHost(), host.getPort());
                channelExec = (ChannelExec) session.openChannel("exec");
                // 设置需要执行的shell命令
                log.info("linux命令:" + command);
                channelExec.setInputStream(null);
                channelExec.setErrStream(System.err);
                channelExec.setCommand(command);
                InputStream in = channelExec.getInputStream();
                channelExec.connect();
                //读数据
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                	resultJson += line+"/r/n";
                }
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != channelExec) {
                    channelExec.disconnect();
                }
            }
        }
        return resultJson;
    } 
 
    public static void closeSession() {
        if (session != null) {
            session.disconnect();
        }
 
    }
 
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        return str.replace("-", "");
    }

}

2.服务器属性对象

public class HostAddress {
	private String host;
	private Integer port;
	private String username;
	private String passwd;
	private String dir;
public String getHost() {
	
		return host;
	}
	public void setHost(String host) {
	
		this.host = host;
	}
	public Integer getPort() {
	
		return port;
	}
	public void setPort(Integer port) {
	
		this.port = port;
	}
	public String getUsername() {
	
		return username;
	}
	public void setUsername(String username) {
	
		this.username = username;
	}
	public String getPasswd() {
	
		return passwd;
	}
	public void setPasswd(String passwd) {
	
		this.passwd = passwd;
	}
	public String getDir() {
	
		return dir;
	}
	public void setDir(String dir) {
	
		this.dir = dir;
	}
}

 

转载于:https://my.oschina.net/lisc2016/blog/3080457

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值