/** * */ public function close() { $this->ssh->disconnect(); }
/** * Write a config snippet to to a device using SSH */ public function writeSnippetSSH($snippetArr, $prompt) { $log = ADLog::getInstance(); if (!($ssh = new Net_SSH2($this->_hostname, 22, $this->_timeout))) { $output = "Failure: Unable to connect to {$this->_hostname}\n"; $log->Conn("Failure: Unable to connect to " . $this->_hostname . " - (File: " . $_SERVER['PHP_SELF'] . ")"); return false; } if (!$ssh->login($this->_username, $this->_password)) { $output = "Error: Authentication Failed for {$this->_hostname}\n"; $log->Conn("Error: Authentication Failed for {$this->_hostname} (File: " . $_SERVER['PHP_SELF'] . ")"); return false; } $output = ''; if ($this->_enableMode === 'on') { // $ssh->write("\n"); // 1st linebreak after above prompt check $ssh->read('/.*>/', NET_SSH2_READ_REGEX); // read out to '>' $ssh->write("enable\n"); $ssh->read('/.*:/', NET_SSH2_READ_REGEX); $ssh->write($this->_enableModePassword . "\n"); $ssh->read('/' . $prompt . '/', NET_SSH2_READ_REGEX); foreach ($snippetArr as $key => $command) { $ssh->write($command . "\n"); $output .= $ssh->read('/.*#/', NET_SSH2_READ_REGEX); // read out to '#' } $ssh->write("\n"); // to line break after command output $ssh->read('/' . $prompt . '/', NET_SSH2_READ_REGEX); } else { // $ssh->write("\n"); // 1st linebreak after above prompt check $ssh->read('/' . $prompt . '/', NET_SSH2_READ_REGEX); foreach ($snippetArr as $key => $command) { $ssh->write($command . "\n"); $output .= $ssh->read('/.*#/', NET_SSH2_READ_REGEX); // read out to '#' because the prompt will change depending on the deployed config } $ssh->write("\n"); // to line break after command output $ssh->read('/' . $prompt . '/', NET_SSH2_READ_REGEX); } $ssh->disconnect(); return $output; }
public function detectRemoteUserId($repoObject) { $host = $repoObject->getOption("SFTP_HOST"); $port = $repoObject->getOption("SFTP_PORT"); $credentials = AJXP_Safe::tryLoadingCredentialsFromSources(NULL, $repoObject); $user = $credentials["user"]; $pass = $credentials["password"]; $ssh2 = new Net_SSH2($host, $port); if ($ssh2->login($user, $pass)) { $output = $ssh2->exec('id'); $ssh2->disconnect(); if (trim($output != "")) { $res = sscanf($output, "uid=%i(%s) gid=%i(%s) groups=%i(%s)"); preg_match_all("/(\\w*)=(\\w*)\\((\\w*)\\)/", $output, $matches); if (count($matches[0]) == 3) { $uid = $matches[2][0]; $gid = $matches[2][1]; return array($uid, $gid); } } } unset($ssh2); return array(null, null); }
} unset($servers); //------------------------------------------------------------------------------------------------------------+ //Data $boxCache = array($rowsBoxes['boxid'] => array('players' => array('players' => $p), 'bandwidth' => array('rx_usage' => $bandwidth_rx_usage, 'tx_usage' => $bandwidth_tx_usage, 'rx_total' => $bandwidth_rx_total, 'tx_total' => $bandwidth_tx_total), 'cpu' => array('proc' => $cpu_proc, 'cores' => $cpu_cores, 'usage' => $cpu_usage), 'ram' => array('total' => $ram_total, 'used' => $ram_used, 'free' => $ram_free, 'usage' => $ram_usage), 'loadavg' => array('loadavg' => $loadavg), 'hostname' => array('hostname' => $hostname), 'os' => array('os' => $os), 'date' => array('date' => $date), 'kernel' => array('kernel' => $kernel), 'arch' => array('arch' => $arch), 'uptime' => array('uptime' => $uptime), 'swap' => array('total' => $swap_total, 'used' => $swap_used, 'free' => $swap_free, 'usage' => $swap_usage), 'hdd' => array('total' => $hdd_total, 'used' => $hdd_used, 'free' => $hdd_free, 'usage' => $hdd_usage))); unset($p, $bandwidth_rx_total, $bandwidth_tx_total, $bandwidth_rx_usage, $bandwidth_tx_usage, $cpu_proc, $cpu_cores, $cpu_usage); unset($ram_used, $ram_free, $ram_total, $ram_usage, $loadavg, $hostname, $os, $date, $kernel, $arch, $uptime); unset($swap_used, $swap_free, $swap_total, $swap_usage, $hdd_total, $hdd_used, $hdd_free, $hdd_usage); //------------------------------------------------------------------------------------------------------------+ //Update DB for the current box query_basic("UPDATE `" . DBPREFIX . "box` SET\n\t\t\t\t`cache` = '" . mysql_real_escape_string(gzcompress(serialize($boxCache), 2)) . "' WHERE `boxid` = '" . $rowsBoxes['boxid'] . "'"); $boxData = $boxData + $boxCache; unset($boxCache); } usleep(2000); $ssh->disconnect(); } unset($boxes); //------------------------------------------------------------------------------------------------------------+ //Update dataBox table query_basic("INSERT INTO `" . DBPREFIX . "boxData` SET\n\t`timestamp` = '" . time() . "',\n\t`cache` = '" . mysql_real_escape_string(gzcompress(serialize($boxData), 2)) . "'"); unset($boxData); } //------------------------------------------------------------------------------------------------------------+ //------------------------------------------------------------------------------------------------------------+ /** * '*Data' table operations */ //---------------------------------------------------------+ // Remove old data $time = time() - (60 * 60 * 24 * 7 * 4 * 3 + 3600);
/** * Aktuellen Status des Devices ermitteln und, wenn verbunden, abfragen.. * * @return boolean */ public function RequestState() { if ($this->Init() === false) { return false; } set_include_path(__DIR__); require_once __DIR__ . '/Net/SSH2.php'; $ssh = new Net_SSH2($this->ReadPropertyString("Address")); $login = @$ssh->login('root', $this->ReadPropertyString("Password")); if ($login == false) { trigger_error('Could not log in on SqueezeBox', E_USER_NOTICE); return false; } $PowerMode = (int) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/power_mode"); $this->SetValueInteger('State', $PowerMode); if ($PowerMode == 5) { $this->SetValueFloat("WallVoltage", 0); } else { $WallVoltage = round((int) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/wall_voltage") / 1000, 1); $this->SetValueFloat("WallVoltage", $WallVoltage); } $SysVoltage = round((double) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/sys_voltage") / 1000, 1); $this->SetValueFloat('SysVoltage', $SysVoltage); $ChargeState = (int) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/charger_state"); $this->SetValueInteger('ChargeState', $ChargeState); if ($ChargeState != 1) { $BatteryLevel = (int) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_charge") / 2000; $this->SetValueFloat('BatteryLevel', $BatteryLevel); $BatteryCapacity = (int) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_capacity"); $this->SetValueInteger('BatteryCapacity', $BatteryCapacity); $BatteryTemperature = round((double) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_temperature") / 32, 1); $this->SetValueFloat('BatteryTemperature', $BatteryTemperature); $BatteryVoltage = round((double) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_voltage") / 1000, 1); $this->SetValueFloat('BatteryVoltage', $BatteryVoltage); $BatteryVMon1 = round((double) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_vmon1_voltage") / 1000, 1); $this->SetValueFloat('BatteryVMon1', $BatteryVMon1); $BatteryVMon2 = round((double) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_vmon2_voltage") / 1000, 1); $this->SetValueFloat('BatteryVMon2', $BatteryVMon2); //var_dump($ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/charger_event")); // $BatteryChargeRate = (int) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_charge_rate"); // $this->SetValueInteger('BatteryChargeRate', $BatteryChargeRate); // $BatteryDischargeRate = (int) $ssh->exec("cat /sys/class/i2c-adapter/i2c-1/1-0010/battery_discharge_rate"); // $this->SetValueInteger('BatteryDischargeRate', $BatteryDischargeRate); } else { $this->SetValueFloat('BatteryLevel', 0.0); $this->SetValueInteger('BatteryCapacity', 0); $this->SetValueFloat('BatteryTemperature', 0.0); $this->SetValueFloat('BatteryVoltage', 0.0); $this->SetValueFloat('BatteryVMon1', 0.0); $this->SetValueFloat('BatteryVMon2', 0.0); // $this->SetValueInteger('BatteryChargeRate', 0); // $this->SetValueInteger('BatteryDischargeRate', 0); } $ssh->disconnect(); return true; }
/** * Add a New Box To The Collection * * @http_method POST * @resource box/ * * @param string $name query * @param string $os query * @param string $ip query * @param string $port query * @param string $login query * @param string $password query * @param optional string $userPath * @param optional string $steamPath * @param optional string $notes * * @return application/json * * @author Nikita Rousseau */ function postBox($name, $os, $ip, $port, $login, $password, $userPath = '', $steamPath = '', $notes = '') { $args = array('name' => $name, 'os' => $os, 'ip' => $ip, 'port' => $port, 'login' => $login, 'password' => $password, 'userPath' => $userPath, 'steamPath' => $steamPath, 'notes' => $notes); $errors = array(); // array to hold validation errors $data = array(); // array to pass back data $dbh = Core_DBH::getDBH(); // Get Database Handle // validate the variables ====================================================== $v = new Valitron\Validator($args); $rules = ['required' => [['name'], ['os'], ['ip'], ['port'], ['login'], ['password']], 'regex' => [['name', "/^([-a-z0-9_ -])+\$/i"]], 'integer' => [['os'], ['port']], 'ip' => [['ip']], 'alphaNum' => [['login']]]; $labels = array('name' => T_('Remote Machine Name'), 'os' => T_('Operating System'), 'ip' => T_('IP Address'), 'port' => T_('Port'), 'login' => T_('Login'), 'password' => T_('Password')); $v->rules($rules); $v->labels($labels); $v->validate(); $errors = $v->errors(); // validate the variables phase 2 ============================================== if (empty($errors)) { // Verify OS ID try { $sth = $dbh->prepare("\n\t\t\t\t\tSELECT operating_system\n\t\t\t\t\tFROM " . DB_PREFIX . "os\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tos_id = :os_id\n\t\t\t\t\t;"); $sth->bindParam(':os_id', $args['os']); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } if (empty($result[0])) { $errors['os'] = 'Bad Identifier'; } // Verify Communication $socket = @fsockopen($args['ip'], $args['port'], $errno, $errstr, 3); if ($socket === FALSE) { $errors['com'] = "Unable to connect to " . $args['ip'] . " on port " . $args['port'] . ". " . utf8_encode($errstr) . " ( {$errno} )"; unset($socket); } else { unset($socket); $ssh = new Net_SSH2($args['ip'], $args['port']); if (!$ssh->login($args['login'], $args['password'])) { $errors['com'] = 'Login failed'; } else { // Verify Remote Paths if (!empty($args['userPath'])) { if (boolval(trim($ssh->exec('test -d ' . escapeshellcmd($args['userPath']) . " && echo '1' || echo '0'"))) === FALSE) { $errors['remoteUserHome'] = 'Invalid path. Must be an absolute or full path'; } } if (!empty($args['steamPath'])) { if (boolval(trim($ssh->exec('test -f ' . escapeshellcmd($args['steamPath']) . " && echo '1' || echo '0'"))) === FALSE) { $errors['steamcmd'] = 'SteamCMD not found. Must be an absolute or full path'; } } } $ssh->disconnect(); } } // Apply ======================================================================= if (empty($errors)) { // // Database update // // Vars Init if (empty($args['userPath'])) { $home = "~"; $args['userPath'] = $home; } else { $home = escapeshellcmd(normalizePath($args['userPath'])); $args['userPath'] = $home; } $config = parse_ini_file(CONF_SECRET_INI); // BOX try { $sth = $dbh->prepare("\n\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box\n\t\t\t\t\tSET\n\t\t\t\t\t\tos_id \t\t\t= :os,\n\t\t\t\t\t\tname \t\t\t= :name,\n\t\t\t\t\t\tsteam_lib_path \t= :steamcmd,\n\t\t\t\t\t\tnotes \t\t\t= :notes\n\t\t\t\t\t;"); $sth->bindParam(':os', $args['os']); $sth->bindParam(':name', $args['name']); $sth->bindParam(':steamcmd', $args['steamPath']); $sth->bindParam(':notes', $args['notes']); $sth->execute(); $box_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } // IP try { $sth = $dbh->prepare("\n\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_ip\n\t\t\t\t\tSET\n\t\t\t\t\t\tbox_id = :box_id,\n\t\t\t\t\t\tip = :ip,\n\t\t\t\t\t\tis_default = 1\n\t\t\t\t\t;"); $sth->bindParam(':box_id', $box_id); $sth->bindParam(':ip', $args['ip']); $sth->execute(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } // CREDENTIALS // Phase 1 // Connect to the remote host // Try to append our public key to authorized_keys $ssh = new Net_SSH2($args['ip'], $args['port']); $ssh->login($args['login'], $args['password']); $remote_keys = $ssh->exec('cat ' . $home . '/.ssh/authorized_keys'); // Check if the public key already exists if (strpos($remote_keys, file_get_contents(RSA_PUBLIC_KEY_FILE)) === FALSE) { // Otherwise, append it $ssh->exec("echo '" . file_get_contents(RSA_PUBLIC_KEY_FILE) . "' >> " . $home . "/.ssh/authorized_keys"); } // Phase 2 // Verify that the public key is allowed on the remote host $isUsingSSHPubKey = TRUE; // By default, we use the SSH authentication keys method $remote_keys = $ssh->exec('cat ' . $home . '/.ssh/authorized_keys'); $ssh->disconnect(); if (strpos($remote_keys, file_get_contents(RSA_PUBLIC_KEY_FILE)) === FALSE) { // authorized_keys is not writable // Use compatibility mode // Store the password in DB $isUsingSSHPubKey = FALSE; } else { // Phase 3 // Try to connect with our private key on the remote host $ssh = new Net_SSH2($args['ip'], $args['port']); $key = new Crypt_RSA(); $key->loadKey(file_get_contents(RSA_PRIVATE_KEY_FILE)); if (!$ssh->login($args['login'], $key)) { // Authentication failed // Use compatibility mode // Store the password in DB $isUsingSSHPubKey = FALSE; } $ssh->disconnect(); } // SSH CREDENTIALS $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB); $cipher->setKeyLength(256); $cipher->setKey($config['APP_SSH_KEY']); if ($isUsingSSHPubKey) { try { $sth = $dbh->prepare("\n\t\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_credential\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tlogin = :login,\n\t\t\t\t\t\t\tremote_user_home = :home,\n\t\t\t\t\t\t\tcom_protocol = 'ssh2',\n\t\t\t\t\t\t\tcom_port = :com_port\n\t\t\t\t\t\t;"); $login = $cipher->encrypt($args['login']); $sth->bindParam(':login', $login); $sth->bindParam(':home', $args['userPath']); $sth->bindParam(':com_port', $args['port']); $sth->execute(); $credential_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } else { try { $sth = $dbh->prepare("\n\t\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_credential\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tlogin = :login,\n\t\t\t\t\t\t\tpassword = :password,\n\t\t\t\t\t\t\tremote_user_home = :home,\n\t\t\t\t\t\t\tcom_protocol = 'ssh2',\n\t\t\t\t\t\t\tcom_port = :port\n\t\t\t\t\t\t;"); $login = $cipher->encrypt($args['login']); $password = $cipher->encrypt($args['password']); $sth->bindParam(':login', $login); $sth->bindParam(':password', $password); $sth->bindParam(':home', $args['userPath']); $sth->bindParam(':com_port', $args['port']); $sth->execute(); $credential_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } // UPDATE BOX try { $sth = $dbh->prepare("\n\t\t\t\t\tUPDATE " . DB_PREFIX . "box\n\t\t\t\t\tSET\n\t\t\t\t\t\tbox_credential_id = :box_credential_id\n\t\t\t\t\tWHERE box_id = :box_id\n\t\t\t\t\t;"); $sth->bindParam(':box_credential_id', $credential_id); $sth->bindParam(':box_id', $box_id); $sth->execute(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } // return a response and log =================================================== $logger = self::getLogger(); $data['errors'] = $errors; if (!empty($data['errors'])) { $data['success'] = false; $logger->info('Failed to add box.'); } else { $data['success'] = true; $logger->info('Box added.'); } return array('response' => 'application/json', 'data' => json_encode($data)); }
function update_firmware() { $ssh = new Net_SSH2('192.168.88.1'); $current_firwmare_version = ''; if ($ssh->login('admin', '')) { $routerboard = $ssh->exec('system resource print'); preg_match_all('/([^:]*?):([^\\r\\n]*)\\r\\n?/', $routerboard, $matches); $output = array_combine(preg_replace('/\\s/', '', $matches[1]), $matches[2]); $current_firmware_version = preg_replace("/[^0-9.]/", "", $output['version']); logthis('current firmware version: ' . $current_firmware_version); $routerboard = $ssh->exec('system routerboard print'); preg_match_all('/([^:]*?):([^\\r\\n]*)\\r\\n?/', $routerboard, $matches); $output = array_combine(preg_replace('/\\s/', '', $matches[1]), $matches[2]); $model = 'RB' . preg_replace("/[^0-9]/", "", $output['model']); $ssh->disconnect(); $files = scandir($GLOBALS['firmware_directory']); $sftp = new Net_SFTP('192.168.88.1'); if (!$sftp->login('admin', '')) { exit('Login Failed'); } $routeros_file_found = 0; foreach ($files as $file) { if (strstr($file, 'routeros-' . $GLOBALS['architecture_types'][$model] . '-')) { $routeros_file_found = 1; $newfw = preg_replace("/.npk/", "", $file); $newfw = preg_replace("/[^0-9.]/", "", $newfw); if ($current_firmware_version != $newfw) { if ($current_firmware_version > $newfw) { logthis('current firmware is newer than ' . $newfw); } else { logthis('new firmware version: ' . $newfw); } } else { logthis('firmware already up to date'); } } } if ($routeros_file_found == 0) { die('no routeros for ' . $GLOBALS['architecture_types'][$model] . ' found.'); } $sftp->pwd(); foreach ($files as $file) { if ($file != '.' && $file != '..') { if (strstr($file, $GLOBALS['architecture_types'][$model]) || strstr($file, $model)) { if (!strstr($file, $current_firmware_version . '-') && !strstr($file, $current_firmware_version . '.npk')) { //append a '-' here also check for npk... logthis('sftping file (not using a password): ' . $file); $sftp->put("{$file}", file_get_contents($GLOBALS['firmware_directory'] . $file)); $ssh->exec(':beep frequency=137 length=2ms;'); } } if (strstr($file, $model)) { $configfile = $file; } } } if (!$configfile) { die('no backup for ' . $model . ' found.'); } $ssh = new Net_SSH2('192.168.88.1'); if ($ssh->login('admin', '')) { $todo = $ssh->exec('system reboot'); logthis($todo); $ssh->disconnect(); logthis('updated firmware (not using a password)'); } return $configfile; } if ($ssh->login('admin', $GLOBALS['admin_password'])) { $routerboard = $ssh->exec('system resource print'); preg_match_all('/([^:]*?):([^\\r\\n]*)\\r\\n?/', $routerboard, $matches); $output = array_combine(preg_replace('/\\s/', '', $matches[1]), $matches[2]); $current_firmware_version = preg_replace("/[^0-9.]/", "", $output['version']); logthis('current firmware version: ' . $current_firmware_version); $routerboard = $ssh->exec('system routerboard print'); preg_match_all('/([^:]*?):([^\\r\\n]*)\\r\\n?/', $routerboard, $matches); $output = array_combine(preg_replace('/\\s/', '', $matches[1]), $matches[2]); $model = 'RB' . preg_replace("/[^0-9]/", "", $output['model']); $ssh->disconnect(); $files = scandir($GLOBALS['firmware_directory']); $sftp = new Net_SFTP('192.168.88.1'); if (!$sftp->login('admin', $GLOBALS['admin_password'])) { exit('Login Failed'); } foreach ($files as $file) { if (strstr($file, 'routeros-' . $GLOBALS['architecture_types'][$model] . '-')) { $routeros_file_found = 1; $newfw = preg_replace("/.npk/", "", $file); $newfw = preg_replace("/[^0-9.]/", "", $newfw); if ($current_firmware_version != $newfw) { if ($current_firmware_version > $newfw) { logthis('current firmware is newer than ' . $newfw); } else { logthis('new firmware version: ' . $newfw); } } else { logthis('firmware already up to date'); } } } if ($routeros_file_found == 0) { die('no routeros for ' . $GLOBALS['architecture_types'][$model] . ' found.'); } $sftp->pwd(); foreach ($files as $file) { if ($file != '.' && $file != '..') { if (strstr($file, $GLOBALS['architecture_types'][$model]) || strstr($file, $model)) { if (!strstr($file, $current_firmware_version . '-') && !strstr($file, $current_firmware_version . '.npk')) { logthis('sftping file (using password): ' . $file); $sftp->put("{$file}", file_get_contents($GLOBALS['firmware_directory'] . $file)); $ssh->exec(':beep frequency=137 length=2ms;'); } } if (strstr($file, $model)) { $configfile = $file; } } } if (!$configfile) { die('no backup for ' . $model . ' found.'); } $ssh = new Net_SSH2('192.168.88.1'); if ($ssh->login('admin', $GLOBALS['admin_password'])) { $todo = $ssh->exec('system reboot'); logthis($todo); $ssh->disconnect(); logthis('updated firmware (using password)'); } else { logthis('password ' . $GLOBALS['admin_password'] . ' is incorrect. '); } return $configfile; } else { logthis('password ' . $GLOBALS['admin_password'] . ' is incorrect. '); } }