Docker-MySql — 使用mysqldump 命令备份导出mysql容器中的结构数据

1. 查看当前启动的mysql运行容器

docker ps   

2. 使用以下命令备份导出数据库中的所有表结构和数据

docker exec -it  mysql mysqldump -uroot -p123456 paas_portal > /cloud/sql/paas_portal.sql  

3.只导数据不导结构

mysqldump -t 数据库名 -uroot -p > xxx.sql 
docker exec -it mysql mysqldump -t -uroot -p123456 paas_portal >/cloud/sql/paas_portal_dml.sql  

4. 只导结构不导数据

mysqldump --opt -d 数据库名 -u root -p > xxx.sql 
docker exec -it mysql mysqldump  --opt -d   -uroot -p123456 paas_portal >/cloud/sql/paas_portal_ddl.sql   

5. 导出特定表的结构

mysqldump -uroot -p -B 数据库名 --table 表名 > xxx.sql
docker exec -it mysql mysqldump -uroot -p -B paas_portal --table user > user.sql  

这是工作中用到的,记录下来,以供学习参考

MySQL 5.7并发复制和mysqldump相互阻塞引起的复制延迟

本来MySQL BINLOG和SHOW PROCESSLIST命令属于八竿子打不着的两个事务,但在最近故障排查中,发现主库和从库已经存在很严重的复制延迟,但从库上显示slave_behind_master值为0,复制SQL线程与备份线程之间相互阻塞,但未报死锁。

在从库上执行SHOW PROCESSLIST发现复制的SQL线程等待锁,而等待SQL的WHERE条件竟然是类似于WHERE C1=’ABC’ AND C2>’2018-03-01′ AND C2<‘2018-03-26’ 这种个范围查询,第一时间想到就是怎么是个基于STATEMENT的复制,不科学啊,我们生产环境统一使用基于ROW格式的复制,难道研发私自修改回话级别的复制格式?

使用MySQL Binlog导出日志一看:

未分类

发现真错怪研发同事啦,rbr_only=yes说明基于ROW格式进行复制,“SET TRANSACTION ISOLATION LEVEL READ COMMITTED”也是基于行格式复制的典型特征之一,last_committed和sequence_number用于MySQL 5.7版本中的并发复制,row_query后跟的是在主库上执行的原始SQL,也就是我们在从库SHOW PROCESSLIST中看到的SQL,但实际上从库执行的还是BINLOG部分,该BINLOG可以直接可以直接直接在从库上执行,也可以解析成一行行的数据DML操作,BINLOG部分如下:

未分类

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

另外一个很有意思的问题,如果在从库上运行mysqldump进行备份,且从库上使用并行复制,会导致备份和复制相互阻塞:

未分类

在上面的阻塞中,多个SQL线程与备份线程相互之间阻塞,且MySQL无法有效检测出死锁环路而触发死锁的回滚机制,导致复制线程和备份作业相互hang住,需要DBA进行干预(取消备份或停止复制),在复制SQL线程被hang住期间,复制的IO线程仍可以正常工作接受到主库的Binlog信息,但slave_behind_master并不会随之增大,如果仅通过监控slave_behind_master值来判断主从复制延迟,则会导致延迟监控存在严重漏洞,因此在监控复制延迟时,除监控slave_behind_master值外,还需要监控主库binlog位置点和从库执行的binlog位置点。

MySQL数据库INNODB表损坏修复处理过程分享

##状况描述

突然收到MySQL报警,从库的数据库挂了,一直在不停的重启,打开错误日志,发现有张表坏了。innodb表损坏不能通过repair table 等修复myisam的命令操作。现在记录下解决过程,下次遇到就不会这么手忙脚乱了。

处理过程

一遇到报警之后,直接打开错误日志,里面的信息:

InnoDB: Database page corruption on disk or a failed InnoDB: file read of page 30506. InnoDB: You may have to recover from a backup. 130509 20:33:48 InnoDB: Page dump in ascii and hex (16384 bytes): ##很多十六进制的代码 …… …… InnoDB: End of page dump 130509 20:37:34 InnoDB: Page checksum 1958578898, prior-to-4.0.14-form checksum 3765017239 InnoDB: stored checksum 3904709694, prior-to-4.0.14-form stored checksum 3765017239 InnoDB: Page lsn 5 614270220, low 4 bytes of lsn at page end 614270220 InnoDB: Page number (if stored to page already) 30506, InnoDB: space id (if created with >= MySQL-4.1.1 and stored already) 19 InnoDB: Page may be an index page where index id is 54 InnoDB: (index "PRIMARY" of table "maitem"."email_status") InnoDB: Database page corruption on disk or a failed InnoDB: file read of page 30506. InnoDB: You may have to recover from a backup. InnoDB: It is also possible that your operating InnoDB: system has corrupted its own file cache InnoDB: and rebooting your computer removes the InnoDB: error. InnoDB: If the corrupt page is an index page InnoDB: you can also try to fix the corruption InnoDB: by dumping, dropping, and reimporting InnoDB: the corrupt table. You can use CHECK InnoDB: TABLE to scan your table for corruption. InnoDB: See also http://dev.mysql.com/doc/refman/5.5/en/forcing-innodb-recovery.html InnoDB: about forcing recovery. InnoDB: A new raw disk partition was initialized or InnoDB: innodb_force_recovery is on: we do not allow InnoDB: database modifications by the user. Shut down InnoDB: mysqld and edit my.cnf so that newraw is replaced InnoDB: with raw, and innodb_force_... is removed. 130509 20:39:35 [Warning] Invalid (old?) table or database name '#sql2-19c4-5'

从错误日志里面很清楚的知道哪里出现了问题,该怎么处理。这时候数据库隔几s就重启,所以差不多可以说你是访问不了数据库的。所以马上想到要修复innodb表了。以前在Performance的blog上看过类似文章。

当时想到的是在修复之前保证数据库正常,不是这么异常的无休止的重启。

所以就修改了配置文件的一个参数:innodb_force_recovery

innodb_force_recovery 会影响整个InnoDB存储引擎的恢复状况。默认为0,表示当需要恢复时执行所有的

innodb_force_recovery可以设置为1-6,大的数字包含前面所有数字的影响。当设置参数值大于0后,可以对表进行

select,create,drop操作,但insert,update或者delete这类操作是不允许的。

  • (SRV_FORCE_IGNORE_CORRUPT):忽略检查到的corrupt页。
    (SRV_FORCE_NO_BACKGROUND):阻止主线程的运行,如主线程需要执行full purge操作,会导致crash。
  • (SRV_FORCE_NO_TRX_UNDO):不执行事务回滚操作。
  • (SRV_FORCE_NO_IBUF_MERGE):不执行插入缓冲的合并操作。
  • (SRV_FORCE_NO_UNDO_LOG_SCAN):不查看重做日志,InnoDB存储引擎会将未提交的事务视为已提交。
  • (SRV_FORCE_NO_LOG_REDO):不执行前滚的操作。

因为错误日志里面提示出现了坏页,导致数据库崩溃,所以这里把innodb_force_recovery 设置为1,忽略检查到的坏页。重启数据库之后,正常了,没有出现上面的错误信息。找到错误信息出现的表:
(index "PRIMARY" of table "maitem"."email_status")

数据页面的主键索引(clustered key index)被损坏。这种情况和数据的二级索引(secondary indexes)被损坏相比要糟很多,因为后者可以通过使用OPTIMIZE TABLE命令来修复,但这和更难以恢复的表格目录(table dictionary)被破坏的情况来说要好一些。

操作步骤

因为被破坏的地方只在索引的部分,所以当使用innodb_force_recovery = 1运行InnoDB时,操作如下:

执行check,repair table 都无效

alter table email_status engine =myisam; #也报错了,因为模式是innodb_force_recovery =1。

ERROR 1025 (HY000): Error on rename of '...' to '....' (errno: -1)

1. 建立一张表:

mysql> create table email_status_bak #和原表结构一样,只是把INNODB改成了MYISAM。

2. 把数据导进去 :

mysql>  insert into email_status_bak select * from email_status;

3. 删除掉原表:

mysql>  drop table email_status;

4. 注释掉innodb_force_recovery 之后,重启服务。

5. 重命名:

mysql> rename table edm_email_status_bak to email_status;

6. 最后该回存储引擎

mysql> alter table edm_email_status engine = innodb;

总结

这里的一个重要知识点就是 对 innodb_force_recovery 参数的理解了,要是遇到数据损坏甚至是其他的损坏。可能上面的方法不行了,需要尝试另一个方法:insert into tb select * from ta limit X;甚至是dump出去,再load回来。

Jenkins持续集成演示

1. 去我们的仓库修改一下代码

为了节约时间,我直接在网页上改了。

未分类

我们把布局页的footer信息改一下:

未分类

然后提交。

2. 切换到Jenkins可以看到已经在构建了

未分类

等待构建完成。

未分类

3. 访问我们部署的地址 可以看到footer已经被成功更改

未分类

整个过程我们就改一下代码,提交就行了。

etcd集群增加节点

主要两步:

  • 添加节点
  • 启动新节点

原本etcd集群

# etcdctl member list
b7124c8d88451: name=myetcd1 peerURLs=http://192.168.9.100:2380 clientURLs=http://192.168.9.100:2379 isLeader=true
235dcf74ed6248d5: name=myetcd3 peerURLs=http://192.168.9.100:2382 clientURLs=http://192.168.9.100:2399 isLeader=false
e35665335259ca10: name=myetcd2 peerURLs=http://192.168.9.100:2381 clientURLs=http://192.168.9.100:2389 isLeader=false

新增节点: 192.168.9.101:2383

# etcdctl member add myetcd4  http://192.168.9.101:2383

Added member named myetcd4 with ID 2644935c1a10c721 to cluster

ETCD_NAME="myetcd4"
ETCD_INITIAL_CLUSTER="myetcd1=http://192.168.9.100:2380,myetcd3=http://192.168.9.100:2382,myetcd4=http://192.168.9.101:2383,myetcd2=http://192.168.9.100:2381"
ETCD_INITIAL_CLUSTER_STATE="existing"

启动新节点:

# etcd --name myetcd4  --listen-client-urls http://0.0.0.0:2409 --advertise-client-urls http://192.168.9.101:2409 --listen-peer-urls http://0.0.0.0:2383 --initial-advertise-peer-urls http://192.168.9.101:2383  --initial-cluster-token etcd-cluster-test --initial-cluster-state existing --initial-cluster myetcd1=http://192.168.9.100:2380,myetcd2=http://192.168.9.100:2381,myetcd3=http://192.168.9.100:2382,myetcd4=http://192.168.9.101:2383
1

etcd集群搭建

下载安装

  • 从这下载https://github.com/coreos/etcd/releases/download/v3.3.2/etcd-v3.3.2-linux-amd64.tar.gz
  • tar xzvf etcd-v3.3.2-linux-amd64.tar.gz
  • cd etcd-v3.3.2-linux-amd64; cp etcd* /user/local/bin/
  • 这样即成功添加etcd命令
    etcd –version

运行与搭建

常见命令演示

etcd –version
etcdctl –version

API3的要这样
ETCDCTL_API=3 etcdctl version

启动:etcd
写一个数据与读取一个数据:key:key1 value:helloworld
ETCDCTL_API=3 etcdctl –endpoints=localhost:2379 put helloworld
ETCDCTL_API=3 etcdctl –endpoints=localhost:2379 get key1

单机启动:

etcd --name myetcd1  --listen-client-urls http://0.0.0.0:2379 --advertise-client-urls http://0.0.0.0:2379 --listen-peer-urls http://0.0.0.0:2380 --initial-advertise-peer-urls http://0.0.0.0:2380  --initial-cluster my-etcd-1=http://0.0.0.0:2380

集群启动:

etcd --name myetcd1  --listen-client-urls http://0.0.0.0:2379 --advertise-client-urls http://192.168.9.100:2379 --listen-peer-urls http://0.0.0.0:2380 --initial-advertise-peer-urls http://192.168.9.100:2380  --initial-cluster-token etcd-cluster-test --initial-cluster-state new --initial-cluster myetcd1=http://192.168.9.100:2380,myetcd2=http://192.168.9.100:2381,myetcd3=http://192.168.9.100:2382

etcd --name myetcd2  --listen-client-urls http://0.0.0.0:2389 --advertise-client-urls http://192.168.9.100:2389 --listen-peer-urls http://0.0.0.0:2381 --initial-advertise-peer-urls http://192.168.9.100:2381  --initial-cluster-token etcd-cluster-test --initial-cluster-state new --initial-cluster myetcd1=http://192.168.9.100:2380,myetcd2=http://192.168.9.100:2381,myetcd3=http://192.168.9.100:2382

etcd --name myetcd3  --listen-client-urls http://0.0.0.0:2399 --advertise-client-urls http://192.168.9.100:2399 --listen-peer-urls http://0.0.0.0:2382 --initial-advertise-peer-urls http://192.168.9.100:2382  --initial-cluster-token etcd-cluster-test --initial-cluster-state new --initial-cluster myetcd1=http://192.168.9.100:2380,myetcd2=http://192.168.9.100:2381,myetcd3=http://192.168.9.100:2382

用三个端口2380,2381,2382来模拟集群(这三个是成员之间通信),2379,2389,2399是给客户端连接的.服务器IP:192.168.9.100, 如果在本机模拟集群, 可以将192.168.9.100改为0.0.0.0

带advertise参数是广播参数: 如–listen-client-urls和–advertise-client-urls, 前者是Etcd端监听客户端的url,后者是Etcd客户端请求的url, 两者端口是相同的, 只不过后者一般为公网IP, 暴露给外部使用.

查看成员:

etcdctl member list 

使用时需要指定endpoints(默认本地端口2379), 集群时数据会迅速同步:

ETCDCTL_API=3 etcdctl –endpoints=127.0.0.1:2389 put key1 xx 
ETCDCTL_API=3 etcdctl –endpoints=127.0.0.1:2379 get key1

参数说明

–name etcd0:本member的名字

–initial-advertise-peer-urls http://192.168.9.100:2380: 其他member使用,其他member通过该地址与本member交互信息。一定要保证从其他member能可访问该地址。静态配置方式下,该参数的value一定要同时在–initial-cluster参数中存在。memberID的生成受–initial-cluster-token和–initial-advertise-peer-urls影响。

–listen-peer-urls http://0.0.0.0:2380:本member侧使用,用于监听其他member发送信息的地址。ip为全0代表监听本member侧所有接口

–listen-client-urls http://0.0.0.0:2379: 本member侧使用,用于监听etcd客户发送信息的地址。ip为全0代表监听本member侧所有接口

–advertise-client-urls http://192.168.9.100:2379: etcd客户使用,客户通过该地址与本member交互信息。一定要保证从客户侧能可访问该地址

–initial-cluster-token etcd-cluster-2:用于区分不同集群。本地如有多个集群要设为不同。

–initial-cluster myetcd0=http://192.168.9.100:2380,myetcd1=http://192.168.9.100:2381,myetcd2=http://192.168.9.100:2382:本member侧使用。描述集群中所有节点的信息,本member根据此信息去联系其他member。memberID的生成受–initial-cluster-token和–initial-advertise-peer-urls影响。

–initial-cluster-state new:用于指示本次是否为新建集群。有两个取值new和existing。如果填为existing,则该member启动时会尝试与其他member交互。集群初次建立时,要填为new,经尝试最后一个节点填existing也正常,其他节点不能填为existing。集群运行过程中,一个member故障后恢复时填为existing,经尝试填为new也正常。

–data-dir:指定节点的数据存储目录,这些数据包括节点ID,集群ID,集群初始化配置,Snapshot文件,若未指定-wal-dir,还会存储WAL文件;如果不指定会用缺省目录。

–discovery http://192.168.9.100:20003/v2/keys/discovery/78b12ad7-2c1d-40db-9416-3727baf686cb:用于自发现模式下,指定第三方etcd上key地址,要建立的集群各member都会向其注册自己的地址。

使用详细说明

ETCD API有两种, 一种是3, 一种是2, 默认为2, 我们主要用3:

API3:

[root@guods-1 centos]# ETCDCTL_API=3 etcdctl --endpoints=localhost:2379 put key1 helloworld
OK
[root@guods-1 centos]# ETCDCTL_API=3 etcdctl --endpoints=localhost:2379 get key1
key1
helloworld

API2:

[root@guods-1 centos]# etcdctl set key2 helloworld
helloworld
[root@guods-1 centos]# etcdctl get key2
helloworld

命令详解:

[root@guods-1 centos]# ETCDCTL_API=2 etcdctl
NAME:
   etcdctl - A simple command line client for etcd.

USAGE:
   etcdctl [global options] command [command options] [arguments...]

VERSION:
   3.3.2

COMMANDS:
     backup          backup an etcd directory
     cluster-health  check the health of the etcd cluster
     mk              make a new key with a given value
     mkdir           make a new directory
     rm              remove a key or a directory
     rmdir           removes the key if it is an empty directory or a key-value pair
     get             retrieve the value of a key
     ls              retrieve a directory
     set             set the value of a key
     setdir          create a new directory or update an existing directory TTL
     update          update an existing key with a given value
     updatedir       update an existing directory
     watch           watch a key for changes
     exec-watch      watch a key for changes and exec an executable
     member          member add, remove and list subcommands
     user            user add, grant and revoke subcommands
     role            role add, grant and revoke subcommands
     auth            overall auth controls
     help, h         Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --debug                          output cURL commands which can be used to reproduce the request
   --no-sync                        don't synchronize cluster information before sending request
   --output simple, -o simple       output response in the given format (simple, `extended` or `json`) (default: "simple")
   --discovery-srv value, -D value  domain name to query for SRV records describing cluster endpoints
   --insecure-discovery             accept insecure SRV records describing cluster endpoints
   --peers value, -C value          DEPRECATED - "--endpoints" should be used instead
   --endpoint value                 DEPRECATED - "--endpoints" should be used instead
   --endpoints value                a comma-delimited list of machine addresses in the cluster (default: "http://127.0.0.1:2379,http://127.0.0.1:4001")
   --cert-file value                identify HTTPS client using this SSL certificate file
   --key-file value                 identify HTTPS client using this SSL key file
   --ca-file value                  verify certificates of HTTPS-enabled servers using this CA bundle
   --username value, -u value       provide username[:password] and prompt if password is not supplied.
   --timeout value                  connection timeout per request (default: 2s)
   --total-timeout value            timeout for the command execution (except watch) (default: 5s)
   --help, -h                       show help
   --version, -v                    print the version
[root@guods-1 centos]# ETCDCTL_API=3 etcdctl
NAME:
    etcdctl - A simple command line client for etcd3.

USAGE:
    etcdctl

VERSION:
    3.3.2

API VERSION:
    3.3


COMMANDS:
    get         Gets the key or a range of keys
    put         Puts the given key into the store
    del         Removes the specified key or range of keys [key, range_end)
    txn         Txn processes all the requests in one transaction
    compaction      Compacts the event history in etcd
    alarm disarm        Disarms all alarms
    alarm list      Lists all alarms
    defrag          Defragments the storage of the etcd members with given endpoints
    endpoint health     Checks the healthiness of endpoints specified in `--endpoints` flag
    endpoint status     Prints out the status of endpoints specified in `--endpoints` flag
    endpoint hashkv     Prints the KV history hash for each endpoint in --endpoints
    move-leader     Transfers leadership to another etcd cluster member.
    watch           Watches events stream on keys or prefixes
    version         Prints the version of etcdctl
    lease grant     Creates leases
    lease revoke        Revokes leases
    lease timetolive    Get lease information
    lease list      List all active leases
    lease keep-alive    Keeps leases alive (renew)
    member add      Adds a member into the cluster
    member remove       Removes a member from the cluster
    member update       Updates a member in the cluster
    member list     Lists all members in the cluster
    snapshot save       Stores an etcd node backend snapshot to a given file
    snapshot restore    Restores an etcd member snapshot to an etcd directory
    snapshot status     Gets backend snapshot status of a given file
    make-mirror     Makes a mirror at the destination etcd cluster
    migrate         Migrates keys in a v2 store to a mvcc store
    lock            Acquires a named lock
    elect           Observes and participates in leader election
    auth enable     Enables authentication
    auth disable        Disables authentication
    user add        Adds a new user
    user delete     Deletes a user
    user get        Gets detailed information of a user
    user list       Lists all users
    user passwd     Changes password of user
    user grant-role     Grants a role to a user
    user revoke-role    Revokes a role from a user
    role add        Adds a new role
    role delete     Deletes a role
    role get        Gets detailed information of a role
    role list       Lists all roles
    role grant-permission   Grants a key to a role
    role revoke-permission  Revokes a key from a role
    check perf      Check the performance of the etcd cluster
    help            Help about any command

OPTIONS:
      --cacert=""               verify certificates of TLS-enabled secure servers using this CA bundle
      --cert=""                 identify secure client using this TLS certificate file
      --command-timeout=5s          timeout for short running command (excluding dial timeout)
      --debug[=false]               enable client-side debug logging
      --dial-timeout=2s             dial timeout for client connections
  -d, --discovery-srv=""            domain name to query for SRV records describing cluster endpoints
      --endpoints=[127.0.0.1:2379]      gRPC endpoints
  -h, --help[=false]                help for etcdctl
      --hex[=false]             print byte strings as hex encoded strings
      --insecure-discovery[=true]       accept insecure SRV records describing cluster endpoints
      --insecure-skip-tls-verify[=false]    skip server certificate verification
      --insecure-transport[=true]       disable transport security for client connections
      --keepalive-time=2s           keepalive time for client connections
      --keepalive-timeout=6s            keepalive timeout for client connections
      --key=""                  identify secure client using this TLS key file
      --user=""                 username[:password] for authentication (prompt if password is not supplied)
  -w, --write-out="simple"          set the output format (fields, json, protobuf, simple, table)

在 Linux 上使用 NTP 保持精确的时间 | Linux 中国

如何保持正确的时间,如何使用 NTP 和 systemd 让你的计算机在不滥用时间服务器的前提下保持同步。

它的时间是多少?

让 Linux 来告诉你时间的时候,它是很奇怪的。你可能认为是使用 time 命令来告诉你时间,其实并不是,因为 time 只是一个测量一个进程运行了多少时间的计时器。为得到时间,你需要运行的是 date 命令,你想查看更多的日期,你可以运行 cal 命令。文件上的时间戳也是一个容易混淆的地方,因为根据你的发行版默认情况不同,它一般有两种不同的显示方法。下面是来自 Ubuntu 16.04 LTS 的示例:

$ ls -l
drwxrwxr-x 5 carla carla 4096 Mar 27 2017 stuff
drwxrwxr-x 2 carla carla 4096 Dec 8 11:32 things
-rw-rw-r-- 1 carla carla 626052 Nov 21 12:07 fatpdf.pdf
-rw-rw-r-- 1 carla carla 2781 Apr 18 2017 oddlots.txt

有些显示年,有些显示时间,这样的方式让你的文件更混乱。GNU 默认的情况是,如果你的文件在六个月以内,则显示时间而不是年。我想这样做可能是有原因的。如果你的 Linux 是这样的,尝试用 ls -l –time-style=long-iso 命令,让时间戳用同一种方式去显示,按字母顺序排序。请查阅 如何更改 Linux 的日期和时间:简单的命令[1] 去学习 Linux 上管理时间的各种方法。

检查当前设置

NTP —— 网络时间协议,它是保持计算机正确时间的老式方法。ntpd 是 NTP 守护程序,它通过周期性地查询公共时间服务器来按需调整你的计算机时间。它是一个简单的、轻量级的协议,使用它的基本功能时设置非常容易。systemd 通过使用 systemd-timesyncd.service 已经越俎代庖地 “干了 NTP 的活”,它可以用作 ntpd 的客户端。

在我们开始与 NTP “打交道” 之前,先花一些时间来了检查一下当前的时间设置是否正确。

你的系统上(至少)有两个时钟:系统时间 —— 它由 Linux 内核管理,第二个是你的主板上的硬件时钟,它也称为实时时钟(RTC)。当你进入系统的 BIOS 时,你可以看到你的硬件时钟的时间,你也可以去改变它的设置。当你安装一个新的 Linux 时,在一些图形化的时间管理器中,你会被询问是否设置你的 RTC 为 UTC(世界标准时间Coordinated Universal Time)时区,因为所有的时区和夏令时都是基于 UTC 的。你可以使用 hwclock 命令去检查:

$ sudo hwclock --debug
hwclock from util-linux 2.27.1
Using the /dev interface to the clock.
Hardware clock is on UTC time
Assuming hardware clock is kept in UTC time.
Waiting for clock tick...
...got clock tick
Time read from Hardware Clock: 2018/01/22 22:14:31
Hw clock time : 2018/01/22 22:14:31 = 1516659271 seconds since 1969
Time since last adjustment is 1516659271 seconds
Calculated Hardware Clock drift is 0.000000 seconds
Mon 22 Jan 2018 02:14:30 PM PST .202760 seconds

Hardware clock is on UTC time 表明了你的计算机的 RTC 是使用 UTC 时间的,虽然它把该时间转换为你的本地时间。如果它被设置为本地时间,它将显示 Hardware clock is on local time。

你应该有一个 /etc/adjtime 文件。如果没有的话,使用如下命令同步你的 RTC 为系统时间,

$ sudo hwclock -w

这个命令将生成该文件,内容看起来类似如下:

$ cat /etc/adjtime
0.000000 1516661953 0.000000
1516661953
UTC

新发明的 systemd 方式是去运行 timedatectl 命令,运行它不需要 root 权限:

$ timedatectl
 Local time: Mon 2018-01-22 14:17:51 PST
 Universal time: Mon 2018-01-22 22:17:51 UTC
 RTC time: Mon 2018-01-22 22:17:51
 Time zone: America/Los_Angeles (PST, -0800)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

RTC in local TZ: no 表明它使用 UTC 时间。那么怎么改成使用本地时间?这里有许多种方法可以做到。最简单的方法是使用一个图形配置工具,比如像 openSUSE 中的 YaST。你也可使用 timedatectl:

$ timedatectl set-local-rtc 0

或者编辑 /etc/adjtime,将 UTC 替换为 LOCAL。

systemd-timesyncd 客户端

现在,我已经累了,但是我们刚到非常精彩的部分。谁能想到计时如此复杂?我们甚至还没有了解到它的皮毛;阅读 man 8 hwclock 去了解你的计算机如何保持时间的详细内容。

systemd 提供了 systemd-timesyncd.service 客户端,它可以查询远程时间服务器并调整你的本地系统时间。在 /etc/systemd/timesyncd.conf 中配置你的(时间)服务器。大多数 Linux 发行版都提供了一个默认配置,它指向他们维护的时间服务器上,比如,以下是 Fedora 的:

[Time]
#NTP=
#FallbackNTP=0.fedora.pool.ntp.org 1.fedora.pool.ntp.org

你可以输入你希望使用的其它时间服务器,比如你自己的本地 NTP 服务器,在 NTP= 行上输入一个以空格分隔的服务器列表。(别忘了取消这一行的注释)NTP= 行上的任何内容都将覆盖掉 FallbackNTP 行上的配置项。

如果你不想使用 systemd 呢?那么,你将需要 NTP 就行。

配置 NTP 服务器和客户端

配置你自己的局域网 NTP 服务器是一个非常好的实践,这样你的网内计算机就不需要不停查询公共 NTP 服务器。在大多数 Linux 上的 NTP 都来自 ntp 包,它们大多都提供 /etc/ntp.conf 文件去配置时间服务器。查阅 NTP 时间服务器池[2] 去找到你所在的区域的合适的 NTP 服务器池。然后在你的 /etc/ntp.conf 中输入 4 – 5 个服务器,每个服务器用单独的一行:

driftfile /var/ntp.drift
logfile /var/log/ntp.log
server 0.europe.pool.ntp.org
server 1.europe.pool.ntp.org
server 2.europe.pool.ntp.org
server 3.europe.pool.ntp.org

driftfile 告诉 ntpd 它需要保存用于启动时使用时间服务器快速同步你的系统时钟的信息。而日志也将保存在他们自己指定的目录中,而不是转储到 syslog 中。如果你的 Linux 发行版默认提供了这些文件,请使用它们。

现在去启动守护程序;在大多数主流的 Linux 中它的命令是 sudo systemctl start ntpd。让它运行几分钟之后,我们再次去检查它的状态:

$ ntpq -p
 remote refid st t when poll reach delay offset jitter
==============================================================
+dev.smatwebdesi 192.168.194.89 3 u 25 64 37 92.456 -6.395 18.530
*chl.la 127.67.113.92 2 u 23 64 37 75.175 8.820 8.230
+four0.fairy.mat 35.73.197.144 2 u 22 64 37 116.272 -10.033 40.151
-195.21.152.161 195.66.241.2 2 u 27 64 37 107.559 1.822 27.346

我不知道这些内容是什么意思,但重要的是,你的守护程序已经与时间服务器开始对话了,而这正是我们所需要的。你可以去运行 sudo systemctl enable ntpd 命令,永久启用它。如果你的 Linux 没有使用 systemd,那么,给你留下的家庭作业就是找出如何去运行 ntpd。

现在,你可以在你的局域网中的其它计算机上设置 systemd-timesyncd,这样它们就可以使用你的本地 NTP 服务器了,或者,在它们上面安装 NTP,然后在它们的 /etc/ntp.conf 上输入你的本地 NTP 服务器。

NTP 服务器会受到攻击,而且需求在不断增加。你可以通过运行你自己的公共 NTP 服务器来提供帮助。下周我们将学习如何运行你自己的公共服务器。

linux下的find文件查找命令与grep文件内容查找命令

在使用linux时,经常需要进行文件查找。其中查找的命令主要有find和grep。两个命令是有区的。

区别:(1)find命令是根据文件的属性进行查找,如文件名,文件大小,所有者,所属组,是否为空,访问时间,修改时间等。

(2)grep是根据文件的内容进行查找,会对文件的每一行按照给定的模式(patter)进行匹配查找。

一、find命令

基本格式:find  path expression

1. 按照文件名查找

(1)find / -name httpd.conf  #在根目录下查找文件httpd.conf,表示在整个硬盘查找

(2)find /etc -name httpd.conf  #在/etc目录下文件httpd.conf

(3) find /etc -name '*srm*'  #使用通配符*(0或者任意多个)。表示在/etc目录下查找文件名中含有字符串‘srm’的文件

(4) find . -name 'srm*'   #表示当前目录下查找文件名开头是字符串‘srm’的文件

2. 按照文件特征查找

(1) find / -amin -10   # 查找在系统中最后10分钟访问的文件(access time)

(2) find / -atime -2   # 查找在系统中最后48小时访问的文件

(3) find / -empty   # 查找在系统中为空的文件或者文件夹

(4) find / -group cat   # 查找在系统中属于 group为cat的文件

(5) find / -mmin -5   # 查找在系统中最后5分钟里修改过的文件(modify time)

(6) find / -mtime -1   #查找在系统中最后24小时里修改过的文件

(7) find / -user fred   #查找在系统中属于fred这个用户的文件

(8) find / -size +10000c  #查找出大于10000000字节的文件(c:字节,w:双字,k:KB,M:MB,G:GB)

(9) find / -size -1000k   #查找出小于1000KB的文件

3. 使用混合查找方式查找文件

参数有: !,-and(-a),-or(-o)。

(1) find /tmp -size +10000c -and -mtime +2   #在/tmp目录下查找大于10000字节并在最后2分钟内修改的文件

(2) find / -user fred -or -user george   #在/目录下查找用户是fred或者george的文件文件

(3) find /tmp ! -user panda  #在/tmp目录中查找所有不属于panda用户的文件`

二、grep命令

基本格式:find  expression

1. 主要参数

[options]主要参数:

  • -c:只输出匹配行的计数。

  • -i:不区分大小写

  • -h:查询多文件时不显示文件名。

  • -l:查询多文件时只输出包含匹配字符的文件名。

  • -n:显示匹配行及行号。

  • -s:不显示不存在或无匹配文本的错误信息。

  • -v:显示不包含匹配文本的所有行。

pattern正则表达式主要参数:

  • : 忽略正则表达式中特殊字符的原有含义。

  • ^:匹配正则表达式的开始行。

  • $: 匹配正则表达式的结束行。

  • <:从匹配正则表达 式的行开始。

  • >:到匹配正则表达式的行结束。

  • [ ]:单个字符,如[A]即A符合要求 。

  • [ – ]:范围,如[A-Z],即A、B、C一直到Z都符合要求 。

  • .:所有的单个字符。

  • * :有字符,长度可以为0。

2. 实例

(1) grep 'test' d*  #显示所有以d开头的文件中包含 test的行

(2) grep ‘test’ aa bb cc    #显示在aa,bb,cc文件中包含test的行

(3) grep ‘[a-z]{5}’ aa   #显示所有包含每行字符串至少有5个连续小写字符的字符串的行

(4) grep magic /usr/src  #显示/usr/src目录下的文件(不含子目录)包含magic的行

(5) grep -r magic /usr/src  #显示/usr/src目录下的文件(包含子目录)包含magic的行

(6) grep -w pattern files :只匹配整个单词,而不是字符串的一部分(如匹配’magic’,而不是’magical’)