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
|
public class Monitoring{
public void Monitoring (){
try{
JSch jsch=new JSch();
String host=null;
// connexion ssh avec le nom d'utilisateur et l'@
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session sessionssh=jsch.getSession(user, host, 22);
// Nom utilisateur + mote de passe
UserInfo ui=new MyUserInfo();
sessionssh.setUserInfo(ui); // récupération des informations utilisateur de la session
sessionssh.connect();
// exécution des différentes coammandes
executeCmd("fichierCPU.txt", "sar -uq 1 5 | grep \"Average\" | tr -s \" \"",sessionssh);
executeCmd("fichierMem.txt", "vmstat 1 1",sessionssh);
executeCmd("fichierIO.txt", "iostat -xcnCXTdz",sessionssh);
executeCmd("fichierNet.txt", "netstat -i",sessionssh);
sessionssh.disconnect(); // deconnexion de la session ssh
}
catch(JSchException | IOException e){
System.out.println(e);
}
}
private void executeCmd(String urlFich, String cmd, Session sessionssh) throws JSchException, FileNotFoundException, IOException{
Channel channelssh = sessionssh.openChannel("exec");
((ChannelExec)channelssh).setCommand(cmd);
channelssh.setInputStream(null);
try (FileOutputStream fos = new FileOutputStream(new File(urlFich))) {
((ChannelExec)channelssh).setErrStream(System.err);
InputStream in=channelssh.getInputStream();
channelssh.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
fos.write(((new String(tmp, 0, i)).getBytes()));
System.out.print(new String(tmp, 0, i));
}
if(channelssh.isClosed()){
System.out.println("exit-status: "+channelssh.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channelssh.disconnect();
}
} |
Partager