有時候你可能需要通過代碼來控制執(zhí)行l(wèi)inux命令實現(xiàn)某些功能。
針對這類問題可以使用JSCH來實現(xiàn),具體代碼如下:
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
|
public class CogradientImgFileManager{ private static final Logger log = LoggerFactory.getLogger(CogradientImgFileManager. class ); private static ChannelExec channelExec; private static Session session = null ; private static int timeout = 60000 ; // 測試代碼 public static void main(String[] args){ try { versouSshUtil( "10.8.12.189" , "jmuser" , "root1234" , 22 ); runCmd( "java -version" , "UTF-8" ); } catch (Exception e){ // TODO Auto-generated catch block e.printStackTrace(); } } /** * 連接遠(yuǎn)程服務(wù)器 * @param host ip地址 * @param userName 登錄名 * @param password 密碼 * @param port 端口 * @throws Exception */ public static void versouSshUtil(String host,String userName,String password, int port) throws Exception{ log.info( "嘗試連接到....host:" + host + ",username:" + userName + ",password:" + password + ",port:" + port); JSch jsch = new JSch(); // 創(chuàng)建JSch對象 session = jsch.getSession(userName, host, port); // 根據(jù)用戶名,主機(jī)ip,端口獲取一個Session對象 session.setPassword(password); // 設(shè)置密碼 Properties config = new Properties(); config.put( "StrictHostKeyChecking" , "no" ); session.setConfig(config); // 為Session對象設(shè)置properties session.setTimeout(timeout); // 設(shè)置timeout時間 session.connect(); // 通過Session建立鏈接 } /** * 在遠(yuǎn)程服務(wù)器上執(zhí)行命令 * @param cmd 要執(zhí)行的命令字符串 * @param charset 編碼 * @throws Exception */ public static void runCmd(String cmd,String charset) throws Exception{ channelExec = (ChannelExec) session.openChannel( "exec" ); channelExec.setCommand(cmd); channelExec.setInputStream( null ); channelExec.setErrStream(System.err); channelExec.connect(); InputStream in = channelExec.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in, Charset.forName(charset))); String buf = null ; while ((buf = reader.readLine()) != null ){ System.out.println(buf); } reader.close(); channelExec.disconnect(); } } |