Пример #1
0
 /**
  * Executo command on shell
  * @param Shell $shell
  * @return bool
  * @throws \Exception
  */
 public function run(Shell $shell)
 {
     $match = NULL;
     while (true) {
         fwrite($shell->getStream(), $this->__cmd);
         switch ($key = expect_expectl($shell->getStream(), $cases = $this->formatCases(), $match)) {
             case in_array($key, $cases):
                 // Run next
                 if ($this->__next instanceof TCommand) {
                     $this->__next->run($shell);
                 }
                 if ('break' == ($result = $this->__cases_list[$key]->proceed($shell->getStream(), $match))) {
                     break;
                 }
                 $shell->addCmd($this->__cmd);
                 $shell->addResult($this->formatResult($result));
                 return true;
                 break 2;
             case EXP_EOF:
             case EXP_FULLBUFFER:
                 break 2;
             case EXP_TIMEOUT:
                 throw new \Exception("Connection time out");
                 break 2;
             default:
                 throw new \Exception("Error has occurred!");
                 break 2;
         }
     }
     return false;
 }
Пример #2
0
function hostHardCtl($op, $pass)
{
    openlog("myScriptLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);
    syslog(LOG_WARNING, "Attempting to exec hostHardCtl");
    switch ($op) {
        case 0:
            $cmd = '"/sbin/shutdown -r now"';
            break;
        case 1:
            $cmd = '"/sbin/shutdown -h now"';
            break;
        default:
            syslog(LOG_WARNING, "unknown command");
            break;
    }
    //$cmd = '"ls -la /root"';
    $cases = array(array(0 => "Password: "******"PASSWORD"));
    $full_cmd = "su -c " . $cmd;
    syslog(LOG_WARNING, "execute: " . $full_cmd);
    $stream = expect_popen($full_cmd);
    $ret = expect_expectl($stream, $cases);
    switch ($ret) {
        case "PASSWORD":
            fwrite($stream, $pass . "\n");
            syslog(LOG_WARNING, "pwd: " . $pass);
            break;
        case EXP_TIMEOUT:
            syslog(LOG_WARNING, "EXP_TIMEOUT");
            return false;
            break;
        case EXP_EOF:
            syslog(LOG_WARNING, "EXP_EOF");
            return false;
            break;
        default:
            syslog(LOG_WARNING, "EXP_TIMEOUT");
            return false;
            break;
    }
    $out = '';
    while ($line = fgets($stream)) {
        $out .= $line;
        syslog(LOG_WARNING, "ret: " . $line);
    }
    fclose($stream);
    closelog();
    return $out;
}
Пример #3
0
 /**
  * Handles expect communication.
  *
  * @param string $expect  String to expect.
  * @param string $error   Error message.
  *
  * @throws Passwd_Exception
  */
 protected function _ctl($expect, $error)
 {
     $result = expect_expectl($this->_stream, array(array(0 => $expect, 1 => 'ok', 2 => EXP_REGEXP)));
     switch ($result) {
         case EXP_EOF:
             throw new Passwd_Exception(_("End of file."));
         case EXP_TIMEOUT:
             throw new Passwd_Exception(_("Time out."));
         case EXP_FULLBUFFER:
             throw new Passwd_Exception(_("Full buffer."));
         case 'ok':
             return;
         default:
             throw new Passwd_Exception($error);
     }
 }
Пример #4
0
 public function checkRepExist($repName)
 {
     $logfile = "/home/apacheUser/temp4autotestsys/" . time() . rand(11, 99) . ".log";
     ini_set("expect.timeout", 3);
     ini_set("expect.loguser", "Off");
     ini_set("expect.logfile", $logfile);
     $cases = array(array(0 => "yes/no", 1 => "YESNO", EXP_EXACT), array(0 => "10.18's password:"******"PASSWORD", EXP_EXACT), array(0 => "\$", 1 => "EXPECTSHELL", EXP_EXACT));
     $stream = expect_popen("ssh www@*.*.*.18");
     $i = 0;
     $result = "";
     while (true) {
         switch (expect_expectl($stream, $cases, $match)) {
             case "YESNO":
                 fwrite($stream, "yes\r");
                 break;
             case "PASSWORD":
                 fwrite($stream, "www\r");
                 break;
             case "EXPECTSHELL":
                 if ($i == 1) {
                     break 2;
                 } else {
                     fwrite($stream, "mkdir /data1/www/*/{$repName}\r");
                     fwrite($stream, "mkdir /data1/www/*/{$repName}\r");
                     fwrite($stream, "mkdir /data1/www/*/cloud/{$repName}\r");
                     $i = $i + 1;
                     break;
                 }
             case EXP_TIMEOUT:
             case EXP_EOF:
                 break 2;
             default:
                 break 2;
         }
     }
     fclose($stream);
     return $logfile;
     //        $result = exec("sudo /usr/bin/expect ../app/script/checkRepExist ".$repName,$result1);
     //        $isExist = false;
     //        foreach($result1 as $item)
     //            if(strstr($item,"File exists")){
     //                $isExist=true;
     //                break;
     //            };
     //        return $isExist;
 }
Пример #5
0
 public function exec(Command $cmd)
 {
     $match = NULL;
     // Get clear shell for work
     while (true) {
         switch (expect_expectl($this->__stream, array(array("(.*)[\$|#][ ]\$", SHELL, EXP_REGEXP)), $match)) {
             case SHELL:
                 $cmd->run($this);
                 return $this;
                 // Chain of commands
                 break 2;
             case EXP_EOF:
             case EXP_FULLBUFFER:
                 break 2;
             case EXP_TIMEOUT:
                 throw new \Exception("Connection time out");
                 break 2;
             default:
                 throw new \Exception("Error has occurred!");
                 break 2;
         }
     }
     return false;
 }
Пример #6
0
<?php

ini_set("expect.loguser", "Off");
$stream = fopen("expect://ssh root@remotehost uptime", "r");
$cases = array(array(0 => "password:"******"password\n");
        break;
    default:
        die("Error was occurred while connecting to the remote host!\n");
}
while ($line = fgets($stream)) {
    print $line;
}
fclose($stream);
Пример #7
0
 /**
  * Uses Docker to deploy the given project to a live server
  * @param  \GitDeployer\Objects\Project $project The project to deploy
  * @param  string                       $gitpath The path to the checked-out project
  * @param  array                        $config  The configuration options to pass to this deployer
  * @return mixed
  */
 public function deploy(\GitDeployer\Objects\Project $project, $gitpath, $config)
 {
     $useTunnel = false;
     // -> Connect to the docker daemon on a tcp or unix socket
     if (!isset($config['host']) || strlen($config['host']) < 1) {
         $config['host'] = getenv('DOCKER_HOST');
     }
     if (strlen($config['host']) < 1) {
         throw new \Exception('Neither the "host" parameter was specified in the .deployer file nor is the DOCKER_HOST environment variable set!');
     }
     if (stristr($config['host'], 'tcp://')) {
         // Setting the docker host to tcp:// may enable usage of the SSH tunnel functionality
         if (isset($config['ssh']) && is_array($config['ssh'])) {
             if (isset($config['ssh']['tunnel']) && $config['ssh']['tunnel'] == true) {
                 $useProc = false;
                 $useTunnel = true;
                 parent::showMessage('DOCKER', 'Connecting to Docker daemon via SSH...', $this->output);
                 // Check if the ssh binary is executable, else bail out
                 // since we can't open a tunnel without it
                 if (!$this->commandExists('ssh')) {
                     throw new \Exception('SSH client not found: Please make sure the "ssh" command is available, and in your $PATH!');
                 } else {
                     if (!isset($config['ssh']['host']) || strlen($config['ssh']['host']) < 1) {
                         throw new \Exception('Please specify at least a SSH host in your .deployerfile to connect to!');
                     }
                     if (!isset($config['ssh']['user']) || strlen($config['ssh']['user']) < 1) {
                         $config['ssh']['user'] = "******";
                     }
                     $config['ssh']['port'] = isset($config['ssh']['port']) && strlen($config['ssh']['port']) > 0 ? $config['ssh']['port'] : 22;
                     if (!isset($config['ssh']['privatekey']) || strlen($config['ssh']['privatekey']) < 1) {
                         throw new \Exception('Please correctly specify your SSH private key in the .deployerfile!');
                     }
                     // -> Open tunnel via SSH command
                     $randport = rand(60000, 65000);
                     $remotedesc = str_replace('tcp://', '', $config['host']);
                     $cmdstring = 'ssh -N -i ' . escapeshellarg($config['ssh']['privatekey']) . ' -L ' . $randport . ':' . $remotedesc . ' -p ' . $config['ssh']['port'] . ' ' . $config['ssh']['user'] . '@' . $config['ssh']['host'];
                     if (isset($config['ssh']['password']) && strlen($config['ssh']['password']) > 1) {
                         if (!extension_loaded('expect')) {
                             throw new \Exception('Expect extension not found: Please make sure the PHP expect extension is available in your PHP installation!');
                         }
                         $stream = fopen('expect://' . $cmdstring, 'r');
                         $cases = array(array('Enter passphrase', PASSWORD));
                         ini_set("expect.timeout", 30);
                         switch (expect_expectl($stream, $cases)) {
                             case PASSWORD:
                                 fwrite($stream, $config['ssh']['password'] . "\n");
                                 // Wait for tunnel port to be available
                                 while (true) {
                                     $socket = @fsockopen('127.0.0.1', $randport, $errno, $errstr, 5);
                                     if ($socket) {
                                         fclose($socket);
                                         break;
                                     }
                                 }
                                 break;
                             default:
                                 throw new \Exception('Unable to connect to the remote SSH host! Invalid string received: Expected passphrase prompt.');
                         }
                     } else {
                         $stream = proc_open('exec ' . $cmdstring, array(), $pipes);
                         $useProc = true;
                         // Wait for tunnel port to be available
                         while (true) {
                             $socket = @fsockopen('127.0.0.1', $randport, $errno, $errstr, 5);
                             if ($socket) {
                                 fclose($socket);
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     $client = new \Docker\DockerClient(array('remote_socket' => 'tcp://127.0.0.1:' . $randport, 'ssl' => isset($config['ssl']) && $config['ssl'] == true ? true : false));
     $docker = new \Docker\Docker($client);
     // -> Build the docker image if a Dockerfile is present
     if (!file_exists($gitpath . '/Dockerfile')) {
         throw new \Exception('No Dockerfile found - aborting build!');
     }
     parent::showMessage('DOCKER', 'Building image (no-cache)...', $this->output);
     parent::showMessage('DOCKER', 'Uploading context...', $this->output);
     $context = new \Docker\Context\Context($gitpath);
     $imageManager = $docker->getImageManager();
     $buildStream = $imageManager->build($context->toStream(), array('t' => 'git-deployer/' . $project->name()), \Docker\Manager\ContainerManager::FETCH_STREAM);
     $buildStream->onFrame(function (\Docker\API\Model\BuildInfo $buildInfo) {
         parent::showMessage('BUILD', $buildInfo->getStream(), $this->output);
     });
     $buildStream->wait();
     // -> Stop and remove the old container with the same name, sicne we're going
     // to replace the app here with the newly built container
     parent::showMessage('DOCKER', 'Getting running containers...', $this->output);
     $containersOnHost = $docker->getContainerManager()->findAll();
     if (count($containersOnHost) > 0) {
         // We check for a container with the same name as the one we are going to deploy
         foreach ($containersOnHost as $key => $container) {
             $containerFound = false;
             // Search by name
             foreach ($container->getNames() as $name) {
                 $cleanName = $this->cleanName($project->name());
                 preg_match('#\\/.*\\/(.*)#', $name, $matches);
                 if ($cleanName == $matches[1]) {
                     $containerFound = true;
                 }
             }
             // Search by image
             if ($container->getImage() == 'git-deployer/' . $project->name()) {
                 $containerFound = true;
             }
             if ($containerFound) {
                 parent::showMessage('DOCKER', 'Stopping old container ' . $container->getId() . '...', $this->output);
                 $docker->getContainerManager()->stop($container->getId());
                 $docker->getContainerManager()->remove($container->getId());
             }
         }
     }
     // -> Start the container up if we have built sucessfully
     parent::showMessage('DOCKER', 'Starting new container...', $this->output);
     $hostConfig = new \Docker\API\Model\HostConfig();
     $containerConfig = new \Docker\API\Model\ContainerConfig();
     $containerConfig->setNames(array('git-deployer/' . $this->cleanName($project->name())));
     $containerConfig->setImage('git-deployer/' . $project->name());
     // Add environment from the config file, if any
     $envArray = array();
     if (isset($config['environment'])) {
         foreach ($config['environment'] as $key => $value) {
             $envArray[] = $key . '=' . $value;
         }
     }
     $containerConfig->setEnv($envArray);
     // Add exposed ports from the config file, if any
     if (isset($config['ports']) && is_array($config['ports']) && count($config['ports']) > 0) {
         $exposedPorts = new \ArrayObject();
         $mapPorts = new \ArrayObject();
         foreach ($config['ports'] as $portdesc) {
             $portspec = $this->parsePortSpecification($portdesc);
             // Exposed port
             $exposedPort = $portspec['port'] . (strlen($portspec['protocol']) > 0 ? '/' . $portspec['protocol'] : '/tcp');
             $exposedPorts[$exposedPort] = new \stdClass();
             // Host port binding
             $hostPortBinding = new \Docker\API\Model\PortBinding();
             $mapPorts[$exposedPort] = array($hostPortBinding);
         }
         $containerConfig->setExposedPorts($exposedPorts);
         $hostConfig->setPortBindings($mapPorts);
     }
     // Add restart policy
     if (isset($config['restart']) && strlen($config['restart']) > 0) {
         $policy = $this->parseRestartPolicy($config['restart']);
         $restartPolicy = new \Docker\API\Model\RestartPolicy();
         $restartPolicy->setName($policy['Name']);
         if (isset($policy['MaximumRetryCount'])) {
             $restartPolicy->setMaximumRetryCount($policy['MaximumRetryCount']);
         }
         $hostConfig->setRestartPolicy($restartPolicy);
     }
     // Add binds
     if (isset($config['volumes']) && is_array($config['volumes']) && count($config['volumes']) > 0) {
         $binds = new \ArrayObject();
         foreach ($config['volumes'] as $volume) {
             $binds[] = $volume;
         }
         $hostConfig->setBinds($binds);
     }
     $containerConfig->setHostConfig($hostConfig);
     $containerCreateResult = $docker->getContainerManager()->create($containerConfig, array('name' => $this->cleanName($project->name())));
     if ($containerCreateResult->getId()) {
         $docker->getContainerManager()->start($containerCreateResult->getId());
     }
     // -> Clean up and close the SSH tunnel
     if ($useTunnel) {
         if ($useProc) {
             proc_terminate($stream, 9);
             proc_close($stream);
         } else {
             fclose($stream);
         }
     }
     return array(true, 'No trace');
 }
Пример #8
0
 public function getSTokenOnline()
 {
     $mobile = Input::get('mobile');
     $logfile = "/home/apacheUser/temp4autotestsys/" . time() . rand(11, 99) . ".log";
     ini_set("expect.timeout", 3);
     ini_set("expect.loguser", "Off");
     ini_set("expect.logfile", $logfile);
     $cases = array(array(0 => "yes/no", 1 => "YESNO", EXP_EXACT), array(0 => "'s password:"******"PASSWORD", EXP_EXACT), array(0 => "bash-4.1\$", 1 => "EXPECTSHELL", EXP_EXACT), array(0 => "选择服务器:", 1 => "SERVER", EXP_EXACT), array(0 => "请选择账号:", 1 => "ZHANGHAO", EXP_EXACT), array(0 => "mysql>", 1 => "MYSQL", EXP_EXACT));
     $stream = expect_popen("ssh *@1*");
     while (true) {
         switch (expect_expectl($stream, $cases)) {
             case "YESNO":
                 fwrite($stream, "yes\r");
                 break;
             case "PASSWORD":
                 fwrite($stream, "*\r");
                 break;
             case "SERVER":
                 fwrite($stream, "0\n");
                 usleep(300000);
                 fwrite($stream, "\r");
                 usleep(100000);
                 break;
             case "ZHANGHAO":
                 fwrite($stream, "0\r");
                 break;
             case "EXPECTSHELL":
                 fwrite($stream, "mysql -u*@l1 *P*\r");
                 break 2;
             case EXP_TIMEOUT:
             case EXP_EOF:
                 break 2;
             default:
                 break 2;
         }
     }
     $time = 0;
     while (true) {
         switch (expect_expectl($stream, $cases)) {
             case "EXPECTSHELL":
                 fwrite($stream, "mysql*@l1 -h 1*\r");
                 break;
             case "MYSQL":
                 if ($time < 2) {
                     fwrite($stream, "use user_db;\r");
                     fwrite($stream, "select sToken from t_user_login_status where iUserID=(select iAutoID from\r\n        t_user where sMobile= " . $mobile . ") order by iAutoID desc limit 1;\r");
                     $time = $time + 1;
                 }
                 break;
             case EXP_TIMEOUT:
             case EXP_EOF:
                 break 2;
             default:
                 break 2;
         }
     }
     fclose($stream);
     return $logfile;
 }