Shell Common Operation command series in Linux: Service operation

Source: Internet
Author: User
Tags findone flush mongodb server sql show tables mysql commands mysql insert mongodump mongorestore

Basic operation of the service


/etc/init.d/sendmail Start # Launch service


/etc/init.d/sendmail Stop # Close Service


/etc/init.d/sendmail Status # View the current status of the service


/date/mysql/bin/mysqld_safe--user=mysql & # start MySQL background run


vi/etc/rc.d/rc.local # Boot Boot execution can be used for boot up scripts


/ETC/RC.D/RC3.D/S55SSHD # power-on start and shutdown shutdown Service Connection # s boot start k shutdown Stop 55 level followed by service name


Ln-s-F/DATE/HTTPD/BIN/APACHECTL/ETC/RC.D/RC3.D/S15HTTPD # to connect the launcher script to the boot directory


IPVSADM-LN # LVS View back-end load machine concurrency


Ipvsadm-c # LVs Purge rule


XM List # View Xen Virtual Host list


Virsh # Virtualization (XENKVM) management tools Yum Groupinstall virtual*


./bin/httpd-m # View httpd loading module


Httpd-t-D dump_modules # RPM Package httpd View Load module


echo Content | /bin/mail-s "title" Inbox-F sender # Send mail


"' echo" content "|iconv-f utf8-t gbk '" | /bin/mail-s "' echo" title "|iconv-f utf8-t GBK" Inbox # Resolve message garbled


/usr/local/nagios/bin/nagios-v/usr/local/nagios/etc/nagios.cfg # detection Nagios configuration file

Chkconfig Common operations


Chkconfig Service Name On|off|set # set up a non-standalone service reboot state


Chkconfig--level httpd off # Let service not start automatically


Chkconfig--level httpd on # Let the service start automatically 35 refers to the run level


Chkconfig--list # View the startup status of all services


Chkconfig--list |grep httpd # View the startup status of a service


chkconfig–-list [Service Name] # View the status of the service

HTTPD Basic Operations
Compilation parameters
# so module is used to provide the Apache core module supported by DSO
# If the compilation contains any DSO modules, the MOD_SO will be automatically included in the core.
# If you want the core to be able to load DSO, but do not actually compile any DSO module, you need to explicitly specify the "--enable-so=static"

./configure--prefix=/usr/local/apache--enable-so--enable-mods-shared=most--enable-rewrite--enable-forward # Instance compilation

--with-mpm=worker # has been run by worker mode


--WITH-APXS=/USR/LOCAL/APACHE/BIN/APXS # make Apache dynamic module DSO RPM package Httpd-devel #编译模块 apxs-i-a-c mod_foo.c


--ENABLE-SO # So Apache can support DSO mode


--enable-mods-shared=most # Tell the compiler to dynamically compile all standard modules into the DSO module


--enable-rewrite # support Address rewrite feature


--enable-module=most # Use most to compile modules that are not commonly used, not in the default common modules


--enable-mods-shared=all # means to dynamically load all modules, and if-shared is removed, all modules are statically loaded


--enable-expires # can add file expiration limit, effectively reduce server pressure, cached in the client, the validity period will not access the server again, unless press F5 refresh, but also cause the file update is not timely


--enable-deflate # compression, Web page can achieve 40% compression, save bandwidth cost, but the CPU pressure will be a little improved


--enable-headers # file header information overwrite, compression function required


--disable-module # Disables module modules (for basic modules only)


--enable-module=shared # Compiles module to DSO (available for all modules)


--enable-mods-shared=module-list # will compile all the modules in Module-list into DSO (available for all modules)


--enable-modules=module-list # The Module-list is statically connected to the core (available for all modules)


# The above module-list can be:


1.--enable-mods-shared= ' headers rewrite DAV ' by using quotation marks to delimit the list of modules separated by a space


2, "most" (most modules)--enable-mods-shared=most


3, "All" (all modules)

HTTP forwarding Configuration
#针对非80端口的请求处理
Rewritecond%{server_port}!^80$
Rewriterule ^/(. *) http://fully.qualified.domain.name:%{server_port}/$1 [l,r]

Rewritecond%{http_host} ^ss.aa.com [NC]
Rewriterule ^ (. *) http://www.aa.com/so/$1/0/p0? [l,r=301]
#RewriteRule only deal with the former, so we'll keep the post.
#在转发后地址后加? rewriterule reserved characters can be canceled
#R的含义是redirect, that is, redirect, the request will no longer be Apache to the back-end processing, but directly back to the browser to redirect the jump. 301 is the return of the HTTP status code, you can refer to the HTTP RFC documents, jump is 3XX.
#L是last, the last rewrite rule, if a request is hit by this rule, it will not continue to match the other rules again.

MySQL Common operations


MySQL Source installation


Groupadd MySQL


Useradd mysql-g mysql-m-s/bin/false


Tar zxvf mysql-5.1.71.tar.gz


CD mysql-5.1.71


./configure--prefix=/usr/local/mysql


--with-client-ldflags=-all-static


--with-mysqld-ldflags=-all-static


--with-mysqld-user=mysql


--with-extra-charsets=all


--with-unix-socket-path=/var/tmp/mysql.sock


Make && make install


# Generate MySQL user database and table files, enter in the installation package


scripts/mysql_install_db--user=mysql


VI ~/.BASHRC


Export path= "$PATH:/usr/local/mysql/bin"


# configuration file, with Large,medium,small three, select according to machine performance


CP SUPPORT-FILES/MY-MEDIUM.CNF/ETC/MY.CNF


CP Support-files/mysql.server/etc/init.d/mysqld


chmod 700/etc/init.d/mysqld


Cd/usr/local


chmod 750 Mysql-r


CHGRP MySQL Mysql-r


Chown MySQL Mysql/var-r


Cp/usr/local/mysql/libexec/mysqld Mysqld.old


Ln-s/usr/local/mysql/bin/mysql/sbin/mysql


Ln-s/usr/local/mysql/bin/mysqladmin/sbin/mysqladmin


Ln-s-F/USR/LOCAL/MYSQL/BIN/MYSQLD_SAFE/ETC/RC.D/RC3.D/S15MYSQL5


Ln-s-F/USR/LOCAL/MYSQL/BIN/MYSQLD_SAFE/ETC/RC.D/RC0.D/K15MYSQL5

MySQL Common commands
./mysql/bin/mysqld_safe--user=mysql & # start MySQL service
./mysql/bin/mysqladmin-uroot-p-S./mysql/data/mysql.sock shutdown # Stop MySQL service
Mysqlcheck-uroot-p-S Mysql.sock--optimize--databases account # Check, fix, optimize MyISAM table
Mysqlbinlog slave-relay-bin.000001 # View binary log (error plus absolute path)
Mysqladmin-h myhost-u root-p Create dbname # Creating a Database

Flush privileges; # Refresh


show databases; # Show All databases


Use dbname; # Open Database


Show tables; # Displays all tables in the selected database


DESC tables; # View Table Structure


drop database name; # Delete Database


drop table name; # Delete Table


Create database name; # Create a database


Select Column name from table name; # query


Show grants for REPL; # View User Rights


Show Processlist; # view MySQL Process


Select User (); # View All Users


show slave statusg; # View master/slave status


Show variables; # View all parameter variables


Show Table Status # View the engine status of a table


drop table if exists user # table exists delete


CREATE table if not EXISTS user # table does not exist


Select Host,user,password from user; # Query user permissions First use MySQL


Create TABLE ka (ka_id varchar (6), Qianshu int); # Create a table


Show VARIABLES like ' character_set_% '; # View the setting of the system's character set and sorting method


Show variables like '%timeout% '; # View timeout (wait_timeout)


Delete from user where user= '; # Delete Empty users


Delete from user where user= ' sss ' and host= ' localhost '; # Delete User


ALTER TABLE mytable ENGINE = MyISAM; # Change the storage engine used by existing tables


Show Table STATUS from library name where name= ' table name '; # query Table engine


CREATE TABLE InnoDB (id int, title char ()) ENGINE = InnoDB # Creating tables specifying the type of storage engine (MyISAM or InnoDB)


Grant replication slave on *.* to ' user ' @ '% ' identified by ' password '; # Create a master-slave replication user


ALTER TABLE player ADD INDEX Weekcredit_faction_index (Weekcredit, faction); # Add Index


ALTER TABLE name add column accountid (column name) int (one) not null (field is not null); # Insert Field


Update host set monitor_state= ' Y ', hostname= ' Xuesong ' where ip= ' 192.168.1.1 '; # Update Data

Create a MySQL self-added table
CREATE table Oldboy (ID integer PRIMARY KEY auto_increment, name CHAR not NULL, age INTEGER, sex CHAR (15)); # Create a self-added table
Insert into Oldboy (name,age,sex) VALUES (%s,%s,%s) # self-inserting data

Login to MySQL command
# Format: mysql-h host address-u user name-P user Password
Mysql-h110.110.110.110-p3306-uroot-p
Mysql-uroot-p-s/data1/mysql5/data/mysql.sock-a--DEFAULT-CHARACTER-SET=GBK

Shell execute MySQL command
Mysql-u root-p ' 123 ' test< File.sql # Execute the statements in the SQL file for the specified library, the benefit does not need to escape special symbols, a statement can wrap. Do not specify library execution
Mysql-u$username-p$passwd-h$dbhost-p$dbport-a-E "
Use $dbname;
Delete from data where date= (' $date 1 ');
"# Execute multiple MySQL commands
Mysql-uroot-p-S Mysql.sock-e "Use Db;alter Table gift add column AccountId int (one) not null;flush privileges;" # no login mysql insert field

Back up the MySQL database


Mysqldump-h host-u root-p--default-character-set=utf8 dbname # does not include the library name, the restore needs to first create the library, in use


Mysqldump-h host-u root-p--database--default-character-set=utf8 dbname &gt;dbname_backup.sql # includes library name, restore does not need to create library


/bin/mysqlhotcopy-u Root-p # mysqlhotcopy can only back up the MyISAM engine


Mysqldump-u Root-p-S mysql.sock--default-character-set=utf8 dbname table1 table2 &gt;/data/db.sql # Backup table


mysqldump-uroot-p123-d db &gt; Database.sql # Backup database structure


Innobackupex--user=root--password= ""--defaults-file=/data/mysql5/data/my_3306.cnf--socket=/data/mysql5/data/ Mysql.sock--slave-info--stream=tar--tmpdir=/data/dbbackup/temp/data/dbbackup/2&gt;/data/dbbackup/dbbackup.log | Gzip 1&gt;/data/dbbackup/db50.tar.gz # Xtrabackup backup needs to be installed separately software advantages: fast, low pressure, can directly restore master-slave replication

Restore MySQL Database
Mysql-h host-u root-p dbname < Dbname_backup.sql
SOURCE path. SQL # Restore SQL files after landing MySQL

assigning permissions to MySQL


# Specify IP: $IP native: localhost all IP addresses:% # usually specify multiple


Grant all on zabbix.* to user@ "$IP"; # grant permissions to existing accounts


Grant SELECT on database.* to user@ "%" identified by "passwd"; # Give query permission (no user, create directly)


Grant all privileges on database.* to user@ the "$IP" identified by ' passwd '; # Assign all permissions to the specified IP (do not allow permissions to other users on the current library)


Grant all privileges on database.* to user@ "localhost" identified by ' passwd ' with GRANT option; # Assign all permissions to the local user (allow permissions to other users on the current library)


Grant SELECT, INSERT, UPDATE, delete on database.* to user@ ' IP ' identified by ' passwd '; # Open Management Operation instructions


Revoke all in *.* from User@localhost; # Reclaim Permissions

MySQL User change password
Update user set Password=password (' passwd ') where user= ' root '
mysqladmin-u root password ' xuesong '

MySQL Reset after forgetting password
Cd/data/mysql5
/data/mysql5/bin/mysqld_safe--user=mysql--skip-grant-tables--skip-networking &
Use MySQL;
Update user set Password=password (' 123123 ') where user= ' root ';

MySQL master-slave replication failure recovery

            slave stop;
            Reset Slave;
            Change Master to master_host= ' 10.10.10.110 ' , master_port=3306,master_user= ' Repl ', master_password= ' repl ', master_log_file= ' master-bin.000010 ', Master_log_pos =107,master_connect_retry=60;
            slave start;

SQL statement uses variables
            use Xuesong;
            Set @a=concat (' My ', Weekday (Curdate ()));     # Combined time variable
            set @sql: = Concat (' CREATE TABLE IF not EXISTS ', @a, ' (ID INT (one) not NULL ');   # Combine SQL statements
     &nb sp;      Select @sql;                     # View Statements
             prepare create_tb from @sql;    # prepare
             Execute create_tb;               # executes

detecting MySQL Master-slave Replication latency
1. Update a timeout value in the main library from the time the library is scheduled to execute
2, at the same time out of the library from the timeout value comparison to determine the delay from the library and the main library

MySQL Slow query
Turn on slow query log

                log-slow-queries= /var/lib/mysql/slowquery.log       # Specifies the location of the log file, which can be null, and the system will give a default file Host_name-slow.log
                long_query_time= 2                      # Records over time, defaults to 10s
                 log-queries-not-using-indexes         # Log down without using the index query, Depending on the situation, you can decide whether to open   do not add
                 log-long-format                        # If set, all queries that do not use the index will also be logged     can not add

Mysqldumpslow Slow Query Log view

-S # is the order, including the code, mainly C,t,l,r and Ac,at,al,ar, according to the number of query, time, lock time and the number of records returned to order, preceded by a in reverse


-T # is the meaning of top N, which is to return the number of previous data


G # behind can write a regular matching pattern, case insensitive


Mysqldumpslow-s c-t Host-slow.log # 20 SQL statements with the highest number of visits


Mysqldumpslow-s r-t Host-slow.log # returns up to 20 SQL for recordsets


Mysqldumpslow-t 10-s t-g "left join" Host-slow.log # Follow the time to return to the top 10 SQL statements containing a left-hand connection


Show global status like '%slow% '; # See how many slow queries this session has now


Show variables like '%slow% '; # See if the slow query log is turned on, if Slow_query_log and Log_slow_queries appear on, the slow query log for the server is turned on


Show variables like '%long% '; # View Timeout valve value


Desc SELECT * from Wei where text= ' Xishizhaohua ' G; # Scan the entire table Tepe:all did not use the index Key:null


Create index Text_index on Wei (text); # Create an index

MongoDB Common operations
First, start
# Do not start authentication
./mongod--port 27017--fork--logpath=/opt/mongodb/mongodb.log--logappend--dbpath=/opt/mongodb/data/
# Start Authentication
./mongod--port 27017--fork--logpath=/opt/mongodb/mongodb.log--logappend--dbpath=/opt/mongodb/data/--auth

# configuration file Mode start


Cat/opt/mongodb/mongodb.conf


PORT=27017 # port number


Fork=true # runs as a daemon, creating a server process


Auth=true # Open user authentication


Logappend=true # Log in Append mode


Logpath=/opt/mongodb/mongodb.log # Log output file path


dbpath=/opt/mongodb/data/# Database path


Shardsvr=true # setting is fragmented


Maximum number of connections for the maxconns=600 # database


./mongod-f/opt/mongodb/mongodb.conf


# Other parameters


BIND_IP # binding IP using MONGO login needs to specify corresponding IP


Journal # Open Log function, reduce the recovery time of single machine failure, replace Dur parameter


Syncdelay # System Sync Refresh Disk Time, default 60 seconds


DIRECTORYPERDB # Separate directory for each DB, recommended settings. Similar to MySQL standalone table space


Repairpath # Temporary directory when repair is executed. If the journal is not turned on, an abnormal reboot occurs and the repair operation must be performed


# MongoDB There is no parameter to set the memory size. Using the OS mmap mechanism to cache data files is very efficient when the amount of data is not more than memory. Data volume exceeding system available memory affects write performance

Second, close
# method One: Login MongoDB
./mongo
Use admin
Db.shutdownserver ()

# Method: Kill transmission signal can be both
Kill-2 PID
Kill-15 PID

Third, open authentication and user management


./mongo # Log In first


Use admin # Switch to admin library


Db.adduser ("root", "123456") # Create User


Db.adduser (' Zhansan ', ' Pass ', true) # if the user's readonly is true then the user can only read the data, add a readonly user Zhansan


./mongo 127.0.0.1:27017/mydb-uroot-p123456 # Log on again, only log on to the user's library


#虽然是超级管理员, but admin cannot log in to other databases directly, otherwise the error


#Fri Nov 15:03:21.886 error:18 {code:18, ok:0.0, errmsg: "Auth Fails"} at src/mongo/shell/db.js:228


Show Collections # View link status log on again use the following command to display an error without authorization


Db.system.users.find (); # View Create user Information


Db.system.users.remove ({User: "Zhansan"}) # Delete user


#恢复密码只需要重启mongodb without--auth parameters

Four, Login
192.168.1.5:28017 # HTTP Login to view status
./mongo # Open Test library after default login
./mongo 192.168.1.5:27017/databasename # Connect directly to a library does not exist then create a boot certification need to specify a corresponding library to log on

V. View status


#登录后执行命令查看状态


Db.runcommand ({"Serverstatus": 1})


GlobalLock # Indicates how long the global write lock is consuming the server (microseconds)


MEM # contains the amount of data that the server memory maps, the virtual memory of the server process and the footprint of the resident memory (MB)


Indexcounters # represents the number of times a B-tree is in disk retrieval (misses) and memory retrieval (hits). If these two ratios start to rise, consider adding memory.


Backgroudflushing # indicates how many times the background has been done fsync and how much time has been spent


Opcounters # contains the number of times each major collision


Asserts # counts the number of assertions


#状态信息从服务器启动开始计算, if too large will reset, send reset, all the count will be reset, asserts in the Roolovers value increase


#mongodb自带的命令


./mongostat


Insert #每秒插入量


Query #每秒查询量


Update #每秒更新量


Delete #每秒删除量


Locked #锁定量


QR|QW #客户端查询排队长度 (Read | write)


Ar|aw #活跃客户端量 (Read | write)


Conn #连接数


Time #当前时间

Six, commonly used orders


Db.listcommands () # All commands supported by the current MongoDB (you can also query all commands by running the command Db.runcommand ({"Listcommands": ' 1})


Db.runcommand ({"Buildinfo": 1}) # Returns information about the version number of the MongoDB server and the server OS.


Db.runcommand ({"Collstats": Collection name}) # returns the statistics for the collection, including data size, allocated storage space size, index size, and so on.


Db.runcommand ({"DISTINCT": Collection name, key: Key, "query": Query document}) # returns all the different values of the specified key for all documents in a particular document that match the criteria specified in the query document.


Db.runcommand ({"Dropdatabase": 1}) # Clears the information for the current database, including deleting all collections and indexes.


Db.runcommand ({"IsMaster": 1}) # Check whether this server is a primary server or a server.


Db.runcommand ({"Ping": 1}) # Check that the server link is normal. The command returns immediately, even if the server is locked.


Db.runcommand ({"Repairedatabase": 1}) # Repairs and compresses the current database, which can be time-consuming if the database is particularly large.


Db.runcommand ({"Serverstatus": 1}) # View management statistics for this server.


# Some commands must be run under the Admin database, following two commands:


Db.runcommand ({"Renamecollection": Collection name, "to": Collection name}) # to rename the collection, note that the full collection namespace of the two collection names, such as Foo.bar, represents the collection bar under Database foo.


Db.runcommand ({"ListDatabases": 1}) # list all databases on the server

Vii. Process Control


Db.currentop () # View Active process


Db. $cmd. Sys.inprog.findOne () # View the active process as above


OPID # operation Process number


OP # action type (query update)


NS # namespace, which object the operation is


Query # If the type of operation is an inquiry, the specific query content will be displayed here


The type of the LockType # Lock, indicating whether it is a read or write lock


Db.killop (opid value) # End Process


Db. $cmd. Sys.killop.findOne ({op:opid value}) # End Process

Viii. Backup Restore


./mongoexport-d test-c t1-o t1.dat # Export JSON format


-C # indicates the Export collection


-D # using libraries


./mongoexport-d test-c t1-csv-f num-o t1.dat # export CSV format


-csv # indicates export CSV format


-F # Indicate which cases need to be exported

            Db.t1.drop ()                      # Delete data after login
            /mongoimport-d test-c t1-file t1.dat                             # mongoimport Restore JSON format
            /mongoimport-d test-c t1-type csv--headerline-file t1.dat    # mongoimport restore CSV format number According to the
               --headerline                 # indicates that the first row is not imported because the first row is a column name

           /mongodump-d Test-o/bak/mongodump                 # Mongodump Data backup
            /mongorestore-d Test--drop/bak/mongodump/*        # mongorestore Restore
                --drop      #恢复前先删除
             db.t1.find ()     #查看

            # mongodump can keep backups, but the city has the ability to get real-time data views, Use the Fsync command to copy data directories at run time and not corrupt data
            Fsync forces the server to write data from all buffers to disk. With lock also blocks further writes to the database until the lock is released
             # Backup is backed up from the library, does not delay read and write, and guarantees real-time snapshot backups
            Db.runcommand ({"Fsync": 1, "Lock": 1})    # Perform force update and write lock
             db. $cmd. Sys.unlock.findOne ()           # unlock
            db.currentop ()                          # See if unlocking is normal

Nine, Fix
            # When a power outage or other failure causes an abnormal shutdown, some data corruption is lost
           /mongod--repair       # Repair Action: Add--repair to the
            # Repair Process when starting: Export all documents, Then import immediately, ignoring the invalid document. Rebuild the index when finished. Long time, discard corrupted document
            # Repair Data can also play a role in compressing the database
             db.repairdatabase ()     # MongoDB in operation can use RepairDatabase to repair the currently used database
            {" RepairDatabase ":1}   # via driver

10, Python uses MongoDB
            easy_install Pymongo       # installation (python2.7+)
             Import Pymongo
            Connection=pymongo. Connection (' localhost ', 27017)    # Create a connection
             db = connection.test_database                       # switch Database
             collection = db.test_collection                     # Get Collection
             # DB and collection are both created in a delay, and the

is actually created when the document is added.

Document Add, _ID automatically created


Import datetime


Post = {"Author": "Mike",


"Text": "My A-blog post!",


"Tags": ["MongoDB", "Python", "Pymongo"],


"Date": Datetime.datetime.utcnow ()}


Posts = db.posts


Posts.insert (POST)


ObjectId (' ... ')

BULK INSERT


New_posts = [{"Author": "Mike",


"Text": "Another post!",


"Tags": ["Bulk", "insert"],


"Date": Datetime.datetime (2009, 11, 12, 11, 14)},


{"Author": "Eliot",


"title": "MongoDB is Fun",


"Text": "and Pretty easy Too!",


"Date": Datetime.datetime (2009, 11, 10, 10, 45)}]


Posts.insert (new_posts)


[ObjectId (' ... '), ObjectId (' ... ')]


Get all Collection


Db.collection_names () # equivalent to the SQL show tables


Get a single document


Posts.find_one ()

Querying multiple documents
For post in Posts.find ():
Post

Conditional query
Posts.find_one ({"Author": "Mike"})

Advanced Query
Posts.find ({"date": {"$lt": "D"}}). Sort ("author")

Number of statistics
Posts.count ()

Add index
From Pymongo import Ascending, descending
Posts.create_index ([("Date", descending), ("Author", Ascending)]

To view the performance of a query statement


Posts.find ({"date": {"$lt": "D"}}). Sort ("Author"). Explain () ["Cursor"]


Posts.find ({"date": {"$lt": "D"}}). Sort ("Author"). Explain () ["nscanned"]


JDK Installation


chmod 744 Jdk-6u24-linux-x64.bin


./jdk-6u24-linux-x64.bin


Vi/etc/profile # Add Environment variables


Export java_home=/usr/java/jdk1.6.0_24


Export classpath=.: $JAVA _home/jre/lib/rt.jar: $JAVA _home/lib/dt.jar: $JAVA _home/lib/tools.jar


Export path= $PATH: $JAVA _home/bin


. /etc/profile


JPS-ML # view Java processes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.