--- alx-src/branches/alx-web-060/include/common-functions.php 2011/05/09 22:13:37 2022
+++ alx-src/branches/alx-web-060/include/common-functions.php 2011/06/07 13:10:02 2194
@@ -1,44 +1,78 @@
- include("config.inc.php");
+include('config.inc.php');
+include('ppping.inc.php');
- function exec_on_client($serial, $ip, $cmd, $failure=1, $verbose=0)
- {
- global $pingcmd;
- global $sshcmd;
+function sshdo($cmd, $ip, $user="root")
+{
+ global $privkey_file;
+ global $pubkey_file;
+
+ if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist. You must install the ssh2 module from pecl library!");
- $pubkey = mysql_query('select public_key from ssh_auth_clients where serial='.$serial.'');
- while ($row = mysql_fetch_row ($pubkey))
+ if(!($con = ssh2_connect($ip, "22")))
+ {
+ echo "failure, could not connect\n";
+ }
+ else
+ {
+ if(!ssh2_auth_pubkey_file($con, $user, $pubkey_file, $privkey_file))
{
- # write known hosts
- $hostfile = fopen ($home."/.ssh/known_hosts","w");
- fwrite($hostfile,$ip." ".$row[0],strlen($row[0])+strlen($ip)+1);
- fclose($hostfile);
-
- # check if the client is online
- passthru($pingcmd.' '.$ip.' &> /dev/null && exit 0 || exit 1', $retval);
- if ($retval == 0)
- {
- if ($verbose == 1) echo "sshcmd: '".$sshcmd."'
";
+ echo "failure, could not login\n";
+ }
+ else
+ {
+ echo "logged in\n";
- # exec the cmd
- exec($sshcmd.' '.$ip.' "source /etc/profile;'.$cmd.'"', $cmdout, $err);
- if ($verbose == 1)
+ if(!($stream = ssh2_exec($con, "source /etc/profile; ".$cmd."; echo '__RETVAL__:'$?")))
+ {
+ echo "failure, could not execute command '".$cmd."'\n";
+ }
+ else
+ {
+ // collect stream data
+ stream_set_blocking($stream, true);
+ $data = "";
+ while ($buf = fread($stream,4096))
{
- echo "err: '".$err."'
";
- foreach( $cmdout as $i )
- {
- echo "cmdout: '".$i."'
";
- }
+ $data .= $buf;
+ echo "buf=" .$buf."\n";
}
-
- if($err != 0) if ($failure == 1) echo '';
- else if ($verbose == 1) echo '';
+ fclose($stream);
+ # get the last element of data as retval
+ $retval = explode('__RETVAL__:', trim($data));
}
- else if ($failure == 1) echo '';
}
-
- # return the output of $cmd
- return $cmdout;
}
+ // return an array -> 0=retval, 1=data
+ return array($retval[1], $retval[0]);
+}
+
+function ssh_editvar($var, $value, $file)
+{
+ global $ip;
+
+ // sed cmd: ssh -l root 10.11.12.13 'sed -i -e "s|^\(VAR=\).*|\1\"VALUE\"| FILE'
+ sshdo('if [[ ! -z $(grep "^'.$var.'=" '.file.') ]]; then sed -i -e "s|^\('.$var.'=\).*|\1\"'.$value.'\"|" '.$file. 'else echo "'.$var.'=\"'.$value.'\"" >> '.file, $ip);
+}
+
+function online($ip)
+{
+ $ping = new PPPing();
+ $ping->hostname = $ip;
+ $ping->timeout = "0.3";
+ $result = $ping->Ping();
+
+ if($result<0)
+ {
+ echo "error: ".$ping->strError($result);
+ $retval=1;
+ }
+ else
+ {
+ echo $result." ms";
+ $retval=0;
+ }
+ return $retval;
+}
?>