I have a shop having about 10 Macs. Current I am able to shutdown/restart them remotely through PHP SSH2 function using this code
<?php
include('Net/SSH2.php');
$server = "hostname";
$username = "user";
$password = "pwd";
$command = "sudo shutdown -r now";
$ssh = new Net_SSH2($server);
if (!$ssh->login($username, $password)) {
exit('Login Failed');
}
echo $ssh->exec($command);
echo "Sucessfully Restarted blah blah blah";
?>
But in order to shutdown/restart 10 of the terminals, I have to run 10 different script to achieve that. Is there any methods where I can connect to multiple server and run the same command?
You could store the hostnames and credentials in a multi-dimensional array. This will allow you to iterate through each item using foreach and execute the required command on each host. Here's an example of what you'd need to do:
<?php
include('Net/SSH2.php');
$hosts = array(
array(
'hostname' => 'hostname1',
'username' => 'user1',
'password' => 'pwd1'
),
array(
'hostname' => 'hostname2',
'username' => 'user2',
'password' => 'pwd2'
)
);
$command = "sudo shutdown -r now";
foreach ($hosts as $host) {
$ssh = new Net_SSH2($host['hostname']);
if (!$ssh->login($host['username'], $host['password'])) {
echo "Login Failed for host '{$host['hostname']}'\n";
continue;
}
echo $ssh->exec($command);
echo "Sucessfully Restarted {$host['hostname']}\n";
}
Hope this helps.
On security: It's recommended you use SSH keys rather than usernames and passwords. Also, make sure you keep the macs on a network that is not open, for example, to customers, you should use a private network.