当前位置: 首页 > 工具软件 > Orion SSH2 > 使用案例 >

Shell for SSH

宫俊远
2023-12-01

/**   
 * Copyright © 2016 Hefei Wo Yi Information Technology Co., Ltd. All rights reserved.
 * 
 * @Title  SSHShell.java 
 * @Prject  Mhub-comm
 * @Package  com.woyi.mhub.util 
 * @author  wangzi   
 * @date  2016年8月25日 下午3:25:06 
 * @version  V1.0   
 */
package com.wz;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.trilead.ssh2.Connection;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.SFTPv3Client;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;

/**
 * 利用ssh执行shell
 * @ClassName SSHShell
 * @author wangzi
 * @date 2016年8月25日 下午3:25:06
 */
public class SSHShell {
	/**
	 * Windows
	 */
	public static final String OSTYPE_WINDOWS = "Windows";
	/**
	 * Linux
	 */
	public static final String OSTYPE_LINUX = "Linux";
	/**
	 * 连接
	 */
	private Connection conn;

	/**
	 * 构造方法
	 * @Title SSHShell
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 * @throws Exception
	 */
	public SSHShell(String ip, int port, String username, String password) throws Exception {
		conn = new Connection(ip, port);
		conn.connect();
		boolean isAuthenticated = conn.authenticateWithPassword(username, password);
		if (!isAuthenticated) {
			throw new RuntimeException("Authenticat fail!");
		}
	}
	/**
	 * 在远程服务器上执行命令
	 * @Title runRomoteScript
	 * @author wangzi
	 * @param cmds
	 * @param OSType
	 * @return
	 * @throws Exception
	 * @return List<String>
	 */
	public List<String> runRomoteScript(String[] cmds, String osType) throws Exception {
		List<String> result = new ArrayList<String>();
		if (cmds.length == 0) {
			return result;
		}
		Session session = conn.openSession();
		String separator = "";
		if (osType.equals(OSTYPE_WINDOWS)) {
			separator = " && ";
		} else {
			separator = " ; ";
		}
		String cmd = "";
		for (int i = 0; i < cmds.length; i++) {
			if (i == 0) {
				cmd = cmds[i];
			} else {
				cmd = cmd + separator + cmds[i];
			}
		}
		session.execCommand(cmd);
		InputStream stream1 = session.getStdout();
		InputStream stream2 = session.getStderr();
		SequenceInputStream stream = new SequenceInputStream(stream1, stream2);
		InputStream stdout = new StreamGobbler(stream);
		BufferedReader br = new BufferedReader(
				new InputStreamReader(stdout, Charset.forName("GBK")));
		while (true) {
			String line = br.readLine();
			if (line == null){
				break;
			}
			result.add(line);
		}
		br.close();
		session.close();
		return result;
	}
	/**
	 * 从远程服务器获取文件
	 * @Title getFileFromRemote
	 * @author wangzi
	 * @param remoteFileName
	 * @param localDir
	 */
	public void getFileFromRemote(String remoteFileName, String localDir) throws Exception{
		File inputFile = new File(localDir);
		if (!inputFile.exists()) {
			inputFile.mkdirs();
		}
		SCPClient scpClient;
		try {
			scpClient = conn.createSCPClient();
			scpClient.get(remoteFileName, localDir);
		} catch (IOException e) {
			throw new Exception("Get file from remote fail!");
		}
	}
	/**
	 * 将文件发送至服务器
	 * @Title putFileToRemote
	 * @author wangzi
	 * @param localFileName
	 * @param remoteDir
	 */
	public void putFileToRemote(String localFileName, String remoteDir)
			throws Exception{
		try{
			SCPClient scpClient = conn.createSCPClient();
			scpClient.put(localFileName, remoteDir);
		}catch(Exception e){
			throw new Exception("Put file to remote fail!");
		}
	}
	/**
	 * 删除服务器文件
	 * @Title delRemoteFile
	 * @author wangzi
	 * @param remoteFileName
	 */
	public void delRemoteFile(String remoteFileName) throws Exception{
		try{
			SFTPv3Client client = new SFTPv3Client(conn);
			client.rm(remoteFileName);
		}catch(Exception e){
			throw new Exception("Delete remote file fail!");
		}
	}
	
	/**
	 * 断开连接
	 * @Title disConnect
	 * @author wangzi
	 */
	public void disConnect() {
		if (conn != null) {
			conn.close();
		}
	}
	
	public static void main(String[] args) {
		SSHShell shell;
		String cmd;
		try{
			//Windows + MySql
			//注:Windows下每次执行命令后,都要断开连接,重新执行别的操作
			shell = new SSHShell("192.168.1.120", 22, "Administrator", "123");
			cmd = "mysqldump -uroot -ppass --default-character-set=utf8 --no-autocommit --skip-opt --skip-tz-utc"
					+ " -R --verbose --hex-blob --databases ahtxgljapp > C:/120.sql";
			List<String> list = shell.runRomoteScript(new String[]{cmd}, OSTYPE_WINDOWS);
			for(String s:list){
				System.out.println(s);
			}
			shell.disConnect();
			shell = new SSHShell("192.168.1.120", 22, "Administrator", "123");
			shell.getFileFromRemote("C:/120.sql", "C:/");
			shell.disConnect();
			shell = new SSHShell("192.168.1.120", 22, "Administrator", "123");
			shell.delRemoteFile("C:/120.sql");
			shell.disConnect();
			
			//Windows + Oracle
			/*shell = new SSHShell("192.168.1.184", 22, "Administrator", "123");
			cmd = "exp mhub/mhub owner='(mhub)' file = C:/184.dmp";
			List<String> list = shell.runRomoteScript(new String[]{cmd}, OSTYPE_WINDOWS);
			for(String s:list){
				System.out.println(s);
			}
			shell.disConnect();
			shell = new SSHShell("192.168.1.184", 22, "Administrator", "123");
			shell.getFileFromRemote("C:/184.dmp", "C:/");
			shell.disConnect();
			shell = new SSHShell("192.168.1.184", 22, "Administrator", "123");
			shell.delRemoteFile("C:/184.dmp");
			shell.disConnect();*/
			
			//Linux + MySql
			/*shell = new SSHShell("192.168.1.239", 22, "wangzi", "123");
			cmd = "mysqldump -uroot -p123456 --default-character-set=utf8 --no-autocommit --skip-opt --skip-tz-utc"
					+ " -R --verbose --hex-blob --databases test > /home/wangzi/239.sql";
			List<String> list = shell.runRomoteScript(new String[]{cmd}, OSTYPE_LINUX);
			for(String s:list){
				System.out.println(s);
			}
			shell.getFileFromRemote("/home/wangzi/239.sql", "C:/");
			shell.delRemoteFile("/home/wangzi/239.sql");
			shell.disConnect();*/
			
			//Linux + MySql
			/*shell = new SSHShell("192.168.1.239", 22, "wangzi", "123");
			cmd = "exp mhub/mhub owner='(mhub)' file = C:/239.dmp";
			List<String> list = shell.runRomoteScript(new String[]{cmd}, OSTYPE_LINUX);
			for(String s:list){
				System.out.println(s);
			}
			shell.getFileFromRemote("/home/wangzi/239.dmp", "C:/");
			shell.delRemoteFile("/home/wangzi/239.dmp");
			shell.disConnect();*/
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}



orion-ssh2

 类似资料:

相关阅读

相关文章

相关问答