PHP script SSH commands

Suite à un désespoir aujourd’hui, à cause d’un contrôleur WiFi CISCO qui déraille mais également d’un besoin d’envoyer des commandes sur l’ensemble de notre parc de bornes WiFi, j’ai développé un script qui permet d’envoyer des commandes à un ensemble d’équipements réseau (sous réserve d’avoir les mêmes logins partout).

Le script lit 2 fichiers:

  • Liste des adresses des équipements (adresse IPv4)
  • Liste des commandes à exécuter (dans l’ordre)

Ensuite pour chaque équipement il va exécuter les commandes spécifiées.

Prérequis

  • php5
  • libssh2

Le script (licence BSD)

<?php
/* Copyright (c) 2013, Loïc Blot
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1\. Redistributions of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
* 2\. Redistributions in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
*/
    function printErr($output) {
        echo "Erreur: ".$output."\n";
    }

    function printInfo($output) {
        echo "Info: ".$output."\n";
    }

    function connectToDevice($device,$sshuser,$sshpwd,$enablepwd) {
        global $conn;
        $conn = ssh2_connect($device,22);
        if(!$conn)
            return -1;

        if(!ssh2_auth_password($conn, $sshuser, $sshpwd))
            return -2;

        $stdio = @ssh2_shell($conn,"xterm");
        fwrite($stdio,"enable\n");
        usleep(250000);
        while($line = fgets($stdio)) {}

        fwrite($stdio,$enablepwd."\n");
        usleep(250000);
        while($line = fgets($stdio)) {
            if($line == "% Access denied\r\n")
                               return -3;
               }
        return $stdio;
    }

    function sendSSHCmd($stdio, $cmd) {
        $output = "";
        $output_arr = array();
        $promptfind = false;

        fwrite($stdio,$cmd."\n");
        $matches = array();
        while(!$promptfind) {
            while($line = fgets($stdio)) {
                if(preg_match("#--More--#",$line))
                    fwrite($stdio," ");
                else if(preg_match("/^(.+)[#]$/",$line,$matches))
                    $promptfind = true;
                else array_push($output_arr,$line);
            }
        }

        for($i=0;$i<count($output_arr)-2;$i++) {
            $output .= $output_arr[$i];
        }
        return $output;
    }

    function readCmdFile($file) {
        global $cmdfilebuf;
        $cmdfilebuf = file($file);
        if(!$cmdfilebuf) return false;
        return true;
    }

    function readDevAndExec($file) {
        global $sshuser,$sshpwd,$enablepwd,$cmdfilebuf;

        $devfilebuf = file($file);
        if($devfilebuf == false) {
            printErr("Impossible de lire le fichier '".$file."'");
            return false;
        }

        for($i=0;$i<count($devfilebuf);$i++) {
            if(!preg_match("#^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$#",$devfilebuf[$i])) {
                printErr("L'IP '".$devfilebuf[$i]."' n'est pas valide");
                return false;
            }
        }

        $cmds="";
        for($i=0;$i<count($cmdfilebuf);$i++)
            $cmds .= $cmdfilebuf[$i];
        printInfo("Le fichier suivant va etre envoye aux peripheriques:\n--------------------------------------\n".$cmds."--------------------------------------");

        for($i=0;$i<count($devfilebuf);$i++) {
            $host = substr($devfilebuf[$i],0,-1);
            printInfo("Connexion a '".$host."'");
            $out = "";
            $stdio = connectToDevice($host,$sshuser,$sshpwd,$enablepwd);
            switch($stdio) {
                case -1: printErr("SSH conn failed"); break;
                case -2: printErr("SSH auth failed"); break;
                case -3: printErr("Enable auth failed"); break;
                case false: printErr("Steam failed"); break;
                default:
                    for($j=0;$j<count($cmdfilebuf);$j++) {
                        sendSSHCmd($stdio,$cmdfilebuf[$j])."\n";
                    }
                    break;
            }
        }
        return true;
    }

    /*
    * Main
    */

    $conn = NULL;
    $cmdfilebuf = NULL;

    if(count($argv) != 6) {
        if(count($argv) < 6)
            printErr("Il manque des arguments\nSyntaxe: program <sshuser> <sshpwd> <enablepwd> <devfile> <cmdfile>");
        else
            printErr("Il y a trop d'arguments\nSyntaxe: program <sshuser> <sshpwd> <enablepwd> <devfile> <cmdfile>");
        return;
    }

    $sshuser = $argv[1];
    $sshpwd = $argv[2];
    $enablepwd = $argv[3];    
    $devfile = $argv[4];
    $cmdfile = $argv[5];

    if(!readCmdFile($cmdfile)) {
        printErr("Impossible de lire le fichier '".$cmdfile."'");
        return;
    }

    readDevAndExec($devfile);    
?>

A vous de jouer, n’hésitez pas à rajouter des options des améliorations et à le partager !