Salut,
+1 pour le SSH
Si tu utilises cette librairie: JSCH (examples)
Tu pourras faire ce que tu veux.
Exemple simpliste:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class TestSsh {
public static void main(String[] args) {
try {
String result = execSsh("adress_ip_ou_hostname", 22, "username", "userpassword", "ls -als /", false);
System.out.println("Result: " + result);
result = execSsh("adress_ip_ou_hostname", 22, "username", "userpassword", "ls -als /root", true);
System.out.println("Result: " + result);
} catch(JSchException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
public static String execSsh(String host, int port, String username, String userpassword, String command, boolean useSudo) throws JSchException, IOException {
/* Désactivation de la vérification stricte de clé d'hôte. */
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
/* Configuration de la lib. */
JSch jsch = new JSch();
Session session=jsch.getSession(username, host, port);
session.setPassword(userpassword);
session.setConfig(config);
session.connect();
/* Préparation du channel à utiliser (en mode exec). */
ChannelExec channel= (ChannelExec)session.openChannel("exec");
/* En prévision d'un "oui mais comment qu'on fait avec sudo..." */
// prépare la commande à exécuter. */
channel.setCommand((useSudo ? "sudo -S -p '' " : "") + command);
channel.setInputStream(null);
channel.setErrStream(null);
/* Si sudo est requis */
OutputStream out = useSudo ? channel.getOutputStream() : null;
InputStream in=channel.getInputStream();
/* ouverture de la connexion. */
channel.connect();
/* on passe le mot de passe à sudo (si besoin). */
if(out != null) {
out.write((userpassword+"\n").getBytes());
out.flush();
}
/* lecture de la réponse */
final StringBuilder sb = new StringBuilder();
byte[] tmp=new byte[1024];
for(;;){
while(in.available() > 0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
sb.append(new String(tmp, 0, i));
}
if(channel.isClosed()){
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
/* libération des ressources. */
if(out != null) out.close();
if(in != null) in.close();
channel.disconnect();
session.disconnect();
/* Retourne la réponse */
return sb.toString();
}
}
9 déc. 2015 à 13:47