AsiaSSH.java 24.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
package com.sitech.ismp.check.interfaces;


import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sitech.ismp.check.util.RemoteController;
import com.sitech.util.upload.RomoteController;

/**
 * 亚联堡垒机
 * @author xqz
 *
 */
public class AsiaSSH implements RomoteController{
	private String host_ip;	//堡垒机ip
	private int port;		//堡垒机端口
	private String login_id;//堡垒机用户名
	private String password;//堡垒机密码
	private String ip;		//目标机ip
	private String userName;//目标机用户名
	private String dbName;		//数据库名
	private String dbUserName;	//数据库用户名
	private String dbPwd;		//数据库密码
	
	private String type = "1";//1主机;2 oracle
	
	private boolean autorized = false;
	private String keywords = "bomcagent";
	private String keyChecking = "no";
	String RPCCMD = "";
	// 存放命令执行结果
	private StringBuffer result = new StringBuffer();
	private StringBuffer ext_result = new StringBuffer();
	Session session;
	Channel channel;
	private String command;
	InputStream inputStream ;  
	OutputStream outputStream ;

	private Logger logger = Logger.getLogger("Test");

	public void setRPCCMD(String rpccmd) {
		RPCCMD = rpccmd;
	}

	/**
	 * 构造函数
	 * 
	 * @param host_ip
	 * @param port
	 * @param login_id
	 * @param password
	 */
	public AsiaSSH(String ip, String userName) {
		this.ip = ip;
		this.userName = userName;
		this.type = "1";
	}
	public AsiaSSH(String ip, String userName, String dbName,String dbUserName, String dbPwd) {
		this.ip = ip;
		this.userName = userName;
		this.dbName = dbName;
		this.dbUserName = dbUserName;
		this.dbPwd = dbPwd;
		this.type = "2";
	}

	public void run() {
		// super.run();
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		try {
			// if(channel!=null&&channel.isConnected()){
			// channel.disconnect();
			// }
			if (session != null && session.isConnected()) {
				session.disconnect();
				System.out.println("Disonnection successed!");
				logger.info("Disconnect ip=" + this.host_ip);
			} else {
				logger
						.info("Disconnect ip=has exception before"
								+ this.host_ip);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			logger.info("ERROR Disconnect ip=" + this.host_ip);
		}
	}
	/**
	 * 执行指令/sql
	 * @param commands
	 * @return
	 */
	public String execCommnd(List<BaseCommand> commands){
		
		String result = "";
		
		try{
			if(channel==null)
				channel = session.openChannel("shell");
			if (channel != null) {
//				((ChannelExec) channel).setCommand(command);
				channel.connect();
				
				boolean b = false;
				
				if(commands!=null){
					for(int i=0;i<commands.size();i++){
						inputStream=channel.getInputStream(); 
						outputStream = channel.getOutputStream();
						
						BaseCommand cmd = commands.get(i);
						
						b = this.sendInfo(cmd.getCommand(), cmd.getEnd_flag());
						if(!b){
							result = "执行指令出错:"+cmd.getCommand();
							break;
						}else if(cmd.isOut_put()){
							String rs = new String(this.result.toString().getBytes("ISO-8859-1"),"GBK");
							result = this.formatNVT(rs,cmd.getCommand());
						}
					}
				}
				
			}else {
				// 执行出错关闭
				this.close();
				logger.error("docommand has error,channel is nulll");
				result = "连接堡垒机出错";
			}
			
//			String result = this.getResultAsStr(command);
//			System.out.println("result=\n"+result);
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			try {
				inputStream.close();
				outputStream.close();
			}catch(Exception e){
			}
			try{
				this.close();
				if (channel != null && channel.isConnected()) {
					channel.disconnect();
				}
				logger.info("IP_channel=" + this.host_ip + ",close+command"
						+ this.command + "");
				logger.info("ssh close command=" + this.command + "");

			} catch (Throwable th1) {
				logger.error("stream close error" + this.command + ",ip="
						+ this.host_ip);
			}
		}
		
		System.out.println("\nexec command result:\n"+result);
		return result;
	}
	/**
	 * 登陆堡垒机
	 * @return
	 */
	public boolean loginSSH(){
		
		String result = "";
		
		try{
			
			InterfaceService impl = new InterfaceService();
			List<BaseCommand> params = impl.getParameter(ip, userName);
			
			channel = session.openChannel("shell");
//			((ChannelShell)channel).setAgentForwarding(true);
			if (channel != null) {
//				((ChannelExec) channel).setCommand(command);
				channel.connect();
				
				boolean b = false;
				
				if(params!=null){
					for(int i=0;i<params.size();i++){
						Thread.sleep(200);
						
						inputStream=channel.getInputStream(); 
						outputStream = channel.getOutputStream();
						
						BaseCommand cmd = params.get(i);
						
						b = this.sendInfo(cmd.getCommand(), cmd.getEnd_flag());
						if(!b){
//							result = "登录堡垒机出错:"+cmd.getCommand();
//							break;
							return false;
						}
					}
				}
			}else {
				// 执行出错关闭
				this.close();
				logger.error("docommand has error,channel is nulll");
//				result = "连接堡垒机出错";
				return false;
			}
			
//			String result = this.getResultAsStr(command);
//			System.out.println("result=\n"+result);
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			try {
				inputStream.close();
				outputStream.close();
			}catch(Exception e){
			}
			try{
				this.close();
				if (channel != null && channel.isConnected()) {
					channel.disconnect();
				}
				logger.info("IP_channel=" + this.host_ip + ",close+command"
						+ this.command + "");
				logger.info("ssh close command=" + this.command + "");

			} catch (Throwable th1) {
				logger.error("stream close error" + this.command + ",ip="
						+ this.host_ip);
			}
		}
		
		System.out.println("\nexec command result:\n"+result);
		return true;
	}

	private boolean sendInfo(String command,String regext) throws Exception{  
			System.out.println(command);
			this.result = new StringBuffer();
			this.command = command;
			if (command != null && !command.endsWith("\n")) {
				command = command + "\n";
			}
				
				outputStream.write((command).getBytes());  
	            outputStream.flush();  
	            
	            
	            
	            StringBuffer sb=new StringBuffer();  
	            int i=-1; 
	            long startTime=System.currentTimeMillis(); 
	            
	            byte[] bytes = new byte[128];

	           	if(System.currentTimeMillis()-startTime<3000){ 
//	           		while ((i = inputStream.read(bytes))!=-1){  
//	                    String str = new String(bytes);  
//	                    System.out.print(str);  
//	                }  
	                while( (i=(char)inputStream.read())>-1){  
	                    if(i==-1){  
	                        throw  new IllegalArgumentException("接收不到消息");  
	                    }  
	                    char ch=(char)i;  
	                    sb.append(ch);   
	                    
//	                    if(sb.toString().endsWith("\n"))
//	                    	System.out.println(sb.toString());
	                    
	                    
	                    if(inputStream.available()==0){
	                    	if(regext==null||regext.equals("")||sb.toString().trim().endsWith(regext.trim())){
//		                    	System.out.print(regext);
		                    	System.out.println(sb.toString());
		                    	result = sb;
		                    	return true;
		                    }
//	                    	else
//	                    		return false;
//	                    	
	                    }
	                }
	           	}else{
                	throw new Exception("访问超时");
                }
	            
				if (channel.isClosed()) {
					System.out.println("channel is closed ");
				} else {
					System.out.println("channel is connect.... ");
				}
			logger.info("ssh connection exec command=" + command);
		return false;
    } 
	
	private String formatNVT(String str,String command){
		String nvt_start = InterfacePro.nvt_start;
		String nvt_end = InterfacePro.nvt_end;
		
//		str = Pattern.compile("\\[0[^\\[0]*m", Pattern.DOTALL).matcher(str).replaceAll("");
		str = Pattern.compile(nvt_start+"[^"+nvt_start+"]*"+nvt_end, Pattern.DOTALL).matcher(str).replaceAll("");
		
		String[] s = str.split("\n");
		
		String result = "";
		if(s.length>0){
			for(int i=0;i<s.length-1;i++){
				if(s[i].indexOf(command)>=0||s[i].indexOf("Last login:")>=0)
					continue;
				else
					result += s[i]+"\n";
			}
		}
		return result;
	}
	
	public void doCommand(String command) {
		try {
			this.result = new StringBuffer();
			this.command = command;
			channel = session.openChannel("exec");
			if (command != null && !command.endsWith("\n")) {
				command = command + "\n";
			}
			if (channel != null) {
				((ChannelExec) channel).setCommand(command);
				channel.connect();
				if (channel.isClosed()) {
					System.out.println("channel is closed ");
				} else {
					System.out.println("channel is connect.... ");
				}
			} else {
				// 执行出错关闭
				this.close();
				logger.error("docommand has error,channel is nulll");
			}
			logger.info("ssh connection exec command=" + command);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("ssh exception command=" + command + ",error=" + e);
		}
	}

	public String getExtResult() {
		try {
			InputStream in = channel.getExtInputStream();
			BufferedInputStream bin = new BufferedInputStream(in);
			int length;
			byte[] bytes = new byte[1024];
			byte[] tmp = new byte[1024];
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					System.out.println(new String(tmp, 0, i));
					this.ext_result.append(new String(tmp, 0, i));
				}
				if (channel.isClosed()) {

					System.out.println("exit-status: "
							+ channel.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
			}

			logger.info("end ssh connection get command result");
		} catch (Exception e) {
			// this.result = new StringBuffer();
			e.printStackTrace();
			logger.error(e);
			logger.error("ssh exception commandresult=" + this.command);
		}
		return this.result.toString();
	}

	public String getResult() {
		if (channel == null || channel.isClosed()) {
			int i = 0;
			while (channel == null || channel.isClosed()) {
				this.doCommand(this.command);
				i += 1;
				if (i > 3 && (channel == null || channel.isClosed())) {
					logger.info("channel has closed,getResult fail,ip="
							+ this.host_ip);
					return "";
				}
				if (channel != null && !channel.isClosed()) {
					break;
				}
			}

		}
		InputStream in = null;
		BufferedInputStream bin = null;

		try {
			in = channel.getInputStream();
			bin = new BufferedInputStream(in);
		} catch (Throwable e) {
			e.printStackTrace();
		}

		try {
			// int length;
			// byte[] bytes = new byte[1024];
			/*
			 * while (true) { try { Thread.sleep(500); } catch (Exception ee) {
			 * ee.printStackTrace(); } while ((length=bin.read(bytes))>0) {
			 * result.append(new String(bytes,0,length)); } if
			 * (channel.isClosed()&&channel.isEOF() ) { // System.out.println("
			 * exit-status: " // + channel.getExitStatus());
			 * 
			 * while ((length=bin.read(bytes))>0) { result.append(new
			 * String(bytes,0,length-1)); } logger.info("ssh
			 * command="+this.command+" exstatus ="); in.close(); bin.close();
			 * System.out.println(result.toString()); break; } }
			 */
			byte[] tmp = new byte[1024];
			long timeout = 60000;
			long wait = 0;
			try {
				while (in != null && timeout > wait) {
					while (in.available() > 0) {
						int i = in.read(tmp, 0, 1024);
						if (i <= 0)
							break;
						// System.out.println(new String(tmp, 0, i));
						this.result.append(new String(tmp, 0, i));
					}
					if (channel.isClosed() || channel.isEOF()) {
						// System.out.println("exit-status:
						// "+channel.getExitStatus());
						break;
					}
					try {
						Thread.sleep(1000);
						logger.info("wait for result=ip" + this.host_ip);
						wait += 1000;
					} catch (Exception ee) {
					}
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			} catch (Throwable th) {
				th.printStackTrace();
			}
			logger.info("end ssh connection get command result");
		} catch (Exception e) {
			// this.result = new StringBuffer();
			e.printStackTrace();
			logger.error(e);
			logger.error("ssh exception commandresult=" + this.command + ",ip="
					+ this.host_ip);
		} catch (Throwable th) {
			th.printStackTrace();
			logger.error("ssh exception_th commandresult=" + this.command
					+ ",ip=" + this.host_ip);
		} finally {
			try {
				in.close();
				bin.close();
				if (channel != null && channel.isConnected()) {
					channel.disconnect();
				}
				logger.info("IP_channel=" + this.host_ip + ",close+command"
						+ this.command + "");
				logger.info("ssh close command=" + this.command + "");

			} catch (Throwable th1) {
				logger.error("stream close error" + this.command + ",ip="
						+ this.host_ip);
			}
		}
		return this.result.toString();
	}

	public void initial()  {
		try {
			login_id = InterfacePro.login_id;
			host_ip = InterfacePro.host_ip;
			port = Integer.parseInt(InterfacePro.port);
			password = InterfacePro.password;
			
			JSch jsch = new JSch();
			session = jsch.getSession(login_id, host_ip, port);
			logger.info("into the step 11111" + login_id + "--" + host_ip
					+ "--" + port + "--" + password);
			if (session != null) {
				session.setPassword(this.password);
				session.setConfig("StrictHostKeyChecking", this.keyChecking);
				// making a connection with timeout.
				session.connect(3000);
				this.autorized = true;
				logger.info("ssh connect successfuly!!! ip= " + this.host_ip);
				if (session != null && !session.isConnected()) {
					this.autorized = false;
					this.close();
				}
			}
		} catch (Exception e) {
			System.out.println("ssh创建session失败");
			e.printStackTrace();
			logger.error(e);
			logger.error("ssh connect fail ip=" + this.host_ip);

		}
		
		boolean b = this.loginSSH();
	}

	public void initial_keychecking(String keychecking) {
		if (keychecking != null
				&& (keychecking.equals("yes") || (keychecking.equals("no")))) {
			this.keyChecking = keychecking;
		}
		try {
			JSch jsch = new JSch();
			session = jsch.getSession(login_id, host_ip, port);
			session.setPassword(this.password);
			session.setConfig("StrictHostKeyChecking", this.keyChecking);
			session.connect(30000); // making a connection with timeout.

			this.autorized = true;
			logger.info("ssh connect successfuly!!! ip= " + this.host_ip);
		} catch (Exception e) {
			System.out.println("ssh创建session失败");
			e.printStackTrace();
			logger.error(e);
			return;
		}
	}

	/**
	 * 
	 */
	public boolean isAuthorized() {
		return this.autorized;
	}

	public boolean isExistDir(String dir) {
		boolean success = true;

		this.doCommand("cd " + dir + "\n");
		// System.out.println("cd "+dir+"\n");
		// System.out.println("cd result="+this.getResult());
		try {
			InputStream in = channel.getInputStream();
			int nextChar;
			while (true) {
				while ((nextChar = in.read()) != -1) {
					result.append((char) nextChar);
				}
				if (channel.isClosed() || channel.isEOF()) {
					// System.out.println(" exit-status: "
					// + channel.getExitStatus());
					if (channel.getExitStatus() != 0) {
						success = false;
					}
					// System.out.println("channel status
					// ="+channel.getExitStatus());
					in.close();
					break;
				}
				try {
					Thread.sleep(500);
				} catch (Exception ee) {
					ee.printStackTrace();
				}
			}
		} catch (Exception e) {
			this.result = new StringBuffer();
			e.printStackTrace();
		}
		/*
		 * if(this.getResult().indexOf("not found")!=-1){ success = false; }
		 */

		return success;
	}

	public boolean isRunning(String keywords) {
		this.keywords = keywords;
		this.doCommand("ps -ef | grep " + this.keywords);
		String result = this.getResult();
		result = result.replaceAll("grep " + this.keywords, " ");
		if (result != null && result.indexOf(this.keywords) != -1) {
			return true;
		} else {
			return false;
		}
	}

	public boolean getResultAsString(String targetString) {
		try {
			InputStream in = channel.getInputStream();
			int nextChar;
			while (true) {
				while ((nextChar = in.read()) != -1) {
					result.append((char) nextChar);
					if (this.result.toString().indexOf(targetString) != -1) {
						return true;
					}
				}
				if (channel.isClosed() || channel.isEOF()) {
					// System.out.println(" exit-status: "
					// + channel.getExitStatus());
					in.close();
					break;
				}
				try {
					Thread.sleep(500);
				} catch (Exception ee) {
					ee.printStackTrace();
					return false;
				}
			}
		} catch (Exception e) {
			this.result = new StringBuffer();
			e.printStackTrace();
			return false;
		}
		if (this.result.toString().indexOf(targetString) != -1) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * return -1 error occured otherwise child file count of the directory
	 */
	public int childCountOfDir(String dir) {
		int count = 0;
		try {
			if (this.isExistDir(dir)) {
				this.doCommand("cd " + dir + ";ls -l | wc -l");
				String result = this.getResult();
				// System.out.println("dddddddddddddddddddd="+result.trim());
				count = Integer.valueOf(result.trim()).intValue() - 1;
			} else {
				count = -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			count = -1;
		}
		return count;
	}

	public boolean createDir(String dir) {
		boolean isExist = false;
		if (dir != null && !dir.trim().equals("") && this.isExistDir(dir)) {
			isExist = true;
		}
		// 逐层分析目录,如果没有则创建.
		if (dir != null && !dir.trim().equals("") && !this.isExistDir(dir)) {
			String[] split_dir = dir.split("/");
			for (int i = 0; i < split_dir.length; i++) {
				String path = "";
				for (int j = 0; j <= i; j++) {
					if (split_dir[j] != null && !split_dir[j].equals("")) {
						path += "/" + split_dir[j];
					}
				}

				if (path != null && !path.equals("")) {
					if (!this.isExistDir(path)) {
						this.doCommand("mkdir " + path);
						this.getResult();
						System.out.println("creat path=" + path);
					}
					if (!this.isExistDir(path)) {
						System.out.println("cat not creat path=" + path);
						return false;
					}
				}
			}
			if (this.isExistDir(dir)) {
				isExist = true;
			}
		}
		return isExist;
	}

	public String getHostName() {
		this.doCommand("hostname");
		String s = null;
		s = getResult();
		String[] s1 = s.split("\n");
		if (s1 != null && s1.length >= 2) {
			// 获取第2个
			if (s1.length == 3)
				return s1[1].trim();
			if (s1.length == 2) {
				return s1[0].trim();
			}
		} else if (s1 != null && s1.length == 1) {
			return s1[0].trim();
		}
		return "";
	}

	private String getOSType() {
		String os_type = "";
		this.doCommand("uname -a");
		String s = null;
		s = getResult();
		String[] s1 = s.split("\n");
		if (s1 != null && s1.length > 0) {
			String row_1 = s1[0];
			if (row_1 != null && row_1.startsWith("uname -a")) {
				os_type = s1[1];
			} else {
				os_type = s1[0];
			}
			os_type = split(os_type, 0);
		}
		return os_type;

	}

	public String split(String str, int pos) {
		StringTokenizer st = new StringTokenizer(str);
		Vector<String> values = new Vector<String>();
		while (st.hasMoreTokens()) {
			values.add(st.nextToken());
		}
		if (pos >= 0 && pos < values.size()) {
			return (String) values.elementAt(pos);
		}
		return "";
	}

	public Vector<String> getResultAsVector(String command) {
		Vector<String> vResult = new Vector<String>();
		String strResult = null;
		this.doCommand(command);
		strResult = this.getResult();
		/*
		 * try{ this.initial(); this.doCommand(command); strResult =
		 * this.getResult(); }catch(Exception e){ e.printStackTrace(); //
		 * logger.info("error has ocurred when execut
		 * CMD="+this.command+",ip="+this.host_ip); }finally{ this.close(); }
		 */

		// logger.info("testsun ssh result "+command+"="+strResult);
		if (strResult != null) {
			String[] results = strResult.split("\n");
			int length = results.length;
			if (results != null && results.length > 1) {
				String mail = (String) results[results.length - 1];
				if (mail.indexOf("have mail in") > -1) {
					length = results.length - 1;
				}
			}
			if (results != null) {
				for (int i = 0; i < length; i++) {
					vResult.addElement(results[i]);
					// System.out.println("" + results[i]);
					// logger.info("testsun ssh result"+command+"
					// "+i+"="+results[i]);
				}
			}
		}

		return vResult;
	}

	public String getResultAsStr(String command) {
		
		String result = "";
		InterfaceService impl = new InterfaceService();
		List commandList = null;
		if(this.type.equals("1")){
			commandList = impl.getShellCommand(command);
			result = this.execCommnd(commandList);//向堡垒机输入数据
		}else{
			commandList = impl.getOracleCommand(command, dbName, dbUserName, dbPwd);
			result = this.execCommnd(commandList);//向堡垒机输入数据
			result = impl.formatOracleResult(command, result);
		}
		
		
		return result;
	}

	public boolean isConnected() {
		if (this.session != null && this.session.isConnected()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String[][] params = new String[2][2];
		params[0][0] = "su bnmsapp1";		//第一个提示符后应该输入的值
		params[0][1] = "Password:";		//第一个提示符后应该输入的值
		params[1][0] = "bnmsapp1";		//第二个提示符后应该输入的值
		params[1][1] = "";				//第二个提示符后应该输入的值
		
		String[][] command = new String[9][2];
		
		command[0][0] = "sqlplus bnms15/bnms15@BNMS_YF";
		command[0][1] = ">";
		command[1][0] = "set heading off";
		command[1][1] = ">";
		command[2][0] = "set pagesize 0";
		command[2][1] = ">";
		command[3][0] = "set feedback off";
		command[3][1] = ">";
		command[4][0] = "set echo off";
		command[4][1] = ">";
		command[5][0] = "set term off";
		command[5][1] = ">";
		command[6][0] = "set trims on";
		command[6][1] = ">";
		command[7][0] = "select * from tb_cde_kbp t where kbp_class like '11-11%';";
		command[7][1] = ">";
		command[8][0] = "exit";
		command[8][1] = "$";
		
//		String[][] params = new String[7][2];//[1]要输入的参数值;[2]代表期待返回的提示字符串
//		
//		params[0][0] = "";//Input Host IP 登录资源的地址
//		params[0][1] = "Input Protocols Type:";
//		
//		params[1][0] = "SSH2";//Input Protocols Type 登录资源的协议一般为SSH2
//		params[1][1] = "Input Hostname:";
//		
//		params[2][0] = "";//Input Hostname	登录的资源名
//		params[2][1] = "Input User Prompt:";
//		
//		params[3][0] = "null";//Input User Prompt	一般输入null即可
//		params[3][1] = "Input Password Prompt:";
//		
//		params[4][0] = "assword:";//Input Password Prompt	一般输入assword:
//		params[4][1] = "Input User:";
//		
//		params[5][0] = "";//Input User	登录主机的帐号
//		params[5][1] = "Input Password:";
//		
//		params[6][0] = "";//Input Password	登录主机的密码
//		params[6][1] = "";
		
		try {
			
//			String comm = "select FUN_ID,FUN_NAME,FUN_TYPE from tb_cfg_fun t WHERE ROWNUM <= 3";
//			AsiaSSH ssh = new AsiaSSH("11111111", "name","BNMS_YF", "bnms15", "bnms15");//执行sql
			String comm = "ls"; 
			AsiaSSH ssh = new AsiaSSH("11111111", "name");//执行shell
			ssh.initial();
			
			InterfaceService impl = new InterfaceService();
			String result = ssh.getResultAsStr(comm);
			
			result = impl.formatOracleResult(comm, result);
			
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public RomoteController cloneObject() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String executeCommand(List<String> commandList) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String executeCommand(String command) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getError() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getIpAddr() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isRunning(String keywords, String username) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isUsed(int port) {
		// TODO Auto-generated method stub
		return false;
	}
		
}