java 远程执行linux shell (基于JSCH)

1. pom.xml

<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>0.1.50</version>
		</dependency>

2. 

package xxxxx;

import java.io.InputStream;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;

public class JschShellUtil {
	private final Logger LOGGER = LoggerFactory.getLogger(JschShellUtil.class);
	private String host;
	private String user;
	private String password;
	private int port;
	private int maxWaitTime;
	private String keyfile;
	private String passphrase;
	private boolean sshKey;
	private ChannelSftp sftp;
	private ChannelExec exec;

	private Session session;

	public JschShellUtil(String host, String user, String password, int port, int maxWaitTime) {
		this.host = host;
		this.user = user;
		this.password = password;
		this.port = port;
		this.maxWaitTime = maxWaitTime;
		this.keyfile = null;
		this.passphrase = null;
		this.sshKey = false;
	}

	public JschShellUtil(String host, String user, int port, int maxWaitTime, String keyfile, String passphrase) {
		this.host = host;
		this.user = user;
		this.password = null;
		this.port = port;
		this.maxWaitTime = maxWaitTime;
		this.keyfile = keyfile;
		this.passphrase = passphrase;
		this.sshKey = true;
	}

	public void open() throws JSchException {
		JSch client = new JSch();
		if (sshKey && keyfile != null && keyfile.length() > 0) {
			client.addIdentity(this.keyfile, this.passphrase);
		}
		session = client.getSession(this.user, this.host, this.port);
		session.setUserInfo(new UserInfo() {
			public String getPassphrase() {
				return null;
			}

			public String getPassword() {
				return password;
			}

			public boolean promptPassphrase(String arg0) {
				return true;
			}

			public boolean promptPassword(String arg0) {
				return true;
			}

			public boolean promptYesNo(String arg0) {
				return true;
			}

			public void showMessage(String arg0) {
			}
		});
		session.setTimeout(maxWaitTime);
		session.connect();
		Channel channel = session.openChannel("sftp");
		channel.connect();
		sftp = (ChannelSftp) channel;
	}

	public void close() {
		if (sftp != null) {
			sftp.disconnect();
			sftp = null;
		}
		if (session != null) {
			session.disconnect();
			session = null;
		}

	}

	public void cd(String path) throws SftpException {
		sftp.cd(path);
	}

	public String pwd() throws SftpException {
		String pwd = sftp.pwd();
		LOGGER.info(sftp.pwd());
		return pwd;

	}

	public void ls() throws SftpException {
		Vector<?> vector = sftp.ls(".");
		for (Object object : vector) {
			if (object instanceof LsEntry) {
				LsEntry entry = LsEntry.class.cast(object);
				LOGGER.info(entry.getFilename());
			}
		}
	}

	public void ls(String path) throws SftpException {
		Vector<?> vector = sftp.ls(path);
		for (Object object : vector) {
			if (object instanceof LsEntry) {
				LsEntry entry = LsEntry.class.cast(object);
				LOGGER.info(entry.getFilename());
			}
		}
	}

	public void rename(String oldPath, String newPath) throws SftpException {
		sftp.rename(oldPath, newPath);
	}

	public void cp(String src, String dest) throws SftpException {
		int lastSlash = src.lastIndexOf("/");
		String srcFile = src;
		String srcDir = ".";
		if (lastSlash > -1) {
			srcFile = src.substring(lastSlash + 1);
			srcDir = src.substring(0, lastSlash);
		}
		String temp = srcDir + "/temp_" + srcFile;
		rename(src, temp);
		rename(temp, dest);
	}

	public void rm(String file) throws SftpException {
		sftp.rm(file);
	}

	public void mv(String src, String dest) throws SftpException {
		rename(src, dest);
	}

	public void rmdir(String path) throws SftpException {
		sftp.rmdir(path);
	}

	public void mkdir(String path) throws SftpException {
		sftp.mkdir(path);
	}

	public void chmod(int permissions, String path) throws SftpException {
		sftp.chmod(permissions, path);
	}

	/**
	 * 执行一次shell命令,之后连接就关闭
	 * @param cmd
	 * @return
	 * @throws Exception
	 */
	public int runCmd(String cmd) throws Exception {
		exec = (ChannelExec) session.openChannel("exec");
		exec.setCommand(cmd);
		exec.setInputStream(null);
		exec.setErrStream(System.err);
		InputStream in = exec.getInputStream();
		exec.connect();

		int res = -1;
		StringBuffer buf = new StringBuffer(1024);
		byte[] tmp = new byte[1024];
		while (true) {
			while (in.available() > 0) {
				int i = in.read(tmp, 0, 1024);
				if (i < 0)
					break;
				buf.append(new String(tmp, 0, i));
			}
			if (exec.isClosed()) {
				res = exec.getExitStatus();
				LOGGER.info("Exit-status: " + res);
				break;
			}
		}
		LOGGER.info(buf.toString());
		exec.disconnect();
		return res;
	}

	public static void main(String[] args) throws Exception {
		String host = "10.121.163.112 ";
		String user = "admin";
		String password = "admin";
		int port = 22;
		int maxWaitTime = 0;
		JschShellUtil jsch = new JschShellUtil(host, user, password, port, maxWaitTime);
		jsch.open();
	

		String filename = "dubbo-demo-provider-2.5.3-assembly.tar.gz";
		jsch.runCmd("cd /home/admin/vlt/dubbo-demo-provider-2.5.3/bin; ./stop.sh");
		
		jsch.close();
	}

}

猜你喜欢

转载自vilight.iteye.com/blog/1913277