Friday, 11 March 2016

Most Importants Commands In Linux



Create System User with KeyBase Authentication :


For CentOS :

# useradd username

For Ubuntu :

#  adduser username

Generate Key :

# ssh-keygen

Provide KeyName : sysuserkey

Presse Enter --- > Press Enter

# cd /home/sysuser/
# mkdir -p sysuser/.ssh
# touch sysuser/.ssh/authorized_keys
# cat sysuserkey.pub > sysuser/.ssh/authorized_keys
chown -R sysuser:sysuser sysuser/.ssh/

Now,

# visudo

sysuser ALL=(ALL)  NOPASSWD:ALL

:wq

===============================================

To flush/Clear Cached Memory:
sync; echo 3 > /proc/sys/vm/drop_caches

crontab -e
*/10 * * *  * sync; echo 3 > /proc/sys/vm/drop_caches

http://tecadmin.net/flush-memory-cache-on-linux-server/

To free pagecache:
echo 1 > /proc/sys/vm/drop_caches

To free dentries and inodes:
echo 2 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:
echo 3 > /proc/sys/vm/drop_caches
===================================================

To verify nagios configuration file:
/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

====================================================

If GITBLIT Service down

Start it manually:
cd /var/gitblit/
java -jar gitblit.jar --baseFolder data &

====================================================

Set IP Command Line CentOS:

HWADDR=20:89:84:c8:12:8a
DEVICE="eth0"
ONBOOT=yes
TYPE=Ethernet
BOOTPROTO=static   or dhcp
IPADDR= 192.168.100.113
NETMASK=255.255.255.0
GATEWAY=192.168.0.1
DNS1=192.168.100.100
DNS2= 192.168.100.101
/etc/init.d/network restart

===================================================

PowerISO Key: hellboy
Serial  :  SKZRM-TLUPJ-LSV1R-HJDM2-IU8CS

===================================================

MySQL User Creation with full permission:

CREATE USER 'dbadmin'@'localhost' IDENTIFIED BY '#Edws4@12';
GRANT ALL PRIVILEGES ON * . * TO 'dbadmin'@'localhost';
FLUSH PRIVILEGES;

GRANT ALL PRIVILEGES ON *.* TO 'reportadmin'@'%' IDENTIFIED BY PASSWORD '#esPeHdK2';
FLUSH PRIVILEGES;

create user reportadmin@'%' identified by '#esPeHdK2';
grant all on *.* to root@'%' with grant option;
FLUSH PRIVILEGES;

To Change/ update database user permission:

update mysql.user set host='%' where user='dbadmin' and host='localhost';


MySQL Remove User Permission :

REVOKE permission ON database.table FROM 'user'@'localhost';

To check MySQL User Grant Permission :

SHOW GRANTS FOR 'testuser'@'localhost';


Create MySQL User for remote server login:

CREATE USER 'dbadmin'@'%' IDENTIFIED BY 'password';
grant all on *.* to 'nagios'@'%' with grant option;
flush privileges;
\q

====================================================

MySQL User Remote Permission with Specific IP :

GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.20.30.10' IDENTIFIED BY 'Wd7$Qts#123' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.20.30.20' IDENTIFIED BY 'Wd7$Qts#123' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.20.30.30' IDENTIFIED BY 'Wd7$Qts#123' WITH GRANT OPTION;
flush privileges;

====================================================

Create Remote User with Read-Only Permission:

CREATE USER 'bdcsync'@'%' IDENTIFIED BY '$dfde@121';
grant select on *.* to 'b2bsync'@'%';
flush privileges;
\q


use mysql;
GRANT ALL ON 'DBNAME','tablename' TO 'user@ip';
CREATE USER 'merchantdbuser'@'%' IDENTIFIED BY '$d4GwKX8@121';
grant SELECT,INSERT,UPDATE,DELETE,EXECUTE on *.* to 'merchantdbuser'@'%';
flush privileges;
\q


MySQL User Permission with Single Database:

GRANT ALL PRIVILEGES ON wom_article_management.* To 'dbmaileruser'@'localhost' IDENTIFIED BY 'ddf@121$';
=========================================================================================================

Delete MySQL User:

select user,host from mysql.user;
DROP USER 'nagios'@'%';

=================================================

To change MySQL root Password From MySQL Prompt:

use mysql;
update user set password=PASSWORD("$e(re@te@123") where User='root';
flush privileges;
\q

========================================================

How To Reset MySQL Password :

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-networking &
mysql -uroot

In MySQL:

use mysql;
update user set Password=PASSWORD('mysql@123') where user='root';
flush privileges;
quit;

service mysqld stop
service mysqld start

======================================================

Ignore MySQL Replication Normal Error On Slave Server :

STOP SLAVE;
set global sql_slave_skip_counter=1;
START SLAVE;
show slave status \G

======================================================

Delete / Purge MySQL bin log file on linux server:

Note: First check all master and slave server file location mysql-bin log file location, it shoud be updated :

Then purge old bin log files:

Purge Master Logs

If you ARE replicating, then you need to periodically RESET MASTER or PURGE MASTER LOGS to clear out the old logs as those files are necessary for the proper operation of replication. Use following command to purge master logs:


login to mysql prompt:

mysql > PURGE BINARY LOGS TO 'mysql-bin.03';

OR

$ mysql -u root -p 'MyPassword' -e "PURGE BINARY LOGS TO 'mysql-bin.03';"

OR

$ mysql -u root -p 'MyPassword' -e "PURGE BINARY LOGS BEFORE '2008-12-15 10:06:06';"

===================================================================================

Check / List Running Services on Linux:

service --status-all
service --status-all | grep ntpd
service --status-all | less

List all known services (configured via SysV)

chkconfig --list
List service and their open ports

netstat -tulpn

=======================================================

The ps command

Type the following ps command to display all running process:
# ps aux | less
Where,

    -A: select all processes
    a: select all processes on a terminal, including those of other users
    x: select processes without controlling ttys

Task: see every process on the system

# ps -A
# ps -e
Task: See every process except those running as root

# ps -U root -u root -N
Task: See process run by user vivek

# ps -u vivek

====================================================

View All MySQL user from mysql prompt:
mysql -u root -p

mysql> select user, host from mysql.user;
+------------+-----------------------+
| user       | host                  |
+------------+-----------------------+
| root       | 127.0.0.1             |
| root       | ::1                   |
| gitlab     | localhost             |
| mail       | localhost             |
| mydbuser   | localhost             |
| openfire   | localhost             |

=========================================================

Create MySQL user with all database full privilages for any host:

create user dbadmin@'%' identified by '#Edws4@12';
grant all on *.* to dbadmin@'%' with grant option;
flush privileges;

=========================================================

To check MySQL Version:
[root@namdev ~]# mysql -u root -p'mysql@123'

mysql> select version();
==========================================================

To Login Remote database server:
# mysql -h '10.20.30.10' -u dbadmin -p    
[10.20.30.10 is remote server ip & dbadmin is remote server user]
==========================================================

OpenVZ VPS Create Process:

vzctl create 102 --ostemplate centos-6-x86_64
vzctl set 102 --onboot yes --save
vzctl set 102 --ipadd 192.168.100.118 --save
vzctl set 102 --hostname itdb.example.com --save
vzctl set 102 --nameserver 192.168.100.100 --nameserver 192.168.100.102 --save
vzctl set 102 --vmguarpages 1024M --save
vzctl set 102 --oomguarpages 1024M --save
vzctl set 102 --privvmpages 1024M:1024M --save
vzctl set 102 --diskspace 40G:40G --save
vzctl set 102 --diskinodes 401859:401859 --save
vzctl start 102

================================================

How To check updates on centos:

yum check-update

===============================================

For Server information php:

<?php
phpinfo();
?>

================================================

To check mysql replication:

mysql -u root -p'wewew@te@123'
Check MySQL replication status:
SHOW MASTER STATUS;
SHOW SLAVE STATUS\G

On master database:

# show databases;
# show master status;
SHOW BINARY LOGS;

On Slave databases:

SHOW GLOBAL STATUS like 'slave_running';

To Ignore MySQL Error Replication :

STOP SLAVE;
set global sql_slave_skip_counter=1;
START SLAVE;
show slave status \G

=============================================

Change data and time:
date -s "21 April 2015 13:26:40"
cd /etc/
mv localtime localtime-bak
ln -s /usr/share/zoneinfo/Asia/Kolkata /etc/localtime

================================================

Find and Replace

:%s/WORD-To-Find-HERE/Replace-Word-Here/g    or  :%s/FindMe/ReplaceME/g
:%s/106/107/g

======================================================
# Folder Full backup 3pm and 9pm
0 15 * * * zip -r /home/backup_redmine/redmine_$(date +\%d-\%m-\%Y_\%H:\%M:\%S).zip /var/www/redmine

0 21 * * * zip -r /home/backup_redmine/redmine_$(date +\%d-\%m-\%Y_\%H:\%M:\%S).zip /var/www/redmine

* * * * 6 find /home/backup_redmine/ -mtime +5 -exec rm {} \;

================================================================

netstat -ntlp | grep LISTEN

Backup with zip folder
zip -r /opt/backup_repo_data/gitblit_$(date +'%Y%m%d').zip /var/gitblit
zip -r /opt/backup_repo_data/gitblit_$(date +'%Y%m%d').zip /var/gitblit

==============================================================

Cron for shutdown server
0 9 * * * /sbin/shutdown -h now

============================================================

Repo Install Linux:

Yum repo enable/disable:
yum --disablerepo=\* --enablerepo=rpmforge install php
yum --disablerepo=\* --enablerepo=remi-php55 install php http

yum install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

rpm -ivh http://repo.mysql.com/mysql-community-release-el6-5.noarch.rpm
yum install mysql-community-server mysql-community-client mysql-community-libs mysql-community-common

=========================================================================

Repo error: Invalid GPG Key
Error:
warning: rpmts_HdrFromFdno: Header V3 DSA/SHA1 Signature, key ID 6b8d79e6: NOKEY
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
GPG key retrieval failed: [Errno 14] Could not open/read file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag

Solution:  # rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt

========================================================

SSH Login Logs Find:

# lastlog -b 0 -t 100
# stat /var/log/wtmp
# last
# lastlog
# cat /var/log/secure |grep -i accepted
# tail -f /var/log/secure

=========================================================

MySQL Commands:

tail -n 100 /var/log/mysqld.log
show processlist;
show status like 'Conn%';
show status like '%onn%';
lsof -i :3306
SHOW GLOBAL STATUS LIKE 'aborted_connects';
SHOW GLOBAL VARIABLES LIKE 'max_connections';
SHOW GLOBAL STATUS LIKE 'max_used_connections';
SHOW GLOBAL STATUS LIKE "Handler_read%";
SHOW GLOBAL STATUS;
mysql> STATUS;

SELECT @@innodb_buffer_pool_size;

=====================================

System Check memory Logs:
atop
htop
mtop
top
ps -eo size,pid,user,command --sort -size | awk '{ hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }'

============================================================

Send mail with attachment using mutt
mutt  -s "Memory Report" namdev.rathod@firstcry.com -a /tmp/memory-logs.txt < /tmp/mailmessage.txt

========================================================

Network traffic or bandwidth monitor tools:
iptraf and iftop, nload: Monitor,Analyse Network Traffic and Bandwidth ›
yum install iptraf iftop nload

=====================================================

Shortcuts for vi editor
1.Press "G" and Directly goto Last Line of a file.
2.Press "g" and Directly goto First Line of a file.
3.Press "dd" to delete/cut the given line.
4.Press "dw" to delete the word.
5.Press "cc" to replace the word.
6.Press "yy" to copy the given line.
7.Press "p" to paste the copied line.
8.Press "i"/"a" to get into insert mode.
9.Press "o" and get newfresh line downwards.
10.Press "O" and get newfresh line Upwards.
11.Press "Esc + :wq!"to write quickly and forcefully to a file.
12.Press "Esc + u " for Undo
13.Press "Esc + r " for Redo

===============================================================

Steps to Create a bridge network connection:
1. Open /etc/sysconfig/network-scripts/ifcfg-br0
2. Add following script in that file
DEVICE=br0
NAME=br0
TYPE=Bridge
BOOTPROTO=dhcp
DELAY=0
3.Open /etc/sysconfig/network-scripts/ifcfg-eth0
4.Append the script in that file
BRIDGE=br0

=====================================================

MySQL Backup Script in Bash / Cron Job

crontab -e

# ....
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

 15 2 * * * mysqldump -u mysqluser -pmysqlpassword db_name | gzip > /var/backups/mysql/db_name_`date '+\%Y\%m\%d-\%H\%M\%S'`.sql.gz
 20 2 * * * find /var/backups/mysql/db_name* -mtime +30 -exec rm {} \;
==========================================================

OpenVZ VPS Backup
vzdump --suspend --compress --dumpdir /vz/backup/freshvps  111

==============================================================

route add -host 10.0.90.2/32 gw 10.0.90.97

===============================================

vzctl checkpoint exit code 16 issue:

modprobe vzcpt

==========================================================

URL Cron Set :

0 7 * * 1,3 /usr/bin/wget -q -O url2.log www.worldofmoms.com/mailer/get_daily_mailer

==============================================================

Edit Line with sed
sed -i '2s/.*/#*\/1 * * * * \/bin\/sh \/root\/test\/check_sync_final.sh/' /var/spool/cron/root

=====================================================================

MySQL Connection check:
show variables like '%connection%';
max_connections=10000

=================================================================

alter table wom_classified_patron_gallery change subcatid subcat int(11) not null;
desc wom_classified_patron_gallery;

===================================================================

SQLite to MySQL Conversion Database

sqlite3 /var/www/redmine/db/redmine_development.sqlite3 '.dump' | ./sqlitetomysql.py > back2.sql
========================================================================

Start OpenXen Manager
python /opt/openxenmanager/window.py &
======================================================

Windows 7 Key  -     HXCQT-RBK2C-DJ68W-DVJVD-J99FR

snmpwalk -v 2c -c public -O e localhost

======================================================

To check CPU AND HDD Tempreature
with sensor and hddtemp

yum install lm_sensors & yum install hddtemp

==================================================

How To Disable USB Ports In Ubuntu /CentOS:

sudo echo "blacklist usb-storage" >> /etc/modprobe.d/blacklist.conf

reboot machine once

From next time onwards, no one will be able to use the USB ports.
To re-enable the use of USB port, remove the added line from blacklist.conf.

Ref: http://itsfoss.com/how-to-disable-usb-ports-in-ubuntu/

=========================================================

How can I configure a service to run at startup / onboot In Ubuntu

sudo update-rc.d mysql defaults

====================================================

From the official Ubuntu LostPassword documentation:

    Reboot your computer
    Hold Shift during boot to start GRUB menu
    Highlight your image and press E to edit
    Find the line starting with "linux" and append rw init=/bin/bash at the end of that line
    Press Ctrl+X to boot.
    Type in passwd username
    Set your password.
    Type in reboot. If that doesn't work, hit Ctrl+Alt+Del

This works for Linux Mint 14, too.

====================================================

To check freepbx version:

on older system  :   cat /etc/asterisk/freepbxdistro-version
on newer systems :   cat /etc/schmooze/pbx-version


To disable rsyslog

vim /etc/rsyslog.conf
 $SystemLogRateLimitInterval 0
:wq

service rsyslog restart 
====================================

To check http connection live:

netstat | grep http | wc -l
apachetop
iptraf   -  yum install iptraf

==============================

How to Stop and Disable Firewalld on CentOS 7

systemctl disable firewalld
systemctl stop firewalld
systemctl status firewalld
systemctl enable iptables
systemctl start iptables

==============================

#Getting hard disk model and number.

hdparm -I /dev/sda
hdparm -I /dev/sda | grep Serial

======================================

If HDD File System Corrupt : superblock

sudo e2fsck -f -b 32768 -y /dev/sdb1    for partion name fdisk -l

====================================================

SAR install CentOS
yum install sysstat
chkconfig sysstat on
service sysstat start

SAR Command with Option
sar -P ALL -f /var/log/sa/sa09          <--  you can check sa09 means date we can also check back days history with  sa05 sa06 etc

cd /var/log/sa
sar -q -f sa10 | less

You can also narrow down the time period of the statistics using the -s and -e arguments. The -s argument is for the starting time and -e for the ending time. In both cases you specify the time in 24 hour format:

sar -q -s 22:00:00 -e 00:00:00 -f /var/log/sa/sa10

http://www.thegeekstuff.com/2011/03/sar-examples/

========================================================================

To Check MySQL Connection php code :

vim conn.php

<?php
$link = mysql_connect('54.169.69.182', 'fc_backenduser', 'f!4$7c4Y@123');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

:wq

BROWSE :   IP/conn.php
================================================

To check dns working or not at localhost:

dig @localhost namdev.example.net
===================================================

If HDD File System Corrupt : superblock

sudo e2fsck -f -b 32768 -y /dev/sdb1    for partion name fdisk -l
=============================================================

Check CPU Load Diagnosing High CPU utilization and memory leaks

ps -eo pcpu,pid,user,args | sort -b -k1,1n
===========================================

To check mysql time zone :
show variables like '%time_zone%';
SELECT @@global.time_zone, @@session.time_zone;
select now();

To change time zone in MySQL :
check system date and time
# date
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql -p'!P4$$#04d#'
SET GLOBAL time_zone = "Asia/Kolkata";
select now();

OR

vim /etc/my.cnf

default-time-zone='+05:30'

:wq

service mysqld restart
=====================================================

Setup IP On Ubuntu :

sysadmin@b2bmean:~$ cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto p2p1
iface p2p1 inet static
    address 192.168.0.121
    netmask 255.255.255.0
    network 192.168.0.0
    broadcast 192.168.0.255
    gateway 192.168.0.1
    # dns-* options are implemented by the resolvconf package, if installed
    dns-nameservers 10.20.30.80 8.8.8.8
    dns-search firstcry.net

:wq

/etc/init.d/networking restart
============================================

Copy Folder / Files with exclude in rsync

rsync -avz --exclude=MAILS\ IMAGES/ * sysadmin@192.168.0.87:/home/sysadmin/backup/ccshare/
============================================

No comments: