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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.