CONSOLE COMMANDS
help show all the console commands (same as this section)
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
use <db name> set curent database to <db name>
db.help() help on DB methods
db.foo.help() help on collection methods
db.foo.find() list objects in collection foo
db.foo.find({a:1}) list objects in foo where a == 1
it result of last line evaluated; use to further iterate
DATABASE METHODS
db.addUser(username, password)
db.auth(username, password)
db.cloneDatabase(fromhost)
db.commandHelp(name) // returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.currentOp() // displays the current operation in the db
db.dropDatabase()
db.eval(func, args) // run code server-side
db.getCollection(cname) // same as db['cname'] or db.cname
db.getCollectionNames()
db.getLastError() // just returns the err msg string
db.getLastErrorObj() // return full status object
db.getMongo() // get the server connection object
db.getMongo().setSlaveOk() // allow this connection to read from the nonmaster member of a replica pair
db.getName()
db.getPrevError()
db.getProfilingLevel()
db.getReplicationInfo()
db.getSisterDB(name) // get the db at the same server as this onew
db.killOp() // kills the current operation in the db
db.printCollectionStats()
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()
db.removeUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) // run a database command. if cmdObj is a string, turns it into {cmdObj:1}
db.setProfilingLevel(level) // 0=off 1=slow 2=all
db.shutdownServer()
db.version() // current version of the server
COLLECTION METHODS
db.foo.count()
db.foo.dataSize()
db.foo.distinct( key ) // eg. db.foo.distinct( 'x' )
db.foo.drop() // drop the collection
db.foo.dropIndex(name)
db.foo.dropIndexes()
db.foo.ensureIndex(keypattern,options) // options should be an object with these possible fields: name, unique, dropDups
db.foo.find( [query] , [fields]) // first parameter is an optional query filter.
// second parameter is optional set of fields to return.
// e.g. db.foo.find( { x : 77 } , { name : 1 , x : 1 } )
db.foo.find(...).count()
db.foo.find(...).limit(n)
db.foo.find(...).skip(n)
db.foo.find(...).sort(...)
db.foo.findOne([query])
db.foo.getDB() // get DB object associated with collection
db.foo.getIndexes()
db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )
db.foo.remove(query)
db.foo.renameCollection( newName ) // renames the collection
db.foo.save(obj)
db.foo.stats()
db.foo.storageSize() // includes free space allocated to this collection
db.foo.totalIndexSize() // size in bytes of all the indexes
db.foo.totalSize() // storage allocated for all data and indexes
db.foo.update(query, object[, upsert_bool, multi_record_bool])
db.foo.validate() // SLOW
db.foo.getShardVersion() // only for use with sharding
UTILITIES
mongodump -d database_name -o /some/directory
mongorestore -d database_name /some/directory
EXAMPLES
Inserting Data
> j = { name: "mongo"};
{"name" : "mongo"}
> t = { x : 3 };
{ "x" : 3 }
> db.things.save(j);
> db.things.save(t);
Accessing Data from a Query
var cursor = db.things.find();
while (cursor.hasNext()) { print(tojson(cursor.next())); }
Retrieving Data with Javascript functions
db.things.find().forEach( function(x) { printjson(x);});
select * from things where name="mongo"
db.things.find({name:"mongo"}).forEach(printjson);
select * from things where x=4
db.things.find({x:4}).forEach(printjson);
select j from things where x=4
db.things.find({x:4}, {j:true}).forEach(printjson);
order by
db.things.find().sort({x:1}) // ascending
db.things.find().sort({x:-1}) // descending
limit 1
var mongo = db.things.findOne({name:"mongo"});
print(tojson(mongo));
limit(x)
db.things.find().limit(3);
regex search
db.things.find({x : /foo.*/i});
search for type
db.things.find({ x : { $type : 16 }}); // finds integer values in this field
update users set api_token = 'snafu' where _id = "fubar";
db.users.update( { "_id" : "fubar" }, { $set : { "api_token" : "snafu" } }, false );
update or insert users set api_token = 'snafu' where _id = "fubar";
db.users.update( { "_id" : "fubar" }, { $set : { "api_token" : "snafu" } }, true );
Rename all fields in a collection
db.users.update( {}, { $rename : {"old_field_name" : "new_field_name"}}, false, true);
Search This Blog
Wednesday, September 4, 2013
Mongo DB Cheetsheet
Thursday, July 4, 2013
Manage multiple Linux Users on Amazon EC2 Instance
Step 0. Login by default user, “ubuntu”:
1 | ssh -i my_key.pem ubuntu@111.111.11.111 |
Step 1. Create a new user, we will call our new user “john”:
1 | [ubuntu@ip-11-111-111-111 ~]$ sudo adduser gmsundar |
Set password for “gmsundar” by:
1 2 | [ubuntu@ip-11-111-111-111 ~]$ sudo su [root@ip-11-111-111-111 ec2-user]$ passwd gmsundar |
Add “gmsundar” to sudoer’s list by:
1 | [root@ip-11-111-111-111 ec2-user]$ visudo |
and add this to the last line:
1 | gmsundar ALL = (ALL) ALL |
Alright! We have our new user created, now you need to generate the key file which will be needed to login, like we have my_key.pem in Step 0.
Now, exit and go back to ubuntu, out of root.
Step 2. Creating the public and private keys:
1 | [ubuntu@ip-11-111-111-111 ~]$ su gmsundar |
Enter the password you created for “gmsundar” in Step 1.
1 2 3 4 5 6 7 | [gmsundar@ip-11-111-111-111 ec2-user]$ cd /home/gmsundar/ [gmsundar@ip-11-111-111-111 ~]$ ssh-keygen -b 1024 -f gmsundar -t dsa [gmsundar@ip-11-111-111-111 ~]$ mkdir .ssh [gmsundar@ip-11-111-111-111 ~]$ chmod 700 .ssh [gmsundar@ip-11-111-111-111 ~]$ cat gmsundar.pub > .ssh/authorized_keys [gmsundar@ip-11-111-111-111 ~]$ chmod 600 .ssh/authorized_keys [gmsundar@ip-11-111-111-111 ~]$ sudo chown gmsundar:ubuntu .ssh |
In the above step, gmsundar is the user we created and ubuntu is the default user group.
1 | [gmsundar@ip-11-111-111-111 ~]$ sudo chown gmsundar:ec2-user .ssh/authorized_keys |
Step 3. Now you just need to download the key called “gmsundar”
1 2 | [gmsundar@ip-11-111-111-111 ~]$ sudo cp gmsundar /home/ubuntu/ [gmsundar@ip-11-111-111-111 ~]$ sudo chmod 777 /home/ubuntu/gmsundar |
Now come to local machine’s terminal, where you have my_key.pem file and do this:
1 | scp -i my_key.pem ubuntu@111.111.11.111:/home/ubuntu/gmsundar gmsundar |
The above command will copy the key “gmsundar” to the present working directory on your local machine. Once you have copied the key to your local machine, you should delete “/home/ubuntu/gmsundar”, since it’s a private key.
Now, one your local machine chmod gmsundar to 600.
1 | chmod 600 john |
Step 4. Time to test your key:
1 | ssh -i gmsundar gmsundar@111.111.11.111 |
So, in this manner, you can setup multiple users to use one EC2 instance!!
Monday, April 15, 2013
On RHEL in FIPS Mode
Went to an excellent talk by Steve Grubb of Red Hat that went over some of the particulars of the security systems in Red Hat Enterprise Linux. This talk really collected together a lot of the information that I had been searching for. I guess it is a fairly niche market that is searching for auditing capabilities, FIPS mode, and the like, so information was fairly thin until his talk. You can find his slides here.
For me the most important information at the moment is the FIPS 140-2 mode for RHEL 5 platforms. I was aware there were efforts to make this happen, you can use the fipscheck program to verify select binary integrity on start up, OpenSSH was being built with a FIPS mode, and so on, but the slide on page 40 gave me the main command to bring this all together.
- mkinitrd –with-fips -f /boot/initrd-$(uname -r).img $(uname -r)
- Add “fips=1” to grub kernel boot line
- Reboot
Now two caveats that I know of so far: in order for fipscheck to work, prelinking must be disabled, otherwise the hashes will change every time prelinking is re-run (which happens nightly). So in order to disable prelinking on a system do the following:
- Edit /etc/sysconfing/prelink and set ‘PRELINKING=no’
- Execute ‘sudo prelink -ua’ to remove relinking, or just wait until the nightly prelinking is run and everything is cleaned up.
As well /boot has to be a separate partition on your system.
There is now a Red Hat Knowledge base article up that describes this process, sadly you have to be logged in now to see Red Hat knowledge base articles.
Wednesday, April 10, 2013
How to send SMS message in Android
In Android, you can use
SmsManager API or device’s Built-in SMS application to send a SMS message. In this tutorial, we show you two basic examples to send SMS message :- SmsManager API
SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
- Built-in SMS application
Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", "default content"); sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent);
Of course, both need SEND_SMS permission.
<uses-permission android:name="android.permission.SEND_SMS" />P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Note
The Built-in SMS application solution is the easiest way, because you let device handle everything for you.
The Built-in SMS application solution is the easiest way, because you let device handle everything for you.
1. SmsManager Example
Android layout file to textboxes (phone no, sms message) and button to send the SMS message.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textViewPhoneNo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter Phone Number : " android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/editTextPhoneNo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:phoneNumber="true" > </EditText> <TextView android:id="@+id/textViewSMS" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter SMS Message : " android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/editTextSMS" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textMultiLine" android:lines="5" android:gravity="top" /> <Button android:id="@+id/buttonSend" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Send" /> </LinearLayout>
File : SendSMSActivity.java – Activity to send SMS via
SmsManager.package com.mkyong.android; import android.app.Activity; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SendSMSActivity extends Activity { Button buttonSend; EditText textPhoneNo; EditText textSMS; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); buttonSend = (Button) findViewById(R.id.buttonSend); textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo); textSMS = (EditText) findViewById(R.id.editTextSMS); buttonSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String phoneNo = textPhoneNo.getText().toString(); String sms = textSMS.getText().toString(); try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, sms, null, null); Toast.makeText(getApplicationContext(), "SMS Sent!", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "SMS faild, please try again later!", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } }); } }
File : AndroidManifest.xml , need SEND_SMS permission.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.mkyong.android" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.SEND_SMS" /> <application android:debuggable="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".SendSMSActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
See demo :
'via Blog this'
Thursday, January 3, 2013
How to create a yum repository on RHEL/CentOS 5.x with CD/DVD or ISO images « Linux T&T
We need several packages to create yum repository, you can install them from CD/DVD disks or ISO images.
# yum install createrepo wget
# cd /mnt # createrepo .
Mount your CD/DVD or ISO images
DVD Disk or DVD ISO image
Mount your CD/DVD or ISO images
DVD Disk or DVD ISO image
* If you have DVD disk, please mount dvd-rom first, and then create yum repository:
# mkdir /mnt/dvd/
# mount /dev/cdrom /mnt/dvd/
# mount /dev/cdrom /mnt/dvd/
* If you use DVD iso, please copy it to the system, and then create yum repository:
# mkdir /mnt/dvd/
# mount -o loop /root/rhel5.1-dvd.iso /mnt/dvd
# mount -o loop /root/rhel5.1-dvd.iso /mnt/dvd
CD images
If you have multiple CD image files, you should mount all iso images and then create yum repository.
* Mount all iso images:
# mkdir -p /mnt/{1,2,3,4,5}
# mount -o loop rhel5.1-disc1.iso /mnt/1
# mount -o loop rhel5.1-disc2.iso /mnt/2
# mount -o loop rhel5.1-disc3.iso /mnt/3
# mount -o loop rhel5.1-disc4.iso /mnt/4
# mount -o loop rhel5.1-disc5.iso /mnt/5
# mount -o loop rhel5.1-disc1.iso /mnt/1
# mount -o loop rhel5.1-disc2.iso /mnt/2
# mount -o loop rhel5.1-disc3.iso /mnt/3
# mount -o loop rhel5.1-disc4.iso /mnt/4
# mount -o loop rhel5.1-disc5.iso /mnt/5
Install necessary package
* Find and install ‘createrepo’ package in /mnt directory:
# find /mnt -iname ‘createrepo*’
/mnt/dvd/Server/createrepo-0.4.11-3.el5.noarch.rpm
/mnt/dvd/Server/createrepo-0.4.11-3.el5.noarch.rpm
# rpm -ivh /mnt/dvd/Server/createrepo-0.4.11-3.el5.noarch.rpm
Create yum repository
Create metadata
Create metadata
* Create yum repository:
# cd /mnt/
# createrepo .
# createrepo .
Define yum repository
Create yum repository define file /etc/yum.repos.d/dvdiso.repo:
[MailRepo]
name=MailRepo
baseurl=file:///mnt/
enabled=1
gpgcheck=0
name=MailRepo
baseurl=file:///mnt/
enabled=1
gpgcheck=0
Test it
# yum clean all
# yum list
# yum list
If ‘yum list’ list all packages in DVD/CD disks or ISO images, it works. 
Share the repo via NFS:
Copy the yum repository define file /etc/yum.repos.d/dvdiso.repo on the second machine:
scp server1:/etc/yum.repos.d/dvd.repo /etc/yum.repos.d/[root@server1 ~]# echo "/mnt 192.168.1.0/24(ro,async)' >>/etc/exports
[root@server1 ~]# exportfs -r
Subscribe to:
Comments (Atom)