Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!

PHPSSH

PHP SSH2 Bindings

PHP can use the bindings to the  libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.   I documented some code snippets for future reference.

You can use ssh keys but for simplicity here making the call with a password:

$conn_id = ssh2_connect('server', 22);
ssh2_auth_password($conn_id, 'user', 'pwd');

echo("SOLARIS SERVER SNAPSHOTS - CREATION);
$stream=ssh2_exec($conn_id,"/usr/sbin/zfs list -t snapshot -o name,creation | grep $share | grep -v tank");
$outS="";
stream_set_blocking($stream, true);
while($o=fgets($stream)){
$outS = $outS . $o;
}
fclose($stream);
print_snaps_sorted($outS);

Slightly more complicated to make up the built-in javascript "command" you are passing when using a ZFS appliance. 

$chk_snaps_cmd="
run('select DBF');
run('snapshots');
snapshots = list();
for (i = 0; i < snapshots.length; i++) {
run('select ' + snapshots[i]);
creation = run('get creation');
printf('%s %s', snapshots[i],creation);
run('cd ..');
}";

$share = $_GET['share'];
$conn_id = ssh2_connect('server', 22);
ssh2_auth_password($conn_id, 'user', 'pwd');
echo('ZFS STORAGE APPLIANCE SNAPSHOTS - CREATION');
$stream=ssh2_exec($conn_id,"script run('shares select $share');" . $chk_snaps_cmd);
stream_set_blocking($stream, true);
while($o=fgets($stream)){
  $outS = $outS . $o;
}
fclose($stream);
print_snaps_sorted($outS);

Note:  I had an issues using ssh calls not returning results when using a non-privileged user whereas a root user worked.   Thanks Matt M for pointing out the obvious.  I needed to use the full path to the binary in this case /usr/sbin/zfs so most likely some path issue in the user shell.

admin

Bio Info for Riaan