Thursday, November 17, 2016

MySql Commands!!!

This is a list of handy MySQL commands that I use time and time again. At the bottom are statements, clauses, and functions you can use in MySQL. Below that are PHP and Perl API functions you can use to interface with MySQL. To use those you will need to build PHP with MySQL functionality. To use MySQL with Perl you will need to use the Perl modules DBI and DBD::mysql.
Below when you see # it means from the unix shell. When you see mysql> it means from a MySQL prompt after logging into MySQL.
To login (from unix shell) use -h only if needed.

# [mysql dir]/bin/mysql -h hostname -u root -p
Create a database on the sql server.

mysql> create database [databasename];
List all databases on the sql server.

mysql> show databases;
Switch to a database.

mysql> use [db name];
To see all the tables in the db.

mysql> show tables;
To see database's field formats.

mysql> describe [table name];
To delete a db.

mysql> drop database [database name];
To delete a table.

mysql> drop table [table name];
Show all data in a table.

mysql> SELECT * FROM [table name];
Returns the columns and column information pertaining to the designated table.

mysql> show columns from [table name];
Show certain selected rows with the value "whatever".

mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";
Show all records containing the name "Bob" AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';
Show all records not containing the name "Bob" AND the phone number '3444444' order by the phone_number field.

mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;
Show all records starting with the letters 'bob' AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';
Show all records starting with the letters 'bob' AND the phone number '3444444' limit to records 1 through 5.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;
Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with a.

mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";
Show unique records.

mysql> SELECT DISTINCT [column name] FROM [table name];
Show selected records sorted in an ascending (asc) or descending (desc).

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;
Return number of rows.

mysql> SELECT COUNT(*) FROM [table name];
Sum column.

mysql> SELECT SUM(*) FROM [table name];
Join tables on common columns.

mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;
Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;
Change a users password from unix shell.

# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'
Change a users password from MySQL prompt. Login as root. Set the password. Update privs.

# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;
Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.

# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Set a root password if there is on root password.

# mysqladmin -u root password newpassword
Update a root password.

# mysqladmin -u root -p oldpassword newpassword
Allow the user "bob" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges;
Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges; 

or 

mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;
To update info already in a table.

mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';
Delete a row(s) from a table.

mysql> DELETE from [table name] where [field name] = 'whatever';
Update database permissions/privilages.

mysql> flush privileges;
Delete a column.

mysql> alter table [table name] drop column [column name];
Add a new column to db.

mysql> alter table [table name] add column [new column name] varchar (20);
Change column name.

mysql> alter table [table name] change [old column name] [new column name] varchar (50);
Make a unique column so you get no dupes.

mysql> alter table [table name] add unique ([column name]);
Make a column bigger.

mysql> alter table [table name] modify [column name] VARCHAR(3);
Delete unique from table.

mysql> alter table [table name] drop index [colmn name];
Load a CSV file into a table.

mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
Dump all databases for backup. Backup file is sql commands to recreate all db's.

# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql
Dump one database for backup.

# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql
Dump a table from a database.

# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
Restore database (or database table) from backup.

# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
Create Table Example 1.

mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Create Table Example 2.

mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');
MYSQL Statements and clauses
ALTER DATABASE

ALTER TABLE

ALTER VIEW

ANALYZE TABLE

BACKUP TABLE

CACHE INDEX

CHANGE MASTER TO

CHECK TABLE

CHECKSUM TABLE

COMMIT

CREATE DATABASE

CREATE INDEX

CREATE TABLE

CREATE VIEW

DELETE

DESCRIBE

DO

DROP DATABASE

DROP INDEX

DROP TABLE

DROP USER

DROP VIEW

EXPLAIN

FLUSH

GRANT

HANDLER

INSERT

JOIN

KILL

LOAD DATA FROM MASTER

LOAD DATA INFILE

LOAD INDEX INTO CACHE

LOAD TABLE...FROM MASTER

LOCK TABLES

OPTIMIZE TABLE

PURGE MASTER LOGS

RENAME TABLE

REPAIR TABLE

REPLACE

RESET

RESET MASTER

RESET SLAVE

RESTORE TABLE

REVOKE

ROLLBACK

ROLLBACK TO SAVEPOINT

SAVEPOINT

SELECT

SET

SET PASSWORD

SET SQL_LOG_BIN

SET TRANSACTION

SHOW BINLOG EVENTS

SHOW CHARACTER SET

SHOW COLLATION

SHOW COLUMNS

SHOW CREATE DATABASE

SHOW CREATE TABLE

SHOW CREATE VIEW

SHOW DATABASES

SHOW ENGINES

SHOW ERRORS

SHOW GRANTS

SHOW INDEX

SHOW INNODB STATUS

SHOW LOGS

SHOW MASTER LOGS

SHOW MASTER STATUS

SHOW PRIVILEGES

SHOW PROCESSLIST

SHOW SLAVE HOSTS

SHOW SLAVE STATUS

SHOW STATUS

SHOW TABLE STATUS

SHOW TABLES

SHOW VARIABLES

SHOW WARNINGS

START SLAVE

START TRANSACTION

STOP SLAVE

TRUNCATE TABLE

UNION

UNLOCK TABLES

USE

String Functions
AES_DECRYPT

AES_ENCRYPT

ASCII

BIN

BINARY

BIT_LENGTH

CHAR

CHAR_LENGTH

CHARACTER_LENGTH

COMPRESS

CONCAT

CONCAT_WS

CONV

DECODE

DES_DECRYPT

DES_ENCRYPT

ELT

ENCODE

ENCRYPT

EXPORT_SET

FIELD

FIND_IN_SET

HEX

INET_ATON

INET_NTOA

INSERT

INSTR

LCASE

LEFT

LENGTH

LOAD_FILE

LOCATE

LOWER

LPAD

LTRIM

MAKE_SET

MATCH    AGAINST

MD5

MID

OCT

OCTET_LENGTH

OLD_PASSWORD

ORD

PASSWORD

POSITION

QUOTE

REPEAT

REPLACE

REVERSE

RIGHT

RPAD

RTRIM

SHA

SHA1

SOUNDEX

SPACE

STRCMP

SUBSTRING

SUBSTRING_INDEX

TRIM

UCASE

UNCOMPRESS

UNCOMPRESSED_LENGTH

UNHEX

UPPER

Date and Time Functions
ADDDATE

ADDTIME

CONVERT_TZ

CURDATE

CURRENT_DATE

CURRENT_TIME

CURRENT_TIMESTAMP

CURTIME

DATE

DATE_ADD

DATE_FORMAT

DATE_SUB

DATEDIFF

DAY

DAYNAME

DAYOFMONTH

DAYOFWEEK

DAYOFYEAR

EXTRACT

FROM_DAYS

FROM_UNIXTIME

GET_FORMAT

HOUR

LAST_DAY

LOCALTIME

LOCALTIMESTAMP

MAKEDATE

MAKETIME

MICROSECOND

MINUTE

MONTH

MONTHNAME

NOW

PERIOD_ADD

PERIOD_DIFF

QUARTER

SEC_TO_TIME

SECOND

STR_TO_DATE

SUBDATE

SUBTIME

SYSDATE

TIME

TIMEDIFF

TIMESTAMP

TIMESTAMPDIFF

TIMESTAMPADD

TIME_FORMAT

TIME_TO_SEC

TO_DAYS

UNIX_TIMESTAMP

UTC_DATE

UTC_TIME

UTC_TIMESTAMP

WEEK

WEEKDAY

WEEKOFYEAR

YEAR

YEARWEEK

Mathematical and Aggregate Functions
ABS

ACOS

ASIN

ATAN

ATAN2

AVG

BIT_AND

BIT_OR

BIT_XOR

CEIL

CEILING

COS

COT

COUNT

CRC32

DEGREES

EXP

FLOOR

FORMAT

GREATEST

GROUP_CONCAT

LEAST

LN

LOG

LOG2

LOG10

MAX

MIN

MOD

PI

POW

POWER

RADIANS

RAND

ROUND

SIGN

SIN

SQRT

STD

STDDEV

SUM

TAN

TRUNCATE

VARIANCE

Flow Control Functions
CASE

IF

IFNULL

NULLIF

Command-Line Utilities
comp_err

isamchk

make_binary_distribution

msql2mysql

my_print_defaults

myisamchk

myisamlog

myisampack

mysqlaccess

mysqladmin

mysqlbinlog

mysqlbug

mysqlcheck

mysqldump

mysqldumpslow

mysqlhotcopy

mysqlimport

mysqlshow

perror

Perl API - using functions and methods built into the Perl DBI with MySQL
available_drivers

begin_work

bind_col

bind_columns

bind_param

bind_param_array

bind_param_inout

can

clone

column_info

commit

connect

connect_cached

data_sources

disconnect

do

dump_results

err

errstr

execute

execute_array

execute_for_fetch

fetch

fetchall_arrayref

fetchall_hashref

fetchrow_array

fetchrow_arrayref

fetchrow_hashref

finish

foreign_key_info

func

get_info

installed_versions


last_insert_id

looks_like_number

neat

neat_list

parse_dsn

parse_trace_flag

parse_trace_flags

ping

prepare

prepare_cached

primary_key

primary_key_info

quote

quote_identifier

rollback

rows

selectall_arrayref

selectall_hashref

selectcol_arrayref

selectrow_array

selectrow_arrayref

selectrow_hashref

set_err

state

table_info

table_info_all

tables

trace

trace_msg

type_info

type_info_all

Attributes for Handles

PHP API - using functions built into PHP with MySQL
mysql_affected_rows

mysql_change_user

mysql_client_encoding

mysql_close

mysql_connect

mysql_create_db

mysql_data_seek

mysql_db_name

mysql_db_query

mysql_drop_db

mysql_errno

mysql_error

mysql_escape_string

mysql_fetch_array

mysql_fetch_assoc

mysql_fetch_field

mysql_fetch_lengths

mysql_fetch_object

mysql_fetch_row

mysql_field_flags

mysql_field_len

mysql_field_name

mysql_field_seek

mysql_field_table

mysql_field_type

mysql_free_result

mysql_get_client_info

mysql_get_host_info

mysql_get_proto_info

mysql_get_server_info

mysql_info

mysql_insert_id

mysql_list_dbs

mysql_list_fields

mysql_list_processes

mysql_list_tables

mysql_num_fields

mysql_num_rows

mysql_pconnect

mysql_ping

mysql_query

mysql_real_escape_string

mysql_result

mysql_select_db

mysql_stat

mysql_tablename

mysql_thread_id

mysql_unbuffered_query

Monitor RDS with Nagios

This plugin is written on Python and utilizes the module boto (Python interface to Amazon Web Services) to get various RDS metrics from CloudWatch and compare them against the thresholds.


Install the package: yum install python-boto or apt-get install python-boto

Create a config /etc/boto.cfg or ~nagios/.boto with your AWS API credentials. See http://code.google.com/p/boto/wiki/BotoConfig

This plugin that is supposed to be run by Nagios, i.e. under nagios user, should have permissions to read the config /etc/boto.cfg or ~nagios/.boto.

Example:

[root@centos6 ~]# cat /etc/boto.cfg
[Credentials]
aws_access_key_id = THISISATESTKEY
aws_secret_access_key = thisisatestawssecretaccesskey

If you do not use this config with other tools such as our Cacti script, you can secure this file the following way:

[root@centos6 ~]# chown nagios /etc/boto.cfg
[root@centos6 ~]# chmod 600 /etc/boto.cfg
DESCRIPTION

The plugin provides 4 checks and some options to list and print RDS details:

RDS Status
RDS Load Average
RDS Free Storage
RDS Free Memory
To get the list of all RDS instances under AWS account:

# ./aws-rds-nagios-check.py -l
To get the detailed status of RDS instance identified as blackbox:

# ./aws-rds-nagios-check.py -i blackbox -p
Nagios check for the overall status. Useful if you want to set the rest of the checks dependent from this one:

# ./aws-rds-nagios-check.py -i blackbox -m status
OK mysql 5.1.63. Status: available
Nagios check for CPU utilization, specify thresholds as percentage of 1-min., 5-min., 15-min. average accordingly:

# ./aws-rds-nagios-check.py -i blackbox -m load -w 90,85,80 -c 98,95,90
OK Load average: 18.36%, 18.51%, 15.95% | load1=18.36;90.0;98.0;0;100 load5=18.51;85.0;95.0;0;100 load15=15.95;80.0;90.0;0;100
Nagios check for the free memory, specify thresholds as percentage:

# ./aws-rds-nagios-check.py -i blackbox -m memory -w 5 -c 2
OK Free memory: 5.90 GB (9%) of 68 GB | free_memory=8.68;5.0;2.0;0;100
# ./aws-rds-nagios-check.py -i blackbox -m memory -u GB -w 4 -c 2
OK Free memory: 5.90 GB (9%) of 68 GB | free_memory=5.9;4.0;2.0;0;68
Nagios check for the free storage space, specify thresholds as percentage or GB:

# ./aws-rds-nagios-check.py -i blackbox -m storage -w 10 -c 5
OK Free storage: 162.55 GB (33%) of 500.0 GB | free_storage=32.51;10.0;5.0;0;100
# ./aws-rds-nagios-check.py -i blackbox -m storage -u GB -w 10 -c 5
OK Free storage: 162.55 GB (33%) of 500.0 GB | free_storage=162.55;10.0;5.0;0;500.0
CONFIGURATION

Here is the excerpt of potential Nagios config:

define servicedependency{
      hostgroup_name                  mysql-servers
      service_description             RDS Status
      dependent_service_description   RDS Load Average, RDS Free Storage, RDS Free Memory
      execution_failure_criteria      w,c,u,p
      notification_failure_criteria   w,c,u,p
      }

define service{
      use                             active-service
      hostgroup_name                  mysql-servers
      service_description             RDS Status
      check_command                   check_rds!status!0!0
      }

define service{
      use                             active-service
      hostgroup_name                  mysql-servers
      service_description             RDS Load Average
      check_command                   check_rds!load!90,85,80!98,95,90
      }

define service{
      use                             active-service
      hostgroup_name                  mysql-servers
      service_description             RDS Free Storage
      check_command                   check_rds!storage!10!5
      }

define service{
      use                             active-service
      hostgroup_name                  mysql-servers
      service_description             RDS Free Memory
      check_command                   check_rds!memory!5!2
      }

define command{
      command_name    check_rds
      command_line    $USER1$/pmp-check-aws-rds.py -i $HOSTALIAS$ -m $ARG1$ -w $ARG2$ -c $ARG3$
      }

Saturday, November 12, 2016

AWS - Create VPC


1) Go to the AWS console and  Click on VPC Tab

















2) Click on Create VPC












Fill-up  the VPC details eg, VPC Name, Subnet - 172.16.0.0/16 



















3) Create Subnet











Subnet Tag, Select VPC , Available zone and all Network Range (IP )


 Create Subnet, Select Region , Add IP  Range 

 Create 1 Subnet Name: test_data_flow and region : us-east-2a, IP  Range -172.16.0.0/24
 Create 2 Subnet Name: test_backup and region : us-east-2b, IP  Range -172.16.1.0/24
 Create 3 Subnet Name: test_App and region : us-east-2c, IP  Range -172.16.2.0/24
Please find the below Subnet details4 ) Create Internet Gateway













Internet Gateway Tag


Attached ro VPC and enable internet gateway
5) Create Route Table

Select VPC and Add Tag

Ad
d Route, you get the route table details 

Add (Associate) created Subnet to route table 


If you like my post please comment and share

Install NRPE on Ubuntu and LinuxMint

Install and configure nagios nrpe client in Ubuntu with apt-get command

NRPE (Nagios Remote Plugin Executor) is used for executing Nagios plugins on remote client systems. In previous article we had described about installation of Nagios Server on Ubuntu operating system. This article will help you to install NRPE on Ubuntu 15.04, 14.04, 12.04 & LinuxMint systems.

Step 1. Install NRPE and Nagios Plugins

NRPE is available under default apt repositories of Ubuntu systems. Execute the following command to install it
$ sudo apt-get install nagios-nrpe-server nagios-plugins
Step 2. Configure NRPE

In NRPE configuration, first we need to nrpe to which nagios servers it accepts requests, For example your nagios server ip is 192.168.1.x, then add this ip to allowed hosts list. Edit NRPE configuration file /etc/nagios/nrpe.cfg and make changes like

allowed_hosts=127.0.0.1, 192.168.1.X (nagios server ip )
we can add more Nagios servers in allowed hosts by comma separated list.

Backup  /etc/nagios/nrpe.cfg file
mv /etc/nagios/nrpe.cfg /etc/nagios/nrpe.cfg_bkp
Create symlink for /usr/local/nagios/etc/nrpe.cfg to /etc/nagios/nrpe.cfg

ln -s /usr/local/nagios/etc/nrpe.cfg /etc/nagios/nrpe.cfg

Now restart NRPE service. Now its ready to listen requests from Nagios server

$ sudo /etc/init.d/nagios-nrpe-server restart
Let’s login to your Nagios server and verify that your Nagios server can communicate with NRPE service properly. Execute following command from nagios server plugin directory, and we are assuming that your nrpe client-server ip is 192.168.1.11.

# check_nrpe -H 192.168.1.11

NRPE v2.15
The output “NRPE v2.15” shows that nagios server successfully communicated with nrpe.


Step 3. Add Check Commands in NRPE

All the services check commands with the nagios plugins packages, which is by default installed in /usr/lib/nagios/plugins/ for 32 bit systems. Default installation adds few commands in configuration file. Add more commands as per your requirements like below

command[check_users]=/usr/lib/nagios/plugins/check_users -w 5 -c 10
command[check_load]=/usr/lib/nagios/plugins/check_load -w 15,10,5 -c 30,25,20
command[check_hda1]=/usr/lib/nagios/plugins/check_disk -w 20% -c 10% -p /dev/hda1
command[check_zombie_procs]=/usr/lib/nagios/plugins/check_procs -w 5 -c 10 -s Z
command[check_total_procs]=/usr/lib/nagios/plugins/check_procs -w 150 -c 200
Step 4. Start/Stop NRPE Service

Use following commands to start, stop or restart nrpe service. Each time we make any changes in configuration file required to restart service

$ sudo /etc/init.d/nagios-nrpe-server stop
$ sudo /etc/init.d/nagios-nrpe-server start
$ sudo /etc/init.d/nagios-nrpe-server restart

If you like my post please comment and share

Wednesday, November 9, 2016

AWS-Launch new Instance

1 ) Go to the AWS console and click on the EC2 Management Console 



2) Click on Launch Instance Option  

3) Choose an  Amazon Machine Image (AMI) 

















 Select Free tier only 
















4) Choose an Instance Type

















5) Configure Instance Details  
eg.Zzone, Role, VPC, Shutdown Behavior and Termination Agent Protection 

















6)  Add Storage

















7) Tag Tnstance -  Instance Name

















8)  Configure Security Group or Select Existing or  Add rules as per your requirement 

















9) Review Instance launch  ( Full Instance details)

















10) Select Existing key pair  or Create a new key pair




























11) After Launch Instance you get instance id, just check on Instance Id ( Instance Initializing)




12) Now you can find Instance details , eg. IP, VPC, Role, DNS, Status and HDD details 



















If you like my post please comment and share



Monday, November 7, 2016

AWS-AMI-image creation and Launch Instance

Go to the AWS console and check on the EC2 Management Console and Search Server that you want to create image,
1) Search IP or Instance ID


 2) Right click on server and Create Image


3) fill the Image and description and select no reboot option otherwise image is created then original server will reboot automatically   

if you want to delete attached hdd then just click on attached hdd cross mark 




 4) Find the created image details



5) How to launch Image to Instance 
Select Image ID  and click on launch 

6) After Launch Instance, Choose an  Amazon Machine Image (AMI) 

7) Configure Instance Details ,
eg.Zzone, Role, VPC, Shutdown Behavior and Termination Agent Protection  

8) Add storage

9) Tag Instance -  Instance Name

10) Configure Security Group or Select Existing or  Add rules as per your requirement  

11) Review Instance launch  ( Full Instance details)



12)  Select existing key pair  or Create a new key pair



13)  After Launch Instance you get instance id, just check on Instance id ( Instance Initializing)



14)  Now you can find Instance details , eg. IP, VPC, Role, DNS, Status and HDD details 


If you like my post please comment and share

Wednesday, October 5, 2016

Troubleshooting of Linux Issues Part - 1

1) SVN

1.  check permission
2.  password less user
3.  user password expiry details
4.  check owner and group
5.  check scripts and script permission , owner & group
6.  check tortoise version
7.  verify subversion version
8.  check repository path and permission, owner permission
9.  telnet subversion 3690
10 ping subversion
11 check repo size ( same time repo size will 40 gb so you get error a time of check out )
12 Performing a simple "svn cleanup" followed by an "svn update" again will solve your problem
13 check password less ssh with both side
14 reset password and try
15 check svn port
16 check user add or not under svn

2) how to check memory utilization of all process 

ps aux  | awk '{print $6/1024 " MB\t\t" $11}'  | sort -n

 ps aux|awk '{print $6/1024 " MB\t\t" $11}'| sort -n|grep redis

 ps aux|awk '{print $6/1024 " MB\t\t" $11}'| sort -n|grep httpd

ps -eo pcpu,pid,user,args | sort -k1 -r | head -10

ps aux | sort -nrk 3,3 | head -n 5

watch "ps aux | sort -nrk 3,3 | head -n 5"

ps -Ao user,uid,comm,pid,pcpu,tty --sort=-pcpu | head -n 6

ps -eo pcpu,pid,user,args --no-headers| sort -t. -nk1,2 -k4,4 -r |head -n 5


The following command will show the list of top processes ordered by RAM and CPU use in descendant form (remove the pipeline and head if you want to see the full list):

ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head
Brief explanation of above options used in above command.

The -o (or –format) option of ps allows you to specify the output format. A favorite of mine is to show the processes’ PIDs (pid), PPIDs (pid), the name of the executable file associated with the process (cmd), and the RAM and CPU utilization (%mem and %cpu, respectively).

Additionally, I use --sort to sort by either %mem or %cpu. By default, the output will be sorted in ascendant form, but personally I prefer to reverse that order by adding a minus sign in front of the sort criteria.

To add other fields to the output, or change the sort criteria, refer to the OUTPUT FORMAT CONTROL section in the man page of ps command.


3) Check URL Logs 

log path :  /usr/local/apache/log

 grep "03/Nov/2016" access-2016-11-03.log | cut -d[ -f2 | cut -d] -f1 | awk -F: '{print $2":00"}' | sort -n | uniq -c

cat access-2016-11-03.log | grep 03/Nov/2016:19 | awk {'print $4,$9'}

check date and time vise log and search as per requirement 
cat access.log | grep 17/Nov/2016 | awk {'print $4,$9'}|grep 200|wc -l


4) Delete multiple files through awk command in linux

ls -lrth|egrep -v "Jul 27"|awk {'print $9'}|xargs rm -rfv
find . -type f -mtime +30 -exec rm -f {} +

5) with out stop running process run under background

used nohup before binery and & in last
example:
nohun clouchDb start &


6) How to check DNS TTL Value
nslookup -type=soa <domain>
nslookup -type=soa savan.com

nslookup -type=A -debug <domain>
nslookup -type=A -debug savan.com


7 ) Data Recovery Open Source Tool!!

http://www.cgsecurity.org/wiki/TestDisk

8) Find command

find / -name tomcat.sh -type f ------------to search file
find -type d -exec chmod 775 {} ; -------- to change file permission
find -type f -exec chmod 664 {} ;

9) Using the locate command

locate -i springframework
locate tomcat.sh

10) hoe to check only sleeping process

ps -e S
ps -eo pid,cmd,etime

11) How-to-resolve-Nagios-Error:Could-not-read-object-configuration-data

yum groupinstall "development tools"

change permissions
chown -R nagios:apache /var/log/nagios
chown -R nagios:apache /var/log/nagios/nagios.log

service nagios restart
service httpd restart

12 ) Set number in text Configuration file (permanent)

To make the setting permanent, add the following line to /etc/vimrc or ~/.vimrc using your favorite text editor
set number

Vim will read the configuration file every time it's started, and will display the line numbers.