Java遠程執行Linux命令
//指明連接主機的IP地址
Connection conn = new Connection(hostname);
Session ssh = null;
try {
//連接到主機
conn.connect();
//使用用戶名和密碼校驗
boolean isconn = conn.authenticateWithPassword(username, password);
if(!isconn){
System.out.println("用戶名稱或者是密碼不正確");
}else{
System.out.println("已經連接OK");
ssh = conn.openSession();
ssh.execCommand(command);
InputStream is = new StreamGobbler(ssh.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is));
while(true){
String line = brs.readLine();
if(line==null){
break;
}
System.out.println(line);
}
}
//連接的Session和Connection對象都需要關閉
ssh.close();
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = new Connection(hostname);
Session ssh = null;
try {
//連接到主機
conn.connect();
//使用用戶名和密碼校驗
boolean isconn = conn.authenticateWithPassword(username, password);
if(!isconn){
System.out.println("用戶名稱或者是密碼不正確");
}else{
System.out.println("已經連接OK");
ssh = conn.openSession();
ssh.execCommand(command);
InputStream is = new StreamGobbler(ssh.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is));
while(true){
String line = brs.readLine();
if(line==null){
break;
}
System.out.println(line);
}
}
//連接的Session和Connection對象都需要關閉
ssh.close();
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.