How to run SSH command using Laravel Envoy - php

I want to run SSH command to start/stop Server with Laravel Envoy on Linux. But the am getting error for syntax of SSH::into(). I don't know what to do completely stuck. Need way to solve this and make this works.
Envoy setup and works fine with "php artisan" command:
// Envoy.blade.php
#setup
$connection = ['web' => $user.'#'.$host.' -p '. '22'];
#endsetup
#servers($connection)
#task('foo', ['on' => 'web'])
php artisan
#endtask
Command: envoy run foo --user=root --host=94.130.97.242
And this is what am doing for SSH::into() to start/stop server.
// Envoy.blade.php
#include('vendor/autoload.php')
$connection = ['web' => $user.'#'.$host.' -p '. '22'];
$target = [
'host' => $host,
'username' => $user,
'password' => $password,
'timeout' => 10,
];
Config::set('remote.connections.runtime.host', $target['host']);
Config::set('remote.connections.runtime.port', '22');
Config::set('remote.connections.runtime.username', $target['username']);
Config::set('remote.connections.runtime.password', $target['password']);
#endsetup
#servers($connection)
#task('foo', ['on' => 'web'])
SSH::into('runtime')->run(array(
'docker stop ' . $server
));
#endtask
Command: envoy run foo --user=root --host=94.130.97.242 --password=password --server=22
After running it giive an error syntaxt error unexpected token'runtime'.
I need your help. Thank you!

Here is a way with a Symfony process (natively available within Laravel)
use Symfony\Component\Process\Process;
function start(string $user, string $host)
{
$sshSetting = sprintf('ssh://%s#%s', $user, $host);
$process = new Process([
'docker', '-H', $sshSetting, 'start'
]);
$process->run(); //synchronous
$process->mustRun(); //synchronous, throw an exception whenever fail
$process->start(); //asynchronous
}
Here is the official documentation https://symfony.com/doc/current/components/process.html#running-processes-asynchronously

Related

SSH into dynamic remote server and run a command - Laravel 5.8

I'm using L 5.8 and I have a form with 3 inputs
Right now, I can SSH into a specific server with this package laravelcollective/remote": "~5.8. I required to pre configured IP, UN, PW in the config/remote.php like so :
'connections' => [
'production' => [
'host' => '1.1.1.1',
'username' => 'code',
'password' => '8888',
'key' => '',
'keytext' => '',
'keyphrase' => '',
'agent' => '',
'timeout' => 10,
],
],
Then, I can easily run any command(s) or even chain them
$commands = ['cd /home/code && ./runMe.sh'];
SSH::run($commands, function($line)
{
echo $line.PHP_EOL;
});
Result
My portal will connect to that server and run that command successfully, and I've verified it.
Now
I need to read it from form inputs. Is it possible to use the same plugin and dynamically setting that file remote.php ?
or
Should I start looking into something else because this is a dead end ?
Please advise,
You can use the config() helper here:
example config:
config([
'remote.connections.production.host' => $request->input('hostname'),
'remote.connections.production.username' => $request->input('username'),
'remote.connections.production.password' => $request->input('password')
]);
then call:
$commands = ['cd /home/code && ./runMe.sh'];
SSH::run($commands, function($line)
{
echo $line.PHP_EOL;
});
This example require the package php-ssh2, and provide many ways to retrieve the remote shell STDOUT as a stream. It's also great to control the current machine shell and get responses.
sudo apt install php-ssh2
Or by version:
sudo apt install php7.4-ssh2
Example usage of ssh2_exec() and ssh2_fetch_stream():
<?php
$ssh = ssh2_connect('192.162.68.212', 22); // Remote address
ssh2_auth_password($ssh, 'root', 'XQA8DCamdEm'); // Credentials
$shell = ssh2_shell($ssh, 'xterm'); // Choose remote shell
$stream = ssh2_exec($ssh, 'cd /home/code && ./runMe.sh'); // Remote command
stream_set_blocking($stream, true); // Wait for multiline output, till EOF
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); // SSH2_STREAM_STDERR
echo stream_get_contents($stream_out); // Print in real-time
It is possible to retrieve only the errors, this is great for monitoring only without parsing the whole output, by using the flag SSH2_STREAM_STDERR.
To write strings only to STDERR from the remote PHP, we can use:
fwrite(STDERR, "Some logs, from machine (...)\n");
Or we can pipe the errors directly in the remote shell command:
cd /home/code && ./runMe.sh 2>
https://www.php.net/manual/en/ref.ssh2.php

Why am I not able to parse JSON correctly with AWS SDK in Laravel?

I am using Laravel 5.5 with the AWS SDK for laravel (https://github.com/aws/aws-sdk-php-laravel).
I'm trying to do a simple request to establish that I'm connecting correctly. I believe I have my credentials all set and nothing points to that as an error.
Here is the function in my laravel controller that is being called:
public function testData(Request $request) {
$sdk = new Sdk([
'endpoint' => 'http://localhost:80',
'region' => 'us-east-1',
'version' => 'latest'
]);
$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();
$tableName = 'funTalkDataStorage';
$params = [
'TableName' => $tableName
];
try {
$result = $dynamodb->query($params);
} catch (DynamoDbException $e) {
echo "Unable to query:\n";
echo $e->getMessage() . "\n";
}
}
The table 'funTalkDataStorage' does exist out on AWS already where there are two records already.
The thing that I'm not understanding is why I'm getting the following error from Laravel:
Aws \ Api \ Parser \ Exception \ ParserException
Error parsing JSON: Syntax error
being thrown by :
aws\aws-sdk-php\src\Api\Parser\PayloadParserTrait.php
The error is originating from the line in my code:
$result = $dynamodb->query($params);
I've been digging through the sdk and searching the web and I'm just not getting where the issue is. Any help would be marvalous!
Ok. My issue was that i was using port 80. It should have been port 8000.

PHP gearman connection error

I trying to run a task in PHP using gearman I created 2 scripts:
client.php
<?
$mail = array(
'to' => 'test#gmail.com',
'subject' => Hi',
'body' => 'Test message',
);
# Connect to Gearman server
$client = new GearmanClient();
$client->addServer('127.0.0.1', '4730');
# Send message
$client->doBackground('sendmail', json_encode($mail));
worker.php
<?php
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction('sendmail', 'send_mail');
while (1)
{
$worker->work();
if ($worker->returnCode() != GEARMAN_SUCCESS) break;
}
function send_mail($job)
{
$workload = $job->workload();
$data = json_decode($workload, true);
mail($data['to'], $data['subject'], $data['body']);
}
when I run my worker from comand line : php worker.php &
and run my client.php file I get the below error:
GearmanClient::doBackground(): send_packet(GEARMAN_COULD_NOT_CONNECT) Failed to send server-options packet -> libgearman/connection.cc:485
Any help please?
Thanks
Try to change this:
$client->addServer('127.0.0.1', '4730');
to
$client->addServer();
If still no working, try to take a look in the get started page of this tutorial on php. It worked fine for me
You forgot to start gearman by running gearmand -d
Read more about it in the documentation at http://gearman.org/getting-started/

PHP pdo exception "could not find driver" pgsql

So i always get a pdo exception when i try to create my db in the constructor of my Mapper class.
on this line:
$this->db = new PDO($dsn, $db_config['username'], $db_config['password']);
this is my dsn creation:
$db_config = array(
'driver' => 'pgsql',
'username' => $dbUser,
'password' => $dbPassword,
'schema' => 'r0628740',
'dsn' => array(
'host' => 'gegevensbanken.khleuven.be',
'dbname' => '2TX31',
'port' => '51314',
)
);
and finaly my constructor:
public function __construct(){
global $db_config;
$dsn = $db_config['driver'] . ':';
foreach($db_config['dsn'] as $key => $value){
$dsn .= $key . '=' . $value . ';';
}
try{
$this->db = new PDO($dsn, $db_config['username'], $db_config['password']);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(($db_config['driver'] == 'pgsql') && isset($db_config['schema'])){
$this->db->query(sprintf("SET SEARCH_PATH TO %s"), $db_config['schema']);
}
}catch (PDOException $e){
var_dump($e->getLine());
error_log($e->getMessage());
}
}
The PHP contains a dll required by pgsql and pgsql_pdo driver libpq.dll...
Add PHP binary path to system path or copy de DLL into Windows\system32. On linux dependency are installed automatically.
I found article somewhere, works for me. Assuming you have installed PostgreSQL and your WAMP installation is on c:\wamp, you will need to copy:
c:\wamp\bin\php\php5.3.9\libpq.dll to c:\wamp\bin\apache\Apache2.2.11\bin.
Make sure you also have the following files:
C:\wamp\bin\php\php5.3.9\ext\php_pdo_pgsql.dll and
C:\wamp\bin\php\php5.3.9\ext\php_pgsql.dll
Also, make sure you have enabled the above 2 files as extensions, either via the WAMP menu (click on WAMP icon on taskbar: PHP > PHP extensions, find the above 2 and 'check' them).
Please note that php5.3.9 and Apache2.2.11 refer to my specific PHP and Apache versions.
Adjust those to suit your installation.
Copying this libpq.dll from c:\wamp\bin\php\php5.3.9\libpq.dll to c:\wamp\bin\apache\Apache2.2.11\bin. has worked for me

how to connect to the database in openshift application

I did as following
MySQL 5.1 database added. Please make note of these credentials:
Root User: xxxxxxx
Root Password: xxxxxxx
Database Name: php
Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
You can manage your new MySQL database by also embedding phpmyadmin-3.4.
The phpmyadmin username and password will be the same as the MySQL credentials above.
phpMyAdmin 3.4 added. Please make note of these MySQL credentials again:
Root User: xxxxxxx
Root Password: xxxxxxx
URL: https://php-doers.rhcloud.com/phpmyadmin/
and i try to connect db using bellow PDO code .but it does not work
$dbh = new PDO('mysql:host=mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/;dbname=php', "xxxxxx, "xxxxxx");
I don't know what is the connection URL mean ?
There is an error in your connection string plus $OPENSHIFT_MYSQL_DB_* are env variables and need to be fetched via getenv php function.
So try the following:
define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST'));
define('DB_PORT',getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER',getenv('OPENSHIFT_MYSQL_DB_USERNAME'));
define('DB_PASS',getenv('OPENSHIFT_MYSQL_DB_PASSWORD'));
define('DB_NAME',getenv('OPENSHIFT_GEAR_NAME'));
$dsn = 'mysql:dbname='.DB_NAME.';host='.DB_HOST.';port='.DB_PORT;
$dbh = new PDO($dsn, DB_USER, DB_PASS);
Open php myadmin from webconsole , and on left corner you will get some Ip
That is like xx.xx.xx.xx:3306 , so your hostname is xx.xx.xx.xx
Ip address wil work , I have tried and worked for me
below code worked for me ,try this it might help you
var mysql = require('mysql');
var mysql = require('mysql');
exports.pool = mysql.createPool({
host: process.env.OPENSHIFT_MYSQL_DB_HOST || 'localhost',
port: process.env.OPENSHIFT_MYSQL_DB_PORT || '3306',
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root',
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || '',
database: 'chichat' || 'chichat',
multipleStatements : true,
charset: 'utf8'
});
I would like to add some information to future reference.
Today I am trying to deploy a Drupal installation to Open Shift (OS) and tried to configure MySql.
I connected to OS via SSH (rhc ssh ), went to app-root/data/sites/default. Following cat settings.php to see how OS configure database.
Here it is:
// When run from Drush, only $_ENV is available. Might be a bug
if (array_key_exists('OPENSHIFT_APP_NAME', $_SERVER)) {
$src = $_SERVER;
} else {
$src = $_ENV;
}
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => $src['OPENSHIFT_APP_NAME'],
'username' => $src['OPENSHIFT_MYSQL_DB_USERNAME'],
'password' => $src['OPENSHIFT_MYSQL_DB_PASSWORD'],
'host' => $src['OPENSHIFT_MYSQL_DB_HOST'],
'port' => $src['OPENSHIFT_MYSQL_DB_PORT'],
'driver' => 'mysql',
'prefix' => '',
),
),
);
$conf['file_private_path'] = $src['OPENSHIFT_DATA_DIR'] . 'private/';
$conf['file_temporary_path'] = $src['OPENSHIFT_TMP_DIR'] . 'drupal/';
So I created a php folder into git repository (see OS documentation about Drupal), copied a clean Drupal install to it and paste code above to settings.php.
After pushing to git, restarted OS app and worked!

Categories