JSch - Examples - Exec.java

/**
 * 利用JSch包實現遠程主機SHELL命令執行
 * @param ip 主機IP
 * @param user 主機登陸用戶名
 * @param psw  主機登陸密碼
 * @param port 主機ssh2登陸端口,如果取默認值,傳-1
 * @param privateKey 密鑰文件路徑
 * @param passphrase 密鑰的密碼
 */
public static void sshShell(String ip, String user, String psw
,int port ,String privateKey ,String passphrase) throws Exception{
Session session = null;
Channel channel = null;



JSch jsch = new JSch();


//設置密鑰和密碼
if (privateKey != null && !"".equals(privateKey)) {
           if (passphrase != null && "".equals(passphrase)) {
            //設置帶口令的密鑰
               jsch.addIdentity(privateKey, passphrase);
           } else {
            //設置不帶口令的密鑰
               jsch.addIdentity(privateKey);
           }
       }

if(port <=0){
//連接服務器,採用默認端口
session = jsch.getSession(user, ip);
}else{
//採用指定的端口連接服務器
session = jsch.getSession(user, ip ,port);
}


//如果服務器連接不上,則拋出異常
if (session == null) {
throw new Exception("session is null");
}

//設置登陸主機的密碼
session.setPassword(psw);//設置密碼   
//設置第一次登陸的時候提示,可選值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
//設置登陸超時時間   
session.connect(30000);

try {
//創建sftp通信通道
channel = (Channel) session.openChannel("shell");
channel.connect(1000);


//獲取輸入流和輸出流
InputStream instream = channel.getInputStream();
OutputStream outstream = channel.getOutputStream();

//發送需要執行的SHELL命令,需要用\n結尾,表示回車
String shellCommand = "ls \n";
outstream.write(shellCommand.getBytes());
outstream.flush();




//獲取命令執行的結果
if (instream.available() > 0) {
byte[] data = new byte[instream.available()];
int nLen = instream.read(data);

if (nLen < 0) {
throw new Exception("network error.");
}

//轉換輸出結果並打印出來
String temp = new String(data, 0, nLen,"iso8859-1");
System.out.println(temp);
}
   outstream.close();
   instream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
channel.disconnect();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章