summaryrefslogtreecommitdiff
path: root/src/com/nis/nmsclient/util/ProcessUtil.java
blob: 02deffc3c76dffd61d44ad95bc5695ec0a505c3c (plain)
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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
package com.nis.nmsclient.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.nis.nmsclient.common.Contants;

public class ProcessUtil
{
	
	static Logger logger = Logger.getLogger(ProcessUtil.class);
	private static final String EXEC_CMD_FILE = Contants.LOCAL_SCRIPT_PATH + "/execCmdBySu.sh";
	private static final String CHECK_USERPASS_FILE = Contants.LOCAL_SCRIPT_PATH
			+ "/check_userpass.sh";
	private static Byte[] oWin = new Byte[0];
	private static Byte[] oLinux = new Byte[0];
	
	/**
	 * 从文件读取PID值
	 * 
	 * @param pidFile
	 *            存放PID的文件
	 * @return PID数组
	 * @throws Exception
	 */
	public static String[] getProcessIdByFile(File pidFile) throws Exception
	{
		String[] pids = null;
		if (pidFile.exists())
		{
			String[] values = FileWrUtil.cfgFileReader(pidFile);
			if (values != null && values.length > 0 && values[0].trim().length() > 0)
			{
				pids = values[0].trim().split(",");
			}
			
		}
		return pids;
	}
	
	/**
	 * 根据PID按不同操作系统判断进程是否存在
	 * 
	 * @param pid
	 * @return true 存在,false 不存在
	 * @throws Exception
	 */
	public static boolean isProcessExistByPid(String pid) throws Exception
	{
		boolean flag = false;
		// 根据操作系统确定获取进程ID的方式
		String os = System.getProperty("os.name");
		if (os.startsWith("Windows"))
		{
			flag = isWinProcessExistByPid(pid.trim());
		} else if (os.startsWith("Linux"))
		{
			flag = isLinuxProcessExistByPid(pid.trim());
		} else
		{
			throw new IOException("unknown operating system: " + os);
		}
		
		return flag;
	}
	
	/**
	 * 根据PID判断Linux下进程是否存在
	 * 
	 * @param pid
	 * @return
	 */
	public static boolean isLinuxProcessExistByPid(String pid)
	{
		String cmd = "ps -p " + pid.trim() + " | grep " + pid.trim()
				+ " | grep -v defunct | awk '{print $1}'";
		String[] shellCmd1 = new String[] { "/bin/bash", "-c", cmd };
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		boolean flag = false;
		logger.info("isLinuxProcessExistByPid cmd-----" + cmd);
		synchronized (oLinux)
		{
			try
			{
				// 找到根据进程名获取到的进程号列表
				process = Runtime.getRuntime().exec(shellCmd1);
				process.getOutputStream().close();
				
				bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
				String line = null;
				while ((line = bReader.readLine()) != null)
				{
					logger.debug("isLinuxProcessExistByPid line-----" + line);
					flag = true;
				}
				while ((line = errorReader.readLine()) != null)
				{
					logger.debug("isLinuxProcessExistByPid error line--->" + line);
				}
				
			} catch (IOException e)
			{
				logger.error(Utils.printExceptionStack(e));
			} finally
			{
				try
				{
					if (bReader != null)
					{
						bReader.close();
					}
					if (errorReader != null)
					{
						errorReader.close();
					}
					if (process != null)
					{
						process.destroy();
					}
				} catch (IOException e)
				{
					logger.error(Utils.printExceptionStack(e));
				}
			}
			
		}
		return flag;
	}
	
	/**
	 * 根据PID判断Windows下进程是否存在
	 * 
	 * @param pid
	 * @return
	 */
	public static boolean isWinProcessExistByPid(String pid)
	{
		String[] cmd = new String[] { "cmd.exe", "/C",
				"wmic process where processId=" + pid.trim() + " get processId" };
		logger.info("isWinProcessExistByPid cmd-----" + cmd[2]);
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		boolean flag = false;
		try
		{
			synchronized (oWin)
			{
				process = Runtime.getRuntime().exec(cmd);
				process.getOutputStream().close();
				bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
				String line = null;
				while ((line = bReader.readLine()) != null)
				{
					logger.debug("isWinProcessExistByPid line-----" + line);
					if (line.trim().equals(pid.trim()))
					{
						flag = true;
					}
				}
				while ((line = errorReader.readLine()) != null)
				{
					logger.debug("isWinProcessExistByPid error line--->" + line);
				}
			}
			
		} catch (IOException e)
		{
			logger.error(Utils.printExceptionStack(e));
		} finally
		{
			try
			{
				if (bReader != null)
				{
					bReader.close();
				}
				if (errorReader != null)
				{
					errorReader.close();
				}
				if (process != null)
				{
					process.destroy();
				}
			} catch (IOException e)
			{
				logger.error(Utils.printExceptionStack(e));
			}
		}
		
		return flag;
	}
	
	/**
	 * Linux下执行命令
	 * 
	 * @param cmd
	 * @return
	 * @throws Exception
	 */
	public static String execLinuxCmd(String cmd) throws Exception
	{
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		try
		{
			// logger.debug("execLinuxCmd start-------" + cmd);
			String[] shellCmd = new String[] { "/bin/bash", "-c", cmd };
			process = Runtime.getRuntime().exec(shellCmd);
			process.getOutputStream().close();
			
			bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			String line = null;
			while ((line = bReader.readLine()) != null)
			{
				logger.debug("execLinuxCmd line--->" + line);
			}
			StringBuffer errorSb = new StringBuffer();
			while ((line = errorReader.readLine()) != null)
			{
				logger.debug("execLinuxCmd error line--->" + line);
				errorSb.append(line + ",");
			}
			
			if (errorSb.toString().length() > 0)
			{
				errorSb.deleteCharAt(errorSb.length() - 1);
				return errorSb.toString();
			}
			
			// logger.debug("execLinuxCmd end-------" + cmd);
		} catch (Exception e)
		{
			throw e;
		} finally
		{
			try
			{
				if (bReader != null)
				{
					bReader.close();
				}
				if (errorReader != null)
				{
					errorReader.close();
				}
				if (process != null)
				{
					process.destroy();
				}
			} catch (Exception e1)
			{
			}
		}
		return null;
	}
	
	/**
	 * windows下执行命令
	 * 
	 * @param cmd
	 * @return
	 * @throws Exception
	 */
	public static String execWinCmd(String cmd) throws Exception
	{
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		try
		{
			logger.debug("execWinCmd start-------" + cmd);
			//cmd = handlerWinSpace(cmd);
			String[] cmdArr = new String[] { "cmd.exe", "/C", cmd };
			process = Runtime.getRuntime().exec(cmdArr);
			if (cmd.endsWith(".exe"))
			{
				synchronized (process)
				{
					process.wait(1000 * 5);
				}
				process.getOutputStream().close();
				process.getInputStream().close();
				process.getErrorStream().close();
			} else
			{
				process.getOutputStream().close();
				Charset platform = Charset.forName(System.getProperty("sun.jnu.encoding"));
				bReader = new BufferedReader(new InputStreamReader(process.getInputStream(), platform));
				errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), platform));
				String line = null;
				while ((line = bReader.readLine()) != null)
				{
					logger.debug("execWinCmd line--->" + line);
				}
				StringBuffer errorSb = new StringBuffer();
				while ((line = errorReader.readLine()) != null)
				{
					logger.debug("execWinCmd error--->" + line);
					errorSb.append(line + ",");
				}
				if (errorSb.length() > 0)
				{
					errorSb.deleteCharAt(errorSb.length() - 1);
					return errorSb.toString();
				}
			}
			
			logger.debug("execWinCmd end-------" + cmd);
			
		} catch (Exception e)
		{
			throw e;
		} finally
		{
			try
			{
				if (bReader != null)
				{
					bReader.close();
				}
				if (errorReader != null)
				{
					errorReader.close();
				}
				if (process != null)
				{
					process.destroy();
				}
			} catch (Exception e1)
			{
			}
		}
		
		return null;
	}
	
	/**
	 * 执行文件或命令,不同的操作系统按相应方式执行
	 * 
	 * @param cmd
	 *            文件全路径或执行命令
	 * @param cmdParams
	 *            执行参数
	 * @param username
	 *            执行用户
	 * @param passwd
	 *            执行用户的密码
	 * @return 返回错误输出:若有返回,则执行失败;若返回null,则执行成功
	 * @throws IOException
	 */
	public static String runExec(String cmd, String[] cmdParams, String username, String passwd)
			throws IOException
	{
		return runExec(cmd, cmdParams, username, passwd, false);
	}
	
	/**
	 * 执行文件或命令,不同的操作系统按相应方式执行
	 * 
	 * @param isDaemon
	 *            若为true, NC守护进程, 不读取输出;若为false, 执行文件或命令,读取输出
	 * @return
	 * @throws IOException
	 */
	public static String runExec(String cmd, String[] cmdParams, String username, String passwd,
			boolean isDaemon) throws IOException
	{
		// 根据操作系统确定运行方式
		String os = System.getProperty("os.name");
		Process process = null;
		try
		{
			logger.debug("runExec start-------" + cmd);
			String error = null;
			if (os.startsWith("Windows"))
			{
				StringBuffer sb = new StringBuffer();
				if (isDaemon)
				{// -- 执行NC守护进程脚本
					sb.append("start /b " + handlerWinSpace(cmd));
					if (cmdParams != null && cmdParams.length > 0)
					{
						// 如果执行参数为数组类型时使用
						for (String param: cmdParams)
						{
							// 带空格参数的特殊处理
							sb.append(" " + handlerWinSpace(param));
						}
					}
					sb.append(" >nul 2>&1");
					logger.info("runExec Windows-------" + sb.toString());
					String[] cmdArr = new String[] { "cmd.exe", "/C", sb.toString() };
					process = Runtime.getRuntime().exec(cmdArr);
					synchronized (process)
					{
						process.wait(1000 * 5);
					}
					process.getOutputStream().close();
					process.getInputStream().close();
					process.getErrorStream().close();
				} else
				{
					sb.append(handlerWinSpace(cmd));
					if (cmdParams != null && cmdParams.length > 0)
					{
						// 如果执行参数为数组类型时使用
						for (String param: cmdParams)
						{
							// 带空格参数的特殊处理
							sb.append(" " + handlerWinSpace(param));
						}
					}
					logger.info("runExec Windows-------" + sb.toString());
					error = execWinCmd(sb.toString());
				}
			} else if (os.startsWith("Linux"))
			{
				StringBuffer sb = new StringBuffer();
				sb.append("nohup " + cmd.trim());
				if (cmdParams != null && cmdParams.length > 0)
				{
					// 如果执行参数为数组类型时使用
					for (String param: cmdParams)
					{
						// 带空格参数的特殊处理
						sb.append(" " + handlerLinuxSpace(param));
					}
				}
				sb.append(" >/dev/null 2>&1 &");
				logger.info("runExec Linux-------" + sb.toString());
				if (username != null && username.trim().length() > 0)
				{
					// -- 有密码调用execCmdBySu.sh文件执行
					if (passwd != null && passwd.trim().length() > 0)
					{
						File file = new File(EXEC_CMD_FILE);
						// 执行结果标识参数1、0 表示执行命令后是否添加:echo $?
						String temp = file.getCanonicalPath() + " 1 \"" + sb.toString() + "\" "
								+ username.trim();
						logger.info("runExec-->" + temp);
						temp += " " + DESUtil.desDecrypt(passwd.trim());
						sb.delete(0, sb.length());
						sb.append("nohup " + temp + " >/dev/null 2>&1 &");
					} else
					{
						// -- 无密码自己拼命令
						String temp = "su - -c \"" + sb.toString() + "\" " + username.trim();
						logger.info("runExec-->" + temp);
						sb.delete(0, sb.length());
						sb.append(temp);
					}
				}
				error = execLinuxCmd(sb.toString());
			} else
			{
				throw new IOException("unknown operating system: " + os);
			}
			
			logger.debug("sleep: 10 seconds");
			Thread.sleep(10 * 1000);
			
			logger.debug("runExec end-------" + cmd);
			
			return error;
		} catch (Exception e)
		{
			logger.error(Utils.printExceptionStack(e));
//			return "出现异常:" + e.getMessage();
			return "Abnormality:" + e.getMessage();
		} finally
		{
			try
			{
				if (process != null)
				{
					process.destroy();
				}
			} catch (Exception e1)
			{
			}
		}
		
	}
	
	/**
	 * 赋权限:若path是目录,给目录下所有文件赋指定的权限
	 * 
	 * @param permit
	 *            权限的整数值
	 * @param path
	 *            需要赋权限的文件或目录
	 */
	public static void permit(long permit, File path)
	{
		// 根据操作系统确定运行方式
		String os = System.getProperty("os.name");
		logger.debug("permit-----path=" + path.getAbsolutePath());
		try
		{
			if (os.startsWith("Linux") && path != null && path.exists())
			{
				if (path.isDirectory() && path.listFiles().length > 0)
				{
					execLinuxCmd("chmod " + permit + " "
							+ handlerLinuxSpace(path.getCanonicalPath()) + File.separator + "*");
					File[] files = path.listFiles();
					for (File file: files)
					{
						if (file.isDirectory())
						{
							permit(permit, file);
						}
					}
				} else
				{
					execLinuxCmd("chmod " + permit + " "
							+ handlerLinuxSpace(path.getCanonicalPath()));
				}
			}
		} catch (Exception e)
		{
			logger.error(Utils.printExceptionStack(e));
		}
	}
	
	/**
	 * 杀进程:根据操作系统以不同的方式停用进程
	 * 
	 * @param processId
	 * @throws IOException
	 */
	public static void killProcess(String processId) throws IOException
	{
		// 根据操作系统确定运行方式
		String os = System.getProperty("os.name");
		try
		{
			if (os.startsWith("Windows"))
			{
				String cmd = "wmic process where processId=" + processId + " delete";
				logger.debug("killProcess win cmd-------" + cmd);
				execWinCmd(cmd);
			} else if (os.startsWith("Linux"))
			{
				String cmd = "kill -9 " + processId;
				logger.debug("killProcess linux cmd-------" + cmd);
				execLinuxCmd(cmd);
			} else
			{
				throw new IOException("unknown operating system: " + os);
			}
			Thread.sleep(5 * 1000);
		} catch (Exception e)
		{
			logger.error(Utils.printExceptionStack(e));
		}
	}
	
	/**
	 * 只能用来运行命令,取得运行命令的输出结果,根据错误输出流来判断命令运行成功与否 如果需切换用户,调用execCmdBySu.sh执行
	 * 
	 * @param cmd
	 * @param username
	 * @return 成功:0|命令输出信息;失败:1|失败信息
	 * @throws Exception
	 */
	public static String runExecGetResult(String cmd, String username, String passwd)
			throws Exception
	{
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		String seprator = "|";
		try
		{
			logger.debug("runExecGetResult start-------" + cmd);
			String os = System.getProperty("os.name");// 根据操作系统确定运行方式
			String result = "0" + seprator;
			String[] cmdArr = null;
			if (os.startsWith("Windows"))
			{
				// 【&& echo 0 || echo 1】 执行成功输出0,执行失败输出1,为了与Linux下的一致来取执行结果
				String tempCmd = handlerWinSpace(cmd) + " && echo 0 || echo 1";
				logger.info("runExecGetResult-->" + tempCmd);
				cmdArr = new String[] { "cmd.exe", "/C", tempCmd };
			} else if (os.startsWith("Linux"))
			{
				String tempCmd = cmd.trim();
				if (username != null && username.trim().length() > 0)
				{
					// -- 有密码调用execCmdBySu.sh文件执行
					if (passwd != null && passwd.trim().length() > 0)
					{
						File file = new File(EXEC_CMD_FILE);
						// 执行结果标识参数1、0 表示执行命令后是否添加:echo $?
						tempCmd = file.getCanonicalPath() + " 0 \"" + cmd.trim() + "\" "
								+ username.trim();
						logger.info("runExecGetResult-->" + tempCmd);
						tempCmd += " " + DESUtil.desDecrypt(passwd.trim());
					} else
					{
						// -- 无密码自己拼命令
						tempCmd = "su - -c \"" + cmd.trim() + ";echo $?\" " + username.trim();
						logger.info("runExecGetResult-->" + tempCmd);
					}
				} else
				{
					tempCmd += ";echo $?";// 为了与脚本中的echo $?运行命令保持一致
					logger.info("runExecGetResult-->" + tempCmd);
				}
				cmdArr = new String[] { "/bin/bash", "-c", tempCmd };
			} else
			{
				throw new IOException("unknown operating system: " + os);
			}
			process = Runtime.getRuntime().exec(cmdArr);
			process.getOutputStream().close();
			bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = bReader.readLine()) != null)
			{
				sb.append(line + ",");
				logger.debug("runExecGetResult right-->" + line);
			}
			StringBuffer errorSb = new StringBuffer();
			while ((line = errorReader.readLine()) != null)
			{
				errorSb.append(line + ",");
				logger.debug("runExecGetResult error-->" + line);
			}
			if (errorSb.length() > 0)
			{
				errorSb.deleteCharAt(errorSb.length() - 1);
				result = "1" + seprator + errorSb.toString();
			} else if (sb.length() > 0)
			{
				sb.deleteCharAt(sb.length() - 1);// 去掉最后一个逗号
				int lastIndex = sb.lastIndexOf(",");
				String flag = "";
				logger.debug("runExecGetResult lastIndex-->" + lastIndex);
				if (lastIndex != -1)
				{
					// 配合运行命令(echo $?),最后一行为结果标识
					flag = sb.substring(lastIndex + 1, sb.length()).trim();
					sb.delete(lastIndex, sb.length());// 删除结果标识和其前面的逗号
				} else
				{
					flag = sb.toString().trim();
					sb.delete(0, sb.length());
				}
				logger.debug("runExecGetResult flag-->" + flag);
				// 配合运行命令(echo $?):最后一行若是0,则执行成功,若非0,则失败
				if ("0".equals(flag))
				{
					result = "0" + seprator + sb.toString();
				} else
				{
					result = "1" + seprator + sb.toString();
				}
			}
			logger.debug("runExecGetResult result-->" + result);
			logger.debug("runExecGetResult end-------" + cmd);
			
			return result;
		} catch (Exception e)
		{
			throw e;
		} finally
		{
			try
			{
				if (bReader != null)
				{
					bReader.close();
				}
				if (errorReader != null)
				{
					errorReader.close();
				}
				if (process != null)
				{
					process.destroy();
				}
			} catch (Exception e1)
			{
			}
		}
	}
	
	/**
	 * 验证用户名或用户组是否存在
	 * 
	 * @param username
	 * @param userGroup
	 * @return
	 * @throws Exception
	 */
	public static boolean checkUserOrGroupExist(String username, String userGroup) throws Exception
	{
		try
		{
			boolean flag = false;
			logger.debug("checkUserOrGroupExist start-------");
			String os = System.getProperty("os.name");// 根据操作系统确定运行方式
			if (os.startsWith("Windows"))
			{
				flag = true;
			} else if (os.startsWith("Linux"))
			{
				if (username == null && userGroup == null)
				{
					flag = true;
				} else
				{
					StringBuffer sb = new StringBuffer();
					if (username != null)
					{
						sb.append("su " + username.trim() + ";");
					}
					if (userGroup != null)
					{
						sb.append("groups " + userGroup.trim() + ";");
					}
					if (execLinuxCmd(sb.toString()) == null)
					{// 没有返回值,验证通过
						flag = true;
					}
				}
			} else
			{
				throw new IOException("unknown operating system: " + os);
			}
			
			logger.debug("checkUserOrGroupExist end-------");
			
			return flag;
		} catch (Exception e)
		{
			throw e;
		}
		
	}
	
	/**
	 * 验证用户名和密码是否正确,调用check_userpass.sh脚本
	 * 
	 * @param username
	 * @param passwd
	 */
	public static boolean checkUserPass(String username, String passwd) throws Exception
	{
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		try
		{
			boolean flag = false;
			logger.debug("checkUserPass start-------");
			String os = System.getProperty("os.name");// 根据操作系统确定运行方式
			if (os.startsWith("Windows"))
			{
				flag = true;
			} else if (os.startsWith("Linux"))
			{
				File file = new File(CHECK_USERPASS_FILE);
				StringBuffer sb = new StringBuffer();
				sb.append(file.getCanonicalPath() + " " + Utils.getLocalIp());
				if (username != null)
				{
					sb.append(" " + username.trim());
					if (passwd != null)
					{
						sb.append(" " + DESUtil.desDecrypt(passwd.trim()));
					}
				}
				sb.append(" >/dev/null 2>&1;");
				sb.append("echo $?");
				
				String[] cmdArr = new String[] { "/bin/bash", "-c", sb.toString() };
				process = Runtime.getRuntime().exec(cmdArr);
				process.getOutputStream().close();
				bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
				String line = null;
				while ((line = bReader.readLine()) != null)
				{
					logger.debug("checkUserPass line-------" + line);
					if (line.trim().equals("0"))
					{
						flag = true;
					}
				}
				while ((line = errorReader.readLine()) != null)
				{
					logger.debug("checkUserPass error line--->" + line);
				}
			} else
			{
				throw new IOException("unknown operating system: " + os);
			}
			
			logger.debug("runExecGetResult end-------");
			
			return flag;
		} catch (Exception e)
		{
			throw e;
		} finally
		{
			try
			{
				if (bReader != null)
				{
					bReader.close();
				}
				if (errorReader != null)
				{
					errorReader.close();
				}
				if (process != null)
				{
					process.destroy();
				}
			} catch (Exception e1)
			{
			}
		}
	}
	
	/**
	 * 检查文件或命令是否存在且可执行
	 * 
	 * @param cmd
	 * @return true 是,false 否
	 * @throws IOException
	 */
	public static boolean isFileOrCmdExist(String cmd) throws IOException
	{
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		boolean flag = false;
		logger.debug("isFileOrCmdExist start-------" + cmd);
		try
		{
			// 根据操作系统确定运行方式
			String os = System.getProperty("os.name");
			if (os.startsWith("Windows"))
			{
				logger.debug("isFileOrCmdExist Windows-------" + cmd);
				// 待实现: 目前只处理了文件,执行命令未实现判断
				File startFile = new File(cmd);
				if (startFile.exists() && startFile.canExecute())
				{
					flag = true;
				}
			} else if (os.startsWith("Linux"))
			{
				String cmd1 = "[ -x " + cmd + " ] || which " + cmd + ";echo $?";
				logger.debug("isFileOrCmdExist linux-------" + cmd1);
				String[] shellCmd = new String[] { "/bin/bash", "-c", cmd1 };
				process = Runtime.getRuntime().exec(shellCmd);
				process.getOutputStream().close();
				
				bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
				String line = null;
				while ((line = bReader.readLine()) != null)
				{
					logger.debug("isFileOrCmdExist linux--->" + line);
					if (line.trim().equals("0"))
					{
						flag = true;
					}
				}
				while ((line = errorReader.readLine()) != null)
				{
					logger.debug("isFileOrCmdExist linux error--->" + line);
				}
			} else
			{
				throw new IOException("unknown operating system: " + os);
			}
			
		} catch (Exception e)
		{
			logger.error(Utils.printExceptionStack(e));
			return false;
		} finally
		{
			try
			{
				if (bReader != null)
				{
					bReader.close();
				}
				if (errorReader != null)
				{
					errorReader.close();
				}
				if (process != null)
				{
					process.destroy();
				}
			} catch (Exception e1)
			{
			}
		}
		logger.debug("isFileOrCmdExist end-------" + cmd);
		
		return flag;
	}
	
	/**
	 * 
	 * TODO 处理路径中带有空格 括号的问题 在外部加入""
	 * 
	 * @author jinshujuan May 30, 2013
	 * @version 1.0
	 * @param str
	 * @return
	 */
	public static String handlerWinPath(String str)
	{
		
		if (str != null && !str.equals(""))
		{
			if (str.indexOf(" ") != -1 || str.indexOf("(") != -1 || str.indexOf(")") != -1)
			{
				str = "\"" + str + "\"";
			}
		}
		logger.debug("handlerWinPath---str=" + str);
		return str;
	}
	
	/**
	 * 对Windows下路径中带空格的特殊处理
	 * 
	 * @param str
	 * @return
	 */
	public static String handlerWinSpace(String str)
	{
		/*
		 * 注意::若最后一级路径出现空格,处理上的存在Bug -- 需要在最后一级也加上\\或/ 如:xcopy /y D:\\Program
		 * Files\\Test 1\\ D:\\Program Files\\Test 2\\ /s/e 可以正常替换空格 xcopy /y
		 * D:\\Program Files\\Test 1 D:\\Program Files\\Test 2 /s/e
		 * 不能正常替换空格,最后一级Test 1和Test 2中的空格替换不了。
		 */
		if (str != null)
		{
			if (str.indexOf(":\\") != -1)
			{
				// 针对这样的命令, 如:
				// D:\Program Files\Test\test.bat >> D:\Program Files\test.log;
				// xcopy /y D:\Program Files\Test D:\Program Files\Test2 /s/e
				// 先取第一个:\之后,每次再取与\之间的串循环替换空格
				// 若与\之间的串中有:\(/test.bat >> D:/, /Test D:/)则不用替换空格
				int index = str.indexOf(":\\");
				String start = str.substring(0, index + 2);
				String end = str.substring(index + 2, str.length());
				while (end.indexOf("\\") != -1)
				{
					index = end.indexOf("\\");
					String middle = end.substring(0, index + 1);
					if (middle.endsWith(":\\"))
					{
						start += middle;
					} else
					{
						start += middle.replace(" ", "\" \"");
					}
					end = end.substring(index + 1, end.length());
				}
				start += end;
				str = start;
			} else if (str.indexOf(":/") != -1)
			{
				// 针对这样的命令, 如:
				// D:/Program Files/Test/test.bat >> D:/Program Files/test.log;
				// xcopy /y D:/Program Files/Test D:/Program Files/Test2 /s/e
				// 先取第一个:/之后,每次再取与/之间的串循环替换空格
				// 若与/之间的串中有:/(/test.bat >> D:/, /Test D:/)或 /(/Test2 /)则不用替换空格
				int index = str.indexOf(":/");
				String start = str.substring(0, index + 2);
				String end = str.substring(index + 2, str.length());
				while (end.indexOf("/") != -1)
				{
					index = end.indexOf("/");
					String middle = end.substring(0, index + 1);
					if (middle.endsWith(":/") || middle.endsWith(" /"))
					{
						start += middle;
					} else
					{
						start += middle.replace(" ", "\" \"");
					}
					end = end.substring(index + 1, end.length());
				}
				start += end;
				str = start;
			}
		}
		logger.debug("handlerWinSpace---str=" + str);
		return str;
	}
	
	/**
	 * 对Linux下路径中带空格的特殊处理
	 * 
	 * @param str
	 * @return
	 */
	public static String handlerLinuxSpace(String str)
	{
		if (str != null)
		{
			str = str.trim().replace(" ", "\\ ");
		}
		return str;
	}
	
	/**
	 * 根据关键字查找进程PID
	 * 
	 * @param procSearchKey
	 * @return pid列表
	 * @throws Exception
	 */
	public static List<String> getProcessIdBySearchKey(String procSearchKey) throws Exception
	{
		List<String> value = null;
		// 根据操作系统确定获取进程ID的方式
		String os = System.getProperty("os.name");
		if (os.startsWith("Windows"))
		{
			value = getWindowsProcessId(procSearchKey);
		} else if (os.startsWith("Linux"))
		{
			value = getLinuxProcessId(procSearchKey);
		} else
		{
			throw new IOException("unknown operating system: " + os);
		}
		
		return value;
	}
	
	/**
	 * Windows下根据关键字查找进程,关键字不区分大小写
	 * 
	 * @param procSearchKey
	 * @return
	 */
	public static List<String> getWindowsProcessId(String procSearchKey)
	{
		// "wmic process get
		// Caption,commandLine,Description,ExecutablePath,Name,processId|findstr
		// /i " + procSearchKey + "|findstr /v findstr"
		String[] cmd = new String[] {
				"cmd.exe",
				"/C",
				"wmic process where \"Caption like '%%" + procSearchKey
						+ "%%' or CommandLine like '%%" + procSearchKey
						+ "%%' or Description like '%%" + procSearchKey
						+ "%%' or ExecutablePath like '%%" + procSearchKey + "%%' or Name like '%%"
						+ procSearchKey
						+ "%%'\" get Name,ProcessId,CommandLine|findstr /v wmic|findstr /v findstr" };
		logger.info("getWindowsProcessId-----" + cmd[2]);
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		List<String> processIDList = null;
		try
		{
			synchronized (oWin)
			{
				process = Runtime.getRuntime().exec(cmd);
				process.getOutputStream().close();
				bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
				String line = null;
				processIDList = new ArrayList<String>();
				while ((line = bReader.readLine()) != null)
				{
					logger.debug("getWindowsProcessId ---- line >> " + line);
					String[] tmp = line.split("\\s{2,}");
					if (tmp == null)
					{
						continue;
					}
					for (int i = 0; i < tmp.length; i++)
					{
						if (tmp[i].matches("\\d+"))
						{
							processIDList.add(tmp[i]);
						}
					}
				}
				while ((line = errorReader.readLine()) != null)
				{
					logger.debug("getWindowsProcessId error line--->" + line);
				}
			}
			
		} catch (IOException e)
		{
			logger.error(Utils.printExceptionStack(e));
			return null;
		} finally
		{
			try
			{
				if (bReader != null)
				{
					bReader.close();
				}
				if (errorReader != null)
				{
					errorReader.close();
				}
				if (process != null)
				{
					process.destroy();
				}
			} catch (IOException e)
			{
				logger.error(Utils.printExceptionStack(e));
			}
		}
		
		return processIDList;
	}
	
	/**
	 * Linux下根据关键字查找进程,关键字不区分大小写
	 * 
	 * @param procSearchKey
	 * @return
	 */
	public static List<String> getLinuxProcessId(String procSearchKey)
	{
		String cmd = "ps -ef | grep " + procSearchKey.trim() + " | grep -v grep | awk '{print $2}'";
		logger.info("getLinuxProcessId-----" + cmd);
		String[] shellCmd1 = new String[] { "/bin/bash", "-c", cmd };
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		List<String> processIDList = null;
		synchronized (oLinux)
		{
			try
			{
				// 找到根据进程名获取到的进程号列表
				process = Runtime.getRuntime().exec(shellCmd1);
				process.getOutputStream().close();
				
				bReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
				String line = null;
				processIDList = new ArrayList<String>();
				while ((line = bReader.readLine()) != null)
				{
					processIDList.add(line);
					logger.debug("getLinuxProcessId ---- line >> " + line);
				}
				while ((line = errorReader.readLine()) != null)
				{
					logger.debug("getLinuxProcessId error line--->" + line);
				}
			} catch (IOException e)
			{
				logger.error(Utils.printExceptionStack(e));
			} finally
			{
				try
				{
					if (bReader != null)
					{
						bReader.close();
					}
					if (errorReader != null)
					{
						errorReader.close();
					}
					if (process != null)
					{
						process.destroy();
					}
				} catch (IOException e)
				{
					logger.error(Utils.printExceptionStack(e));
				}
			}
			
		}
		return processIDList;
	}
	
	/**
	 * 检查PID是否存在,存在返回PID,不存在返回描述信息
	 * 检查逻辑:先检查PID文件,取出PID,验证PID指定进程是否存在,不存在再使用搜索关键字查找进程 isExistFlag: 0 进程不存在,1
	 * 进程存在且仅找到一个,2 进程存在且找到多个
	 * 
	 * @return 数组:{进程是否存在的标识(0|1|2), 进程PID或者描述信息}
	 */
	public static Object[] checkPidAndGetPid(String pidFile, String procSearchKey) throws Exception
	{
		int isExistFlag = 0;
		String pidInfo = "";
		if (pidFile != null && !"".equals(pidFile))
		{
			File file = new File(pidFile);
			if (file.exists())
			{
				String[] pidArr = ProcessUtil.getProcessIdByFile(file);
				if (pidArr != null && pidArr.length > 0)
				{// 目前考虑只有一个PID的情况
					boolean isExist = ProcessUtil.isProcessExistByPid(pidArr[0]);
					if (isExist)
					{
						pidInfo = pidArr[0];
						isExistFlag = 1;
					} else
					{
//						pidInfo = "进程PID\"" + pidArr[0] + "\"不存在";
						pidInfo = "i18n_client.ProcessUtil.processPid_n81i\"" + pidArr[0] + "\"i18n_client.ProcessUtil.notExists_n81i";
					}
				}
			} else
			{
//				pidInfo = "PID文件\"" + file.getAbsolutePath() + "\"不存在";
				pidInfo = "i18n_client.ProcessUtil.pidFile_n81i\"" + file.getAbsolutePath() + "\"i18n_client.ProcessUtil.notExists_n81i";
			}
		} else
		{
//			pidInfo = "PID文件字段为空";
			pidInfo = "i18n_client.ProcessUtil.pidFieldNull_n81i";
		}
		
		if (isExistFlag == 0 && procSearchKey != null && !"".equals(procSearchKey))
		{
			// PID文件或PID文件中的PID不存在,则使用进程搜索关键字查找PID
			List<String> pidList = ProcessUtil.getProcessIdBySearchKey(procSearchKey);
			if (pidList == null || pidList.size() == 0)
			{
//				pidInfo += (pidInfo.length() > 0 ? ", " : "") + "进程搜索关键字" + procSearchKey + "未找到进程";
				pidInfo += (pidInfo.length() > 0 ? ", " : "") + "i18n_client.ProcessUtil.searchKey_n81i" + procSearchKey + "i18n_client.ProcessUtil.noProcess_n81i";
			} else if (pidList.size() > 1)
			{
				pidInfo += (pidInfo.length() > 0 ? ", " : "") + "i18n_client.ProcessUtil.searchKey_n81i" + procSearchKey
						+ " i18n_client.ProcessUtil.findTooMuch_n81i";
				isExistFlag = 2;
			} else
			{// 只找到一个进程
				pidInfo = pidList.get(0);
				isExistFlag = 1;
			}
		}
		
		return new Object[] { isExistFlag, pidInfo };
	}
	
	/*
	 * public static String getProcessId(String processName, String processPath)
	 * throws Exception{ String value = null; //根据操作系统确定获取进程ID的方式 String os =
	 * System.getProperty("os.name"); if (os.startsWith("Windows")) { value =
	 * getWindowsProcessId(processName, processPath); }else if
	 * (os.startsWith("Linux")){ value = getLinuxProcessId(processName,
	 * processPath); } else { throw new IOException("unknown operating system: " +
	 * os); }
	 * 
	 * return value; }
	 * 
	 * public static String getWindowsProcessId(String procName, String
	 * procPath) { String[] cmd = new String[] { "cmd.exe", "/C", "wmic process
	 * where \"name='" + procName.trim() + "' and executablepath='" +
	 * procPath.trim().replace("\\", "\\\\") + "'\" get processid" };// list
	 * full logger.debug("cmd-----"+cmd[2]); BufferedReader bReader = null;
	 * Process process = null; String processId = null; try { synchronized
	 * (oWin) { process = Runtime.getRuntime().exec(cmd);
	 * process.getOutputStream().close(); bReader = new BufferedReader(new
	 * InputStreamReader(process .getInputStream())); String line = null; while
	 * ((line = bReader.readLine()) != null) { logger.debug("line-----" + line);
	 * if (line.trim().matches("\\d+")) { processId = line.trim(); } } } } catch
	 * (IOException e) { logger.error(Utils.printExceptionStack(e)); return
	 * processId; }finally{ try { if (bReader != null) { bReader.close(); } if
	 * (process != null) { process.destroy(); } } catch (IOException e) {
	 * logger.error(Utils.printExceptionStack(e)); } }
	 * 
	 * return processId; }
	 * 
	 * public static String getLinuxProcessId(String procName, String procPath) {
	 * String cmd = "ps -ef | grep '" + procName.trim() + "' | grep -v grep |
	 * awk '{print $2}'"; String[] shellCmd1 = new String[] { "/bin/bash", "-c",
	 * cmd }; String[] shellCmd2 = new String[] { "/bin/bash", "-c", cmd };
	 * BufferedReader bReader = null; List<String> processIDList = null;
	 * Process process = null; synchronized (oLinux) { try { // 找到根据进程名获取到的进程号列表
	 * process = Runtime.getRuntime().exec(shellCmd1);
	 * process.getOutputStream().close();
	 * 
	 * bReader = new BufferedReader(new InputStreamReader(process
	 * .getInputStream())); String line = null; processIDList = new ArrayList<String>();
	 * while ((line = bReader.readLine()) != null) { processIDList.add(line); } }
	 * catch (IOException e) { logger.error(Utils.printExceptionStack(e)); }
	 * finally { try { if (bReader != null) { bReader.close(); } if (process !=
	 * null) { process.destroy(); } } catch (IOException e) {
	 * logger.error(Utils.printExceptionStack(e)); } }
	 * 
	 * for (int i = 0; i < processIDList.size(); i++) { shellCmd2 = new String[] {
	 * "/bin/bash", "-c", "lsof -p " + processIDList.get(i) + " | grep 'txt'
	 * |grep -v grep | awk '{print $NF}'" }; try { process =
	 * Runtime.getRuntime().exec(shellCmd2); process.getOutputStream().close();
	 * bReader = new BufferedReader(new InputStreamReader(process
	 * .getInputStream())); String line = null; while ((line =
	 * bReader.readLine()) != null) { if (line.trim().equals(procPath.trim()))
	 * return processIDList.get(i); } } catch (IOException e) {
	 * logger.error(Utils.printExceptionStack(e)); } finally { try { if (bReader !=
	 * null) { bReader.close(); } if (process != null) { process.destroy(); } }
	 * catch (IOException e) { logger.error(Utils.printExceptionStack(e)); } }
	 * }//for end } return null; }
	 */

}