So I have written a basic program with PHP and MongoDB and I tested it locally using xampp. This all works fine. Now I want to publish it as a website.
After some research I decided to use Bitnami and I am running an EC2 server on Amazon. I am able to ssh and run commands from the terminal. Now I want to connect to the server and create a Mongo client. I am a bit puzzled and do not know how to do this exactly. I am using the code below. The ssh works fine but I do not know how to set up the mongo client. The '$m = new MongoClient();' works fine locally for localhost, I have also tried to supply to MongoClient my username and password but without success. Thank you very much for any help!
include('Net/SSH2.php');
include('Crypt/RSA.php');
$key = new Crypt_RSA();
$key->loadKey(file_get_contents('../../etc/bitnami.pem'));
$ssh = new Net_SSH2('ip_address');
if (!$ssh->login('bitnami', $key)) {
exit('Login Failed');
}
$ssh->exec('mongo admin --username root -p <myPassword>');
$m = new MongoClient();
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycol;
echo "Collection selected succsessfully";
$document = array(
"title" => "MongoDB",
"description" => "database"
);
$collection->insert($document);
Update answer to Jota Martos (unable to write it as comment):
Hi, thank you for your answer. Yes for now I allow access from all ports and IP's for test purposes. I can successfully connect via ssh but now I am stuck. I am running a Mean bitnami application and my website is running on GoDaddy server under PHP. So I want to connect with PHP to my mongoDB bitnami app that is hosted on AWS. So now the problem is that on my GoDaddy server mongoDB is not installed. So running the following code does not work:
$m = new MongoDB\Driver\Manager("mongodb://${bitnami}:${AWSpassword}#hostIp");
Fatal error: Class 'MongoDB\Driver\Manager' not found.
So my question how do I connect with PHP from my GoDaddy server to the EC2 Amazon server and connect to Bitnami mongoDB account. Should I first setup an ssh connection to the server and then try to login to mongoDB server or how should I connect?
Any help is appreciated, thank you in advance!
According to php.net the function that is used is Deprecated, refer this.
Can you try something like:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://myusername:myp%40ss%3Aw%25rd#example.com/mydatabase");
?>
Refer this
Hi Bitnami Engineer here,
Apart from this tip, please note that the database port for the nodes in this solution cannot be accessed over a public IP address by default. For security reasons, we do not recommend making the database port accessible over a public IP address.
https://docs.bitnami.com/aws/infrastructure/mongodb/#how-to-connect-to-mongodb-from-a-different-machine
You can open the MongoDB port in the server by accessing the AWS console and modifying the access group configuration
https://docs.bitnami.com/aws/faq/#how-to-open-the-server-ports-for-remote-access
You will also need to modify the MongoDB configuration file (/opt/bitnami/mongodb/mongodb.conf) to allow the database to not to work only on 127.0.0.1.
Regards,
Jota
If you are looking to connect a tool like Studio 3T to a remote Mongodb instance built using bitnami AMI you can follow the steps below:
1. Open inbound port 27017 on instance security group.
2. Open Instance log of the instance and find the password for user root.
3. Open Studio 3T, server name is instance public ip and port 27017.
4. Got to Authentication and select basic and put in the user as root and password as obtained from instance log.
Click on Test Connection, it should work.
Related
I am trying to create a tunnel using ssh2_tunnel() to a remote AWS database, after being connected in ssh to the bastion host, via php, that has access to this remote MySql db.
Here is my actual code :
<?php
$ssh = ssh2_connect('domainofbastionhost', 22);
if (ssh2_auth_password($ssh,'myuserofthebastion','mypassofthebastion'){
$tunnel = ssh2_tunnel($ssh,'xxxx.xxx.xxx.rds.amazonaws.com',3306);
$stream_set_blocking($tunnel,true);
//Everything works fine up to here
$db = new PDO('mysql:host=xxxx.xxx.xxx.rds.amazonaws.com;port=3306;dbname=myawsdbname','myusertoaccessmyawsdb','mypasstoaccessmyawsdb');
}
?>
Due to this $db line, I get on my localhost page "Uncaught PDOException: SQLSTATE[HY000] [2002] Connection timed out ....".
I have tried to connect to the db from the bastion host (by ssh) through my shell, everything works fine, I am greeted by the "Trying 'IPOFTHEAWSDB'... Connected to 'canonical domain name of the db'. Escape character is '^]'. ] 5.5.5-xx.x.xx-MariaDB-xxxxxxmysql_native_password", which means everything works fine. I even tried to connect directly to the aws db, and I get disconnected, which means that my bastion host is clearly whitelisted to access the db.
I think the problem is that when I want to create my new PDO object, I am not whitelisted to access the resource, which means I have to use that $tunnel variable somewhere. I have seen a few examples online of some users using, instead of my $db line :
$db = new PDO('mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=myawsdbname,'myusertoaccessmyawsdb','mypasstoaccessmyawsdb');
But this is not working, as I don't have access to this mysql.sock resource as it should be on the bastion host. It's using my own mysqld.sock from my local machine. But where is the $tunnel stream really stored ? I am not sure.
I am quite confused as if it is possible to do so, and if so, how.
If you know anything or find anything, please tell me, it would mean a lot.
ssh2_tunnel() returns a raw socket resource, which is not going to be usable by any MySQL client libraries. It does not create a tunnel like the ssh CLI binary does. Also Unix sockets and TCP are very different beasts, so I would suggest not trying to follow that thread any further.
I would suggest not attempting to establish the tunnel in the context of a PHP script at all, as every request will open another connection and tunnel, potentially creating a lot of overhead on the bastion's SSH server.
To create an SSH tunnel on the command line:
ssh -N -L 3306:your.rds.instance:3306 your_user#bastion.host
Now you should be able to connect via 127.0.0.1:3306 in your PHP script.
To close the connection/turn off the tunnel issue ssh -O exit your_user#bastion.host.
However, I would not suggest using SSH tunnels for anything intended to be unattended. This is because I have found SSH tunnels to be finnicky, and they do not re-establish themselves after an interruption unless you're using a wrapper script, which is another layer of kludge. So I would suggest this approach for local dev/remote access only.
For a persistent connection that you might want to use to connect services/websites over, I would suggest some form of VPN depending on your particular requirements. I believe you can also apply security groups to your RDS instances to simply whitelist connections from certain public IP addresses/networks, but use with caution.
I am trying to connect to mysql DB on AWS with PHP client.
The connection has 2 phases:
1 - connect to SSH port 22 using public/private key auth
2 - connect to mysql server on port 3306
I am having problem with the first phase. I have pem file and I have the following code:
<?php
include('SSH2.php');
include('RSA.php');
$key = new Crypt_RSA();
$key->loadKey(file_get_contents('path to pem file'));
$ssh = new Net_SSH2('server IP');
if (!$ssh->login('root', $key)) {
exit('Login Failed');
}
echo $ssh->exec('ls -la');
?>
what am I doing wrong?
Anyone has an example for end2end connection??
I tested your script and it seems to work properly for me.
Kindly verify a few things to see why the ssh connection is not working,
Check that you are using the correct ssh private key [pem file] and that the permission on that file is readonly [ chown 0400 pemfile]
Check that the security group for the ec2 server allows port 22 to the IP address that the PHP is running on.
Check that you are using the correct Server IP, username. Generally speaking most of the EC2 server AMI are built with remote root login disabled, you will need to use the right username like on Amazon AMI you need to use ec2-user and on ubuntu amiit is ubuntu
Also please check on https://blog.rjmetrics.com/2009/01/06/php-mysql-and-ssh-tunneling-port-forwarding/ which gives in depth on what you are achieving
I have an application in which I have to access all pc connected to same network and their MySql Databases and I also want want to connect to remotely a server.
Actually I have list of drop down services and each service holding a database name. when I select a service then I want to build connection to database either it lies on same network or any remote server.
Remember, I know the hostname, username, password and dbname. and I am using mysqli_connect function.
I have try multiple options given on web, but all in vain. e.g grant host and user access. But not found any solution can help to solve my problem.
I have try bind-address option in my.conf file but no solution.
Here is my code
For remote Server
$con = new mysqli_connect('xxx xxx xxx:3306', 'username', 'pass', 'dbname');
For local Network
$con = new mysqli_connect('xxxx xxx xxx:3306', 'localhost', '', 'talent');
Error
mysqli::mysqli();(HY000/2002): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. and also get this one earlier Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'#'localhost' (using password: YES).
I am using windows platform. WIndow 8.1
I guess you want to access mysql database installed on different computers on same network as your computer and also on some remote server.
What you need is IP Addresses of all the computers on which the mysql server is installed including the remote server. And on each such computer mysql server remote access should be enabled for your computer's IP Address and mysql user you are using in 'new mysqli_connect()'. See this tutorial.
Also as fvu said check php documentation for 'mysqli_connect' function.
UPDATED
What is SSH?
1. SSH is SecureSHell.
2. Its nothing but a remote login tool or program(like telnet but in secured way).
3. Remote login is logging in to some other computer(known as remote computer) as a user of that computer from your computer.
4. After you successfully logged in to the remote computer via ssh, you can type commands on that remote computer on behalf of the user you are loggen in with.
5. Consider this as if you are sitting in front of your computer and watching the command prompt(terminal in linux and mac) screen of the remote computer.
6. Whataver you will type here will reflect there.
For your knowledge to make you understand the problem:
1. When you install XAMPP or WAMP on your computer it also installs MySQL Server with it.
2. MySQL Server is a process running in the background to which we can request to do
database operations like SELECT, UPDATE, etc.
3. This thing we generally do using 'mysql_connect' or 'mysqli_connect' in php.
4. MySQL Server can have many users and different users have different previledges/permissions. So that MySQL admin user(i.e. root) can control what things are allowed and not allowed for a user.
5. Now while connecting to the mysql server process we need to specify the user credentials. That you specify in mysqli_connect function.
Now let me explain you why you are getting that error:
1. The user credentials you are using either does not exist or not correct or the user has no access to connect to MySQL Server process remotely. i.e. from other computer that the one has MySQL Server installed on. In your case from your computer to computer A or to computer B or remote server.
2. The other reason may be the firewall settings of remote computers.
Solution:
1. For computer A and computer B you don't need ssh you can directly go to the computer and open command prompt on it and type commands.
2. But for remote computer you need to use ssh.
3. Now another problem is you are using Windows so ssh program will not be available to you.
4. You will need to download putty program. Its ssh implementation for windows. Same as ssh only name is different.
5. Take a putty tutorial to connect to remote server.
6. Then you can use this tutorial for granting remote login access to mysql user you are using in mysqli_connect function.
If the server is a local hosted database and you can connect to it from local host and i you are not able to connect to it from a remote machine consider the following options.
There is a firewall in ubuntu that you need to open, you do this by granting access in IPtables.
/sbin/iptables -A INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT And now we should be able to login to our server from our local machine:
mysql -h255.112.324.12 -uroot -pMyPASSWORD
You need
to grant access to mysql: https://askubuntu.com/questions/159053/mysql-server-not-accessible-from-remote-machine
as root, open your /etc/mysql/my.cnf with your favorite editor look for the [mysqld] section, and in there for the bind-address keyword. This usually is set to 127.0.0.1 -- change that to match your "normal" IP-address save the file, and reload the service (e.g. using service mysql restart)
Last but not least you need to give remote access in mysql:
GRANT ALL ON mydb.* TO root#'%' IDENTIFIED BY 'MyPASSWORD';
Find more information here: http://web.archive.org/web/20120930214828/http://chosencollective.com/technology/how-to-enable-remote-access-to-mysql
Right now you seem to be mixing object-oriented and procedural approaches. If you want to use object-orented approach, mysqli object should be instantiated as follows:
$con = new mysqli($host, $username, $password, $dbname, $socket); // all but first parameter are optional
If you want to use procedural approach, mysqli connection resource should be created as follows:
$con = mysqli_connect($host, $username, $password, $dbname, $socket); // all but first parameter are optional
I am unable to make a database connection from the App Engine SDK server to my local MySQL which was installed with MAMP. I understand that this is about the MySQL socket file which is in MAMP. How can I let App Engine SDK to listen to the local MySQL? I also want to ensure that my MAMP setup remains intact. Thanks.
App engine SDK for php can connect to you local MySql server in your development environment.
First make sure you have the latest SDK for PHP version, currently release 1.8.6.
Make sure your local MySql server instance is running and listening on port 3306.
Add your application in the App Engine SDK Launcher, click on it and select Edit / Application Settings and add in the "Extra Command Line Flags" field the following:
--mysql_user=user
Where user is the username to connect to your database.
Then you have to connect to your DB from your php code, in my case, I'm using PDO.
Like this:
try {
$db = new PDO('mysql:unix_socket=/cloudsql/<appname>:my-cloudsql-instance;charset=utf8;dbname=<yourdbname>','<user>','<password>');
syslog(LOG_DEBUG, 'Connected to database.');
} catch (PDOException $e) {
syslog(LOG_ERR, 'Failed to get PDO DB handle: ' . $e->getMessage());
print_r($e->getMessage());
exit;
}
Replace the text with <> tags with your application and MySql server settings.
GAE currently does not allow connection to any remote MySQL server. This is their limit and nothing to do with your setup.
Use their Cloud SQL instead.
I don't know in which situation the error occurred to Nagarjun, but to me happened with the following PHP warning
Warning: mysql_connect(): No such file or directory in
/Users/Aerendir/Documents/JooServer/_SandBox/GoogleAppEngine/continuous-wordpress-cms/wordpress/wp-includes/wp-db.php
on line 1372
In my situation, i were trying to install WordPress on Google AppEngine following their tutorial.
The problem was the hostname I used: localhost instead of 127.0.0.1
Using 127.0.0.1 as hostname solved the problem.
The solution was found here: Configuring MySQL connection in Google App Engine PHP SDK on Windows 7
It is the first time I am working with PHP 5 LDAP library and I am a bit confused. I would be very happy if anyone could give me some clarifications on the following:
First of all let me give my configurations:
LDAP server: Windows Server 2013 Active Directory
Hostname: winad
Domain: domain.local
IP: 1.1.1.1 (for the sake of explaining)
Windows Account used for binding: Administrator
Ping hostname from dev machine works
Ping ip from dev machine works
Ping winad.domain.local from dev machine fails
Development Environment: Windows 8 Professional with WAMP
PHP: 5.3.13
PHP LDAP Module loaded and working
Apache LDAP module not loaded
Scenario:
I am trying to authenticate a user against the Windows AD with the administrator account for a start. Here is a sample of my code:
I will be using these variables in the various scenarios below:
$hostname = "winad";
$dnex= "uid=Administrator, ou=Users, dc=domain, dc=local";
Code that works:
$conn = ldap_connect($hostname);
$bind = ldap_bind($conn, "DOMAIN\Administrator", "password");
Code that fails:
$conn = ldap_connect($hostname);
$bind = ldap_bind($conn, $dnex, "password");
Error: Invalid credentials
Now my question is why does it fails when I specify a dn?
Let say I have location1.domain.local and location2.domain.local and I want to bind only with location2, it does not seem possible without specifying the dn.
Can somebody show the right way to proceed?
After some more search I found the following post:
PHP LDAP Connection
The response from AlexC answered my question correctly.
Hope this is helpful.