还没想好用什么标题

0%

需求

ES集群Cluster_A里的数据(某个索引或某几个索引),需要迁移到另外一个ES集群Cluster_B中。

环境

Linux:Centos7 / Centos6.5/ Centos6.4
Elastic:5.2.0

总结的方法

  1. 查询并导出数据

  2. 拷贝ES物理目录/文件

  3. ES快照数据备份和恢复

迁移方法

分别进行以上方法的详细介绍:

查询并导出数据

理论

通过ES提供的查询API,写各种程序,把数据导出csv,或者把数据查询出来,直接入库到新的ES集群中。

实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#coding=utf-8

import os
import sys
import pyes


index_list = [
["index_A", "type_A"],
["index_B", "type_B"],
["index_C", "type_C"],
]


ES_URL = "http://192.168.1.1:9200/"
NEW_ES_URL = "http://192.168.2.1:8200/"

def main():
for _index, _type in index_list:
conn = pyes.es.ES(ES_URL)
search = pyes.query.MatchAllQuery().search(bulk_read=10000)
hits = conn.search(search, _index, _type, scan=True, scroll="30m", model=lambda _,hit: hit)

conn2 = pyes.es.ES(NEW_ES_URL)
count = 0
for hit in hits:
conn2.index(hit['_source'], _index, _type, hit['_id'], bulk=True)
count += 1
if count % 10000 == 0:
print count
conn2.flush()
conn2.flush()
conn2 = None

conn = None


if __name__ == '__main__':
main()

注意事项

  1. 需要安装python的pyes模块,注意pyes的版本,此处的版本为:pyes.0.20.1

  2. 用了查询ES的scroll方式,也有一种直接通过ES的DSL查询语句用分页from和size查询,但是ES的分页查询到了千万级别之后,from就会慢的出奇,甚至报错,不信的同学去尝试吧,等着功亏一篑….

  3. 客户现场的数据级别是物理存储大概在5T(一个副本),条数大概1百亿。现场使用该方法亲测之后,未解决ES迁移的问题。pyes在约到后面查询越慢,最后ES报错…..

总结

  1. 百万、千万级别条数的数据,可以尝试该方法。

拷贝ES物理目录/文件

理论

ES的文件存在磁盘中,把物理文件一模一样拷贝一份到新的集群环境中,达到数据迁移的效果。

实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
1. 找到ES的存储目录,一般可以到elasticsearch.yml中找到path.data的配置

2. 集群下一般会有多个节点,所以ES的存储目录也就有多个


3. 一般ES的存储目录下,会存储一个集群名字一样的文件夹,需要拷贝的就是这个文件夹.


4. 环境如下:
旧集群:
集群名字:Cluster_A
分片数:6
机器A:一个节点 192.168.1.1
node0 数据存储目录:/opt/data1,/opt/data2
机器B:三个节点 192.168.1.2
node1 数据存储目录:/opt/data1,/opt/data2
node2 数据存储目录:/opt/data3,/opt/data4
node3 数据存储目录:/opt/data5,/opt/data6

新的集群:
集群名字:Cluster_A
分片数:6
机器A:一个节点 192.168.2.1
node0 数据存储目录:/opt/data1,/opt/data2
机器B:三个节点 192.168.2.2
node1 数据存储目录:/opt/data1,/opt/data2
node2 数据存储目录:/opt/data3,/opt/data4
node3 数据存储目录:/opt/data5,/opt/data6


5. 迁移代码如下:
新集群机器A:192.168.2.1如下操作

scp –r [email protected]:/opt/data1/Cluster_A /opt/data1/
scp –r [email protected]:/opt/data2/Cluster_A /opt/data2/


新集群机器B:192.168.2.2如下操作

scp –r [email protected]:/opt/data1/Cluster_A /opt/data1/
scp –r [email protected]:/opt/data2/Cluster_A /opt/data2/
scp –r [email protected]:/opt/data3/Cluster_A /opt/data3/
scp –r [email protected]:/opt/data4/Cluster_A /opt/data4/
scp –r [email protected]:/opt/data5/Cluster_A /opt/data5/
scp –r [email protected]:/opt/data6/Cluster_A /opt/data6/

ES快照数据备份和恢复

理论

使用ES官网提供的快照备份方法,将旧集群ES的索引进行备份,拷贝备份出来的所有文件,在新的集群中进行恢复。

官网写的非常简单:先创建仓库(repository),再往仓库里添加一个快照(snapshot),查看备份状态,That’s all。但是实践需要麻烦很多了。

实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
1. 旧的集群备份出来的东西,需要拷贝到新集群机器上。解决两个问题:一是旧集群没有足够的空间存储这些东西;二是反正备份出来都需要拷贝到新的集群中。此处想到一个方法,将新集群机器的目录远程Mount到旧集群机器上。


2. 挂载目录,2.1)和2.2)可以任选一种方式


3. 使用sshfs进行挂载:

// 在每台机器上安装sshfs
yum install fuse sshfs

// 每台机器上创建Mount共享目录
mkdir /opt/backup_es

// 旧集群的每台机器上挂载共享目录(分别挂载了新机器的/opt/data07目录到/opt/backup_es)
sshfs [email protected]:/opt/data07 /opt/backup_es -o allow_other
sshfs [email protected]:/opt/data07 /opt/backup_es -o allow_other

// 测试运行ES的用户是否有对共享目录的写权限
sudo -u elastic touch /opt/backup_es

// 在旧机器上将共享目录的权限付给ES的运行用户
chown elastic:elastic -R /opt/backup_es


2. 使用Mount nfs进行挂载:

// 在新集群的机器上(192.168.2.1, 192.168.2.2)添加共享的文件夹和客户端可以访问的IP地址
vi /etc/exports
/opt/data07 192.168.1.1(rw,no_root_squash)
/opt/data07 192.168.1.2(rw,no_root_squash)

// 查看共享文件夹和
exportfs -rv

// 重启启动新集群机器的NFS服务
services nfs restart

// 旧集群的每台机器上创建共享目录
mkdir /opt/backup_es

// 旧集群机器上进行Mount挂载
mount -t nfs 192.168.2.1:/opt/data07 /opt/backup_es
mount -t nfs 192.168.2.2:/opt/data07 /opt/backup_es

// 在旧机器上将共享目录的权限付给ES的运行用户
chown elastic:elastic -R /opt/backup_es


3. 创建ES仓库

// 创建ES仓库my_backup
http://192.168.1.1:9200/_plugin/head/的复合查询,通过PUT进行发送请求:
PUT _snapshot/my_backup
{
"type": "fs",
"settings": {
"location": "/opt/backup_es",
"compress": true
}
}

// 查看仓库的状态
http://192.168.1.1:9200/_snapshot


4. 创建快照备份

// 针对具体的index创建快照备份(可以指定1个快照1个索引,或1个快照多个索引)
// 后面会依据快照的名称来进行恢复
http://192.168.1.1:9200/
PUT _snapshot/my_backup/snapshot_name_A
{
"indices": "index_A, index_B"
}

成功之后,备份已经异步开始了。


5. 查看备份的状态

// 查看备份状态
http://192.168.1.1:9200/_snapshot/my_backup/snapshot_name_A/_status

细心的同学会看到ES会同时进行几个分片的备份,而且显示备份的数据情况。
有心的同学会看到,旧集群上共享的两个目录/opt/backup_es会均分备份出来的数据。这一点ES还是比较强大的,赞一个。应该还可以指定多个目录(作者没有试过,但是应该也是OK的,这样就可以挂载多个目录,解决磁盘空间不足的问题了)


6. 最后,就是等,直至所有的的备份都完成。
备份完成后,查看旧集群每台机器的/opt/backup_es目录,查看备份出的东东。
取消挂载


7. 在新集群中恢复

// 在新集群每台机器上将共享目录的权限付给ES的运行用户
chown elastic:elastic -R /opt/data07

// 停止ES,设置elasticsearch.yml的参数
path.repo: /opt/data07

// 启动ES,在新集群创建仓库
http://192.168.2.1:9200/_plugin/head/的复合查询,通过PUT进行发送请求:
PUT _snapshot/my_backup
{
"type": "fs",
"settings": {
"location": "/opt/data07",
"compress": true
}
}


8. 在新集群中恢复数据

// 使用RESTful API进行备份的恢复
http://192.168.1.1:9200/
POST
_snapshot/my_backup/snapshot_name_A/_restore

// 查看恢复的状态
http://192.168.1.1:9200/
GET
_snapshot/my_backup/snapshot_name_A/_status


9. 等,直至恢复完成。

注意事项

  1. 索引很大,需要有足够的空间存储备份出来的数据,挂载磁盘和设置path.repo来解决该问题。

  2. 在简历仓库的时候,会报错,找不到快照目录/opt/backup_es
    需要在elasticsearch.yml中设置path.repo: /opt/backup_es

  3. 挂载的磁盘需要赋权限,让ES的用户能读写。Sshfs的时候加上 -oallow_other;Mount的时候需要对目录进行赋权限chown

  4. Mount nfs的时候需要注意配置:vi /etc/exports

    1
    2
    /opt/data07192.168.1.1(rw,no_root_squash)
    /opt/data07192.168.1.2(rw,no_root_squash)
  5. 新集群中如果有索引和备份出来的索引有冲突(索引已存在),恢复不成功。
    解决:可以将旧的索引重命名,然后导入新集群中。导入成功后,将两个索引建立一个别名。

  6. 恢复期间,整个集群会变成红色(集群不可用),最好半夜的时候进行。

环境

1
2
3
4
5
6
7
8
9
10
$ cat /etc/redhat-release 
CentOS Linux release 7.0.1406 (Core)
$ uname -a
Linux zhaopin-2-201 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
$ mongo --version
MongoDB shell version: 3.0.6

node1: 172.30.2.201
node2: 172.30.2.202
node3: 172.30.2.203

配置Shard Server

  • 在3个节点分别执行: *

创建目录

1
$ sudo mkdir -p /data/mongodb/{data/{sh0,sh1},backup/{sh0,sh1},log/{sh0,sh1},conf/{sh0,sh1}}

准备配置文件

  • 第一个分片: *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ sudo vim /data/mongodb/conf/sh0/mongodb.conf
# base
port = 27010
maxConns = 800
filePermissions = 0700
fork = true
noauth = true
directoryperdb = true
dbpath = /data/mongodb/data/sh0
pidfilepath = /data/mongodb/data/sh0/mongodb.pid
oplogSize = 10
journal = true
# security
nohttpinterface = true
rest = false
# log
logpath = /data/mongodb/log/sh0/mongodb.log
logRotate = rename
logappend = true
slowms = 50
replSet = sh0
shardsvr = true
  • 第二个分片: *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ sudo vim /data/mongodb/conf/sh1/mongodb.conf
# base
port = 27011
maxConns = 800
filePermissions = 0700
fork = true
noauth = true
directoryperdb = true
dbpath = /data/mongodb/data/sh1
pidfilepath = /data/mongodb/data/sh1/mongodb.pid
oplogSize = 10
journal = true
# security
nohttpinterface = true
rest = false
# log
logpath = /data/mongodb/log/sh1/mongodb.log
logRotate = rename
logappend = true
slowms = 50
replSet = sh1
shardsvr = true

启动Shard Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ sudo /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh0/mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 41492
child process started successfully, parent exiting
$ sudo /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh1/mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 41509
child process started successfully, parent exiting
$ ps aux | grep mongo | grep -v grep
root 41492 0.5 0.0 518016 54604 ? Sl 10:09 0:00 /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh0/mongodb.conf
root 41509 0.5 0.0 516988 51824 ? Sl 10:09 0:00 /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh1/mongodb.conf
$ mongo --port 27010
MongoDB shell version: 3.0.6
connecting to: 127.0.0.1:27010/test
>
bye
$ mongo --port 27011
MongoDB shell version: 3.0.6
connecting to: 127.0.0.1:27011/test
>
bye

配置Config Server

  • 在3个节点分别执行: *

创建目录

1
$ sudo mkdir -p /data/mongodb/{data/cf0,backup/cf0,log/cf0,conf/cf0}

准备配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ sudo vim /data/mongodb/conf/cf0/config.conf
# base
port = 27000
maxConns = 800
filePermissions = 0700
fork = true
noauth = true
directoryperdb = true
dbpath = /data/mongodb/data/cf0
pidfilepath = /data/mongodb/data/cf0/config.pid
oplogSize = 10
journal = true
# security
nohttpinterface = true
rest = false
# log
logpath = /data/mongodb/log/cf0/config.log
logRotate = rename
logappend = true
slowms = 50
configsvr = true

启动

1
2
3
4
5
6
7
8
$ sudo /opt/mongodb/bin/mongod --config /data/mongodb/conf/cf0/config.conf
about to fork child process, waiting until server is ready for connections.
forked process: 41759
child process started successfully, parent exiting
$ ps aux | grep mongo | grep -v grep
root 41492 0.3 0.0 518016 54728 ? Sl 10:09 0:06 /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh0/mongodb.conf
root 41509 0.3 0.0 518016 54760 ? Sl 10:09 0:06 /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh1/mongodb.conf
root 41855 0.4 0.0 467828 51684 ? Sl 10:25 0:03 /opt/mongodb/bin/mongod --config /data/mongodb/conf/cf0/config.conf

配置Query Routers

  • 在3个节点分别执行: *

创建目录

1
$ sudo mkdir -p /data/mongodb/{data/ms0,backup/ms0,log/ms0,conf/ms0}

准备配置文件

1
2
3
4
5
6
7
8
9
10
11
12
$ sudo vim /data/mongodb/conf/ms0/mongos.conf
# base
port = 30000
maxConns = 800
filePermissions = 0700
fork = true
pidfilepath = /data/mongodb/data/ms0/mongos.pid
# log
logpath = /data/mongodb/log/ms0/mongos.log
logRotate = rename
logappend = true
configdb = 172.30.2.201:27000,172.30.2.202:27000,172.30.2.203:27000

启动

1
2
3
4
5
6
7
8
9
10
$ sudo /opt/mongodb/bin/mongos --config /data/mongodb/conf/ms0/mongos.conf
about to fork child process, waiting until server is ready for connections.
forked process: 42233
child process started successfully, parent exiting
$ ps aux | grep mongo | grep -v grep
root 41492 0.3 0.0 518016 54728 ? Sl 10:09 0:06 /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh0/mongodb.conf
root 41509 0.3 0.0 518016 54760 ? Sl 10:09 0:07 /opt/mongodb/bin/mongod --config /data/mongodb/conf/sh1/mongodb.conf
root 41855 0.4 0.0 546724 37812 ? Sl 10:25 0:03 /opt/mongodb/bin/mongod --config /data/mongodb/conf/cf0/config.conf
root 41870 0.4 0.0 546724 38188 ? Sl 10:25 0:03 /opt/mongodb/bin/mongod --conf
root 42233 0.5 0.0 233536 10188 ? Sl 10:38 0:00 /opt/mongodb/bin/mongos --config /data/mongodb/conf/ms0/mongos.conf

初始化副本集

配置副本集的好处是为了高可用,配置单节点是我自己为了节省时间,后续添加节点和副本集的操作一样,分片的配置不需要修改,在任何一个节点执行,这里在node1上执行

  • 分片一: *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
$ mongo --port 27010
MongoDB shell version: 3.0.6
connecting to: 127.0.0.1:27010/test
> use admin
switched to db admin
> cfg={_id:"sh0", members:[ {_id:0,host:"172.30.2.201:27010"}, {_id:1,host:"172.30.2.202:27010"}, {_id:2,host:"172.30.2.203:27010"} ] }
{
"_id" : "sh0",
"members" : [
{
"_id" : 0,
"host" : "172.30.2.201:27010"
},
{
"_id" : 1,
"host" : "172.30.2.202:27010"
},
{
"_id" : 2,
"host" : "172.30.2.203:27010"
}
]
}
> rs.initiate( cfg );
{ "ok" : 1 }
sh0:OTHER> rs.status()
{
"set" : "sh0",
"date" : ISODate("2015-10-23T05:33:31.920Z"),
"myState" : 1,
"members" : [
{
"_id" : 0,
"name" : "172.30.2.201:27010",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 270,
"optime" : Timestamp(1445578404, 1),
"optimeDate" : ISODate("2015-10-23T05:33:24Z"),
"electionTime" : Timestamp(1445578408, 1),
"electionDate" : ISODate("2015-10-23T05:33:28Z"),
"configVersion" : 1,
"self" : true
},
{
"_id" : 1,
"name" : "172.30.2.202:27010",
"health" : 1,
"state" : 5,
"stateStr" : "STARTUP2",
"uptime" : 7,
"optime" : Timestamp(0, 0),
"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
"lastHeartbeat" : ISODate("2015-10-23T05:33:30.289Z"),
"lastHeartbeatRecv" : ISODate("2015-10-23T05:33:30.295Z"),
"pingMs" : 1,
"configVersion" : 1
},
{
"_id" : 2,
"name" : "172.30.2.203:27010",
"health" : 1,
"state" : 5,
"stateStr" : "STARTUP2",
"uptime" : 7,
"optime" : Timestamp(0, 0),
"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
"lastHeartbeat" : ISODate("2015-10-23T05:33:30.289Z"),
"lastHeartbeatRecv" : ISODate("2015-10-23T05:33:30.293Z"),
"pingMs" : 1,
"configVersion" : 1
}
],
"ok" : 1
}
sh0:PRIMARY>
bye
  • 分片二: *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
$ mongo --port 27011
MongoDB shell version: 3.0.6
connecting to: 127.0.0.1:27011/test
> use admin
switched to db admin
> cfg={_id:"sh1", members:[ {_id:0,host:"172.30.2.201:27011"}, {_id:1,host:"172.30.2.202:27011"}, {_id:2,host:"172.30.2.203:27011"} ] }
{
"_id" : "sh1",
"members" : [
{
"_id" : 0,
"host" : "172.30.2.201:27011"
},
{
"_id" : 1,
"host" : "172.30.2.202:27011"
},
{
"_id" : 2,
"host" : "172.30.2.203:27011"
}
]
}
> rs.initiate( cfg );
{ "ok" : 1 }
sh1:OTHER> rs.status();
{
"set" : "sh1",
"date" : ISODate("2015-10-23T05:36:02.365Z"),
"myState" : 1,
"members" : [
{
"_id" : 0,
"name" : "172.30.2.201:27011",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 406,
"optime" : Timestamp(1445578557, 1),
"optimeDate" : ISODate("2015-10-23T05:35:57Z"),
"electionTime" : Timestamp(1445578561, 1),
"electionDate" : ISODate("2015-10-23T05:36:01Z"),
"configVersion" : 1,
"self" : true
},
{
"_id" : 1,
"name" : "172.30.2.202:27011",
"health" : 1,
"state" : 5,
"stateStr" : "STARTUP2",
"uptime" : 5,
"optime" : Timestamp(0, 0),
"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
"lastHeartbeat" : ISODate("2015-10-23T05:36:01.168Z"),
"lastHeartbeatRecv" : ISODate("2015-10-23T05:36:01.175Z"),
"pingMs" : 0,
"configVersion" : 1
},
{
"_id" : 2,
"name" : "172.30.2.203:27011",
"health" : 1,
"state" : 5,
"stateStr" : "STARTUP2",
"uptime" : 5,
"optime" : Timestamp(0, 0),
"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
"lastHeartbeat" : ISODate("2015-10-23T05:36:01.167Z"),
"lastHeartbeatRecv" : ISODate("2015-10-23T05:36:01.172Z"),
"pingMs" : 0,
"configVersion" : 1
}
],
"ok" : 1
}
sh1:PRIMARY>
bye

配置分片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
$ mongo --port 30000
MongoDB shell version: 3.0.6
connecting to: 127.0.0.1:30000/test
mongos> use admin;
switched to db admin
mongos> sh.addShard("sh0/172.30.2.201:27010,172.30.2.202:27010,172.30.2.203:27010");
{ "shardAdded" : "sh0", "ok" : 1 }
mongos> sh.addShard("sh1/172.30.2.201:27011,172.30.2.202:27011,172.30.2.203:27011");
{ "shardAdded" : "sh1", "ok" : 1 }
mongos> use mydb;
switched to db mydb
mongos> db.createCollection("test");
{
"ok" : 1,
"$gleStats" : {
"lastOpTime" : Timestamp(1444358911, 1),
"electionId" : ObjectId("56172a4bc03d9b1667f8e928")
}
}
mongos> sh.enableSharding("mydb");
{ "ok" : 1 }
mongos> sh.shardCollection("mydb.test", {"_id":1});
{ "collectionsharded" : "mydb.test", "ok" : 1 }
mongos> sh.status();
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("561728b4030ea038bcb57fa0")
}
shards:
{ "_id" : "sh0", "host" : "sh0/172.30.2.201:27010,172.30.2.202:27010,172.30.2.203:27010" }
{ "_id" : "sh1", "host" : "sh1/172.30.2.201:27011,172.30.2.202:27011,172.30.2.203:27011" }
balancer:
Currently enabled: yes
Currently running: no
Failed balancer rounds in last 5 attempts: 0
Migration Results for the last 24 hours:
No recent migrations
databases:
{ "_id" : "admin", "partitioned" : false, "primary" : "config" }
{ "_id" : "mydb", "partitioned" : true, "primary" : "sh0" }
mydb.test
shard key: { "_id" : 1 }
chunks:
sh0 1
{ "_id" : { "$minKey" : 1 } } -->> { "_id" : { "$maxKey" : 1 } } on : sh0 Timestamp(1, 0)

可见分片已经配置完成了

添加开机启动项

1
2
3
4
5
6
$ sudo vim /etc/rc.local
ulimit -SHn 65535
/opt/mongodb/bin/mongod --config /data/mongodb/conf/sh0/mongodb.conf
/opt/mongodb/bin/mongod --config /data/mongodb/conf/sh1/mongodb.conf
/opt/mongodb/bin/mongod --config /data/mongodb/conf/cf0/config.conf
/opt/mongodb/bin/mongos --config /data/mongodb/conf/ms0/mongos.conf

备注

虽然也是3台机器,使用分片的好处是可以把两个分片的primary设置在不同的节点,这个可以分摊单节点的压力,当然有更多机器就可以把分片放到不同机器上。

按照mongodb官网的要求, 需要多余多处理器需要关闭muna,以及其他参数 参加mongodb check list

1
mongodb check list

注意

修改iptables可能导致连接断开, 对于远程连接的用户, 需要在经过充分测试后在修改,
对于懒人可以设置一个crontab, 在你修改iptables的过程中每隔30分钟清空一次iptables规则, 这样在误操作的情况下依然保障可以正常登录系统

1
2
iptables -P INPUT ACCEPT
iptables -t filter -F

不放心的话可以将所有表默认规则都设置为ACCEPT, 然后情况所有规则

基本概念

iptables 可以检测、修改、转发、重定向和丢弃 IPv4 数据包。过滤 IPv4 数据包的代码已经内置于内核中,并且按照不同的目的被组织成 表 的集合。表 由一组预先定义的 链 组成,链 包含遍历顺序规则。每一条规则包含一个谓词的潜在匹配和相应的动作(称为 目标),如果谓词为真,该动作会被执行。也就是说条件匹配。iptables 是用户工具,允许用户使用 链 和 规则。

阅读全文 »

原帖地址: http://blog.itpub.net/519536/viewspace-607549/

该文档配置环境是RHEL,不同系统可能会有差别,本人测试过centos,ubuntu

1.确认VNC是否安装

默认情况下,Red Hat Enterprise Linux安装程序会将VNC服务安装在系统上。
确认是否已经安装VNC服务及查看安装的VNC版本

[root@testdb ~]# rpm -q vnc-server
vnc-server-4.1.2-9.el5
[root@testdb ~]#

若系统没有安装,可以到操作系统安装盘的Server目录下找到VNC服务的RPM安装包vnc-server-4.1.2-9.el5.x86_64.rpm,安装命令如下

rpm -ivh /mnt/Server/vnc-server-4.1.2-9.el5.x86_64.rpm

2.启动VNC服务

使用vncserver命令启动VNC服务,命令格式为“vncserver :桌面号”,其中“桌面号”用“数字”的方式表示,每个用户连个需要占用1个桌面
启动编号为1的桌面示例如下

[root@testdb ~]# vncserver :1

You will require a password to access your desktops.

Password:
Verify:
xauth:  creating new authority file /root/.Xauthority

New 'testdb:1 (root)' desktop is testdb:1

Creating default startup script. /root/.vnc/xstartup
Starting applications specified in /root/.vnc/xstartup
Log file is /root/.vnc/testdb:1.log

以上命令执行的过程中,因为是第一次执行,需要输入密码,这个密码被加密保存在用户主目录下的.vnc子目录(/root/.vnc/passwd)中;同时在用户主目录下的.vnc子目录中为用户自动建立xstartup配置文件(/root/.vnc/xstartup),在每次启动VND服务时,都会读取该文件中的配置信息。
BTW:/root/.vnc/目录下还有一个“testdb:1.pid”文件,这个文件记录着启动VNC后对应后天操作系统的进程号,用于停止VNC服务时准确定位进程号。

3.VNC服务使用的端口号与桌面号的关系

VNC服务使用的端口号与桌面号相关,VNC使用TCP端口从5900开始,对应关系如下

桌面号为“1” —- 端口号为5901
桌面号为“2” —- 端口号为5902
桌面号为“3” —- 端口号为5903
……

基于Java的VNC客户程序Web服务TCP端口从5800开始,也是与桌面号相关,对应关系如下

桌面号为“1” —- 端口号为5801
桌面号为“2” —- 端口号为5802
桌面号为“3” —- 端口号为5803
……

基于上面的介绍,如果Linux开启了防火墙功能,就需要手工开启相应的端口,以开启桌面号为“1”相应的端口为例,命令如下

[root@testdb ~]# iptables -I INPUT -p tcp --dport 5901 -j ACCEPT
[root@testdb ~]# iptables -I INPUT -p tcp --dport 5801 -j ACCEPT

4.测试VNC服务

第一种方法是使用VNC Viewer软件登陆测试,操作流程如下

启动VNC Viewer软件 –> Server输入“144.194.192.183:1” –> 点击“OK” –> Password输入登陆密码 –> 点击“OK”登陆到X-Window图形桌面环境 –> 测试成功

第二种方法是使用Web浏览器(如Firefox,IE,Safari)登陆测试,操作流程如下

地址栏输入http://144.194.192.183:5801/ –> 出现VNC viewer for Java(此工具是使用Java编写的VNC客户端程序)界面,同时跳出VNC viewer对话框,在Server处输入“144.194.192.183:1”点击“OK” –> Password输入登陆密码 –> 点击“OK”登陆到X-Window图形桌面环境 –> 测试成功

(注:VNC viewer for Java需要JRE支持,如果页面无法显示,表示没有安装JRE,可以到http://java.sun.com/javase/downloads/index_jdk5.jsp这里下载最新的JRE进行安装)

5.配置VNC图形桌面环境为KDE或GNOME桌面环境

如果您是按照我的上面方法进行的配置的,登陆到桌面后效果是非常简单的,只有一个Shell可供使用,这是为什么呢?怎么才能看到可爱并且美丽的KDE或GNOME桌面环境呢?回答如下
之所以那么的难看,是因为VNC服务默认使用的是twm图形桌面环境的,可以在VNC的配置文件xstartup中对其进行修改,先看一下这个配置文件

[root@testdb ~]# vi /root/.vnc/xstartup
#!/bin/sh

# Uncomment the following two lines for normal desktop:
# unset SESSION_MANAGER
# exec /etc/X11/xinit/xinitrc

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &
xterm -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
twm &

将这个xstartup文件的最后一行修改为“startkde &”,再重新启动vncserver服务后就可以登陆到KDE桌面环境
将这个xstartup文件的最后一行修改为“gnome-session &”,再重新启动vncserver服务后就可以登陆到GNOME桌面环境

重新启动vncserver服务的方法:

[root@testdb ~]# vncserver -kill :1
[root@testdb ~]# vncserver :1

6.配置多个桌面

可以使用如下的方法启动多个桌面的VNC

vncserver :1
vncserver :2
vncserver :3
……

但是这种手工启动的方法在服务器重新启动之后将失效,因此,下面介绍如何让系统自动管理多个桌面的VNC,方法是将需要自动管理的信息添加到/etc/sysconfig/vncservers配置文件中,先以桌面1为root用户桌面2为oracle用户为例进行配置如下:
格式为:VNCSERVERS=”桌面号:使用的用户名 桌面号:使用的用户名”

[root@testdb ~]# vi /etc/sysconfig/vncservers
VNCSERVERS="1:root 2:oracle"
VNCSERVERARGS[1]="-geometry 1024x768"
VNCSERVERARGS[2]="-geometry 1024x768"

7.修改VNC访问的密码

使用命令vncpasswd对不同用户的VNC的密码进行修改,一定要注意,如果配置了不同用户的VNC需要分别到各自用户中进行修改,例如在我的这个实验中,root用户和oracle用户需要分别修改,修改过程如下:

[root@testdb ~]# vncpasswd
Password:
Verify:
[root@testdb ~]#

8.启动和停止VNC服务

1)启动VNC服务命令

[root@testdb ~]# /etc/init.d/vncserver start
Starting VNC server: 1:root
New 'testdb:1 (root)' desktop is testdb:1

Starting applications specified in /root/.vnc/xstartup
Log file is /root/.vnc/testdb:1.log

2:oracle
New 'testdb:2 (oracle)' desktop is testdb:2

Starting applications specified in /home/oracle/.vnc/xstartup
Log file is /home/oracle/.vnc/testdb:2.log

                              [  OK  ]

2)停止VNC服务命令

[root@testdb ~]# /etc/init.d/vncserver stop
Shutting down VNC server: 1:root 2:oracle                  [  OK  ]

3)重新启动VNC服务命令

[root@testdb ~]# /etc/init.d/vncserver restart
Shutting down VNC server: 1:root 2:oracle                  [  OK  ]
Starting VNC server: 1:root
New 'testdb:1 (root)' desktop is testdb:1

Starting applications specified in /root/.vnc/xstartup
Log file is /root/.vnc/testdb:1.log

2:oracle
New 'testdb:2 (oracle)' desktop is testdb:2

Starting applications specified in /home/oracle/.vnc/xstartup
Log file is /home/oracle/.vnc/testdb:2.log

                              [  OK  ]

4)设置VNC服务随系统启动自动加载
第一种方法:使用“ntsysv”命令启动图形化服务配置程序,在vncserver服务前加上星号,点击确定,配置完成。
第二种方法:使用“chkconfig”在命令行模式下进行操作,命令使用如下(预知chkconfig详细使用方法请自助式man一下)

[root@testdb ~]# chkconfig vncserver on
[root@testdb ~]# chkconfig --list vncserver
vncserver       0:off   1:off   2:on    3:on    4:on    5:on    6:off

9.小结

VNC的详细配置方法到此已经写完,希望能对大家有帮助。VNC对于远程调用图形化界面来说非常的轻巧和便捷,善用之!

Good luck.

– The End –

1. 客户端生成公钥文件

ssh-keygen -t rsa (这样生成就可以了,man具体参数)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@arch ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
1c:ce:14:77:97:35:72:9a:0f:ac:d4:57:3e:ad:3d:23 root@arch
The key's randomart image is:
+---[RSA 2048]----+
| . . ...=o|
| o .o.*.+|
| o . * oo|
| = .. . +o.|
| S . E.+.|
| . o|
| |
| |
| |
+-----------------+

会生成id_rsaid_rsa.pub文件,前者是私钥,后者是需要上传到服务器的公钥

2.把公钥放到服务器上

1
scp .ssh/id_rsa.pub [email protected]:/home/mike/.ssh

使用scp简单方便

3.修改sshd的配置(/etc/ssh/sshd_config)

找到以下内容,并去掉注释符”#“

1
2
3
4
5
=========================
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
=========================

配置authorized_keys文件

若’~/.ssh/authorized_keys’不存在,则建立.ssh文件夹和authorized_keys文件.
将上文中客户机id_rsa.pub的内容拷贝到authorized_keys中.

注意:

用户目录权限为 755 或者 700就是不能是77x
.ssh目录权限必须为755(不能775)
rsa_id.pub 及authorized_keys权限必须为644(或600)
rsa_id权限必须为600

4.重启sshd.

$ /etc/init.d/sshd restart

5.测试

客户机执行:

ssh -v user@host (-v 调试模式)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to xxx.xxx.xxx.xxx [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.7
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3
debug1: match: OpenSSH_5.3 pat OpenSSH_5* compat 0x0c000000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr [email protected] none
debug1: kex: client->server aes128-ctr [email protected] none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<3072<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA fc:96:ed:b8:79:b6:99:7e:58:f2:4c:58:58:e7:3a:17
debug1: Host '127.0.0.1' is known and matches the RSA host key.
debug1: Found key in /root/.ssh/known_hosts:6
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /root/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: Authentication succeeded (publickey).
Authenticated to 127.0.0.1 ([127.0.0.1]:22).
debug1: channel 0: new [client-session]
debug1: Requesting [email protected]
debug1: Entering interactive session.

会显示一些登陆信息.
若登陆失败,或者仍然要输入密码,可以在服务器查看日志文件:/var/log/secure.

若登陆成功,则以后就可以用’ssh user@host’ 直接登陆了,不用输入密码.

附录(sshd配置文件ubuntu14.04默认):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
ListenAddress 127.0.0.1
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin without-password
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

zabbix监控

通过导入/导出zabbix配置文件,我们可以将自己写好的模板等配置在网络上分享,我们也可以导入网络上分享的配置文件,配置文件有两种格式,分为xml与json,通过zabbix管理界面可以导出xml,通过zabbix api可以导出json与xml格式配置。

可导出的项目

  • host groups (只能通过zabbix api导出)
  • templates (包含所有预其直接关联的items, triggers, graphs, screens, discovery rules和link的template)
  • hosts (包含所有与它直接相关的items, triggers, graphs, discovery rules 和link的template)
  • network maps (包含所有相关图片; map export/import 从Zabbix 1.8.2开始被支持)
  • images
  • screens

导出详细说明

  • 导出为单个文件
  • Host and template从模板中link过来的实体 (items, triggers, graphs, discovery rules)不会导出,通过low-level创建的实体不会导出。但是导如之后,会重新创建link的实体。
  • 与low-level实体相关联的实体不会被导出,例如触发器。
  • web items相关的Triggers and graphs不支持导出

导入详细说明

  • 导如过程中遇到任何错误,都会停止导入
  • 支持导如xml与json格式文件,并且文件名后缀必须为.xml或者.json

XML文件基本格式

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
<version>2.0</version>
<date>2015-02-09T05:58:54Z</date>
</zabbix_export>

xml默认头

1
<?xml version="1.0" encoding="UTF-8"?>

zabbix xml root 元素

1
<zabbix_export>

导出版本

1
<version>2.0</version>

导出日期

1
<date>2015-02-09T05:58:54Z</date>

导出模板

configuration>>templates>>勾选需要导出的模板>>左下角下拉列表选择”Export selected”,点击Go,保存xml即可。

如下是我的一个测试模板内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
<version>2.0</version>
<date>2015-02-09T07:34:25Z</date>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<templates>
<template>
<template>A_Template_For_Discovery</template>
<name>A_Template_For_Discovery</name>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<applications>
<application>
<name>Network</name>
</application>
</applications>
<items/>
<discovery_rules>
<discovery_rule>
<name>PING</name>
<type>0</type>
<snmp_community/>
<snmp_oid/>
<key>net.if.icmpping</key>
<delay>30</delay>
<status>0</status>
<allowed_hosts/>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<delay_flex/>
<params/>
<ipmi_sensor/>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<filter>{#LOC}:^cn|^jp</filter>
<lifetime>30</lifetime>
<description/>
<item_prototypes>
<item_prototype>
<name>PING IP $1</name>
<type>3</type>
<snmp_community/>
<multiplier>1</multiplier>
<snmp_oid/>
<key>icmpping[{#IPADD},4,,,]</key>
<delay>30</delay>
<history>90</history>
<trends>365</trends>
<status>0</status>
<value_type>3</value_type>
<allowed_hosts/>
<units/>
<delta>0</delta>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<formula>1000</formula>
<delay_flex/>
<params/>
<ipmi_sensor/>
<data_type>0</data_type>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Network</name>
</application>
</applications>
<valuemap/>
</item_prototype>
</item_prototypes>
<trigger_prototypes/>
<graph_prototypes/>
<host_prototypes/>
</discovery_rule>
</discovery_rules>
<macros/>
<templates>
<template>
<name>Template OS <a href="http://www.ttlsa.com/linux/" title="linux"target="_blank">Linux</a></name>
</template>
</templates>
<screens/>
</template>
</templates>
</zabbix_export>

与模板相关的数据都在xml里,它link的模板”Template OS Linux”并未导出。而是通过如下元素将他关联起来,下回导入还会link一次。

1
2
3
4
5
<templates>
<template>
<name>Template OS Linux</name>
</template>
</templates>

通过此方式,大家可以互相共享配置文件,提高效率。]]>

看到一个挺不错的网址, 列出了一些常用命令的语法, 这里参考 https://www.hackfun.org/kali-tools/kali-tools-zh.html

nmap包说明

NMAP(“网络映射”)是一个自由和开放源码(许可证)工具进行网络发现和安全审计。许多系统和网络管理员也觉得有用,如网络库存,管理服务升级计划和监控主机或服务的正常运行时间的任务。 NMAP使用原始IP包以新颖的方式来确定哪些主机是在网络上可用,这些主机正在提供什么样的服务(应用程序的名称和版本),什么操作系统(和OS版本),它们都在运行,什么类型的分组过滤器/防火墙在使用中,和许多其他特性。它的目的是快速扫描大型网络,但能正常工作对单个主机。 Nmap的运行在所有主要计算机操作系统,和官方的二进制软件包可用于Linux,Windows和Mac OS X的除了经典的命令行Nmap的可执行文件,nmap的套件包括一个先进的GUI和结果浏览器(Zenmap)一种灵活的数据传送,重定向和调试工具(NCAT),用于比较扫描结果(Ndiff)的实用程序,并且一个分组产生和响应分析工具(Nping)。

Nmap的被评为“年度安全产品”,由Linux杂志,信息世界,LinuxQuestions.Org和Codetalker摘要。有人甚至功能十二电影,包括重装上阵,虎胆龙威4,女孩龙纹身,和谍影重重。

Nmap是比较合适?

  • 灵活:支持数十台先进的技术映射出网络充满了IP过滤,防火墙,路由器和其他障碍。这包括许多端口扫描机制(包括TCP和UDP),操作系统检测,版本检测,ping扫描,等等。请参阅文档页面。
  • 功能强大:Nmap的已被用来扫描字面上机数十万庞大的网络。
  • 便携性:大多数操作系统都支持,包括Linux,微软的Windows,FreeBSD下,OpenBSD系统,Solaris和IRIX,Mac OS X中,HP-UX,NetBSD的,SUN OS,Amiga的,等等。
  • 很简单:虽然Nmap的提供了一套丰富的先进功能的电力用户,你可以开始作为简称为“NMAP -v -A targethost”。这两种传统的命令行和图形(GUI)版本可供选择,以满足您的喜好。二进制文件是为那些谁不希望从源代码编译的Nmap。
  • 免费:在Nmap的项目的主要目标是帮助使互联网更安全一点,并为管理员提供/审计/黑客探索他们的网络的先进工具。 NMAP是可以免费下载,并且还配备了完整的源代码,你可以修改,并根据许可协议的条款重新分发。
  • 有据可查:重大努力已投入全面和最新的手册页,白皮书,教程,甚至一整本书!发现他们在这里多国语言。
  • 支持:虽然Nmap的同时没有担保,这是深受开发者和用户一个充满活力的社区提供支持。大多数这种相互作用发生在Nmap的邮件列表。大多数的bug报告和问题应该发送到NMAP-dev邮件列表,但你读的指引之后。我们建议所有用户订阅低流量的nmap-黑客公布名单。您还可以找到的Nmap在Facebook和Twitter。对于即时聊天,加入Freenode上或连接到efnet的#nmap通道。
  • 好评:Nmap的赢得了无数奖项,包括“信息安全产品奖”,由Linux杂志,信息世界和Codetalker文摘。它已被刊登在数以百计的杂志文章,几部电影,几十本书,一本漫画书系列。访问进一步的细节新闻页面。
  • 热门:成千上万的人下载Nmap的每一天,它包含许多操作系统(红帽Linux,Debian的Linux中,Gentoo的,FreeBSD下,OpenBSD的,等等)。它是在Freshmeat.Net库的前十名(总分30000)方案之间。这是很重要的,因为它的Nmap借给其充满活力的发展和用户的支持群体。

资料来源:http://nmap.org/
Nmap的首页 | 卡利Nmap的回购

作者:陀
许可:GPL第二版

包含在nmap包工具

nping - 网络数据包生成工具/ Ping实用程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
root@kali:~# nping -h
Nping 0.6.40 ( http://nmap.org/nping )
Usage: nping [Probe mode] [Options] {target specification}

TARGET SPECIFICATION:
Targets may be specified as hostnames, IP addresses, networks, etc.
Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.*.1-24
PROBE MODES:
--tcp-connect : Unprivileged TCP connect probe mode.
--tcp : TCP probe mode.
--udp : UDP probe mode.
--icmp : ICMP probe mode.
--arp : ARP/RARP probe mode.
--tr, --traceroute : Traceroute mode (can only be used with
TCP/UDP/ICMP modes).
TCP CONNECT MODE:
-p, --dest-port <port spec> : Set destination port(s).
-g, --source-port <portnumber> : Try to use a custom source port.
TCP PROBE MODE:
-g, --source-port <portnumber> : Set source port.
-p, --dest-port <port spec> : Set destination port(s).
--seq <seqnumber> : Set sequence number.
--flags <flag list> : Set TCP flags (ACK,PSH,RST,SYN,FIN...)
--ack <acknumber> : Set ACK number.
--win <size> : Set window size.
--badsum : Use a random invalid checksum.
UDP PROBE MODE:
-g, --source-port <portnumber> : Set source port.
-p, --dest-port <port spec> : Set destination port(s).
--badsum : Use a random invalid checksum.
ICMP PROBE MODE:
--icmp-type <type> : ICMP type.
--icmp-code <code> : ICMP code.
--icmp-id <id> : Set identifier.
--icmp-seq <n> : Set sequence number.
--icmp-redirect-addr <addr> : Set redirect address.
--icmp-param-pointer <pnt> : Set parameter problem pointer.
--icmp-advert-lifetime <time> : Set router advertisement lifetime.
--icmp-advert-entry <IP,pref> : Add router advertisement entry.
--icmp-orig-time <timestamp> : Set originate timestamp.
--icmp-recv-time <timestamp> : Set receive timestamp.
--icmp-trans-time <timestamp> : Set transmit timestamp.
ARP/RARP PROBE MODE:
--arp-type <type> : Type: ARP, ARP-reply, RARP, RARP-reply.
--arp-sender-mac <mac> : Set sender MAC address.
--arp-sender-ip <addr> : Set sender IP address.
--arp-target-mac <mac> : Set target MAC address.
--arp-target-ip <addr> : Set target IP address.
IPv4 OPTIONS:
-S, --source-ip : Set source IP address.
--dest-ip <addr> : Set destination IP address (used as an
alternative to {target specification} ).
--tos <tos> : Set type of service field (8bits).
--id <id> : Set identification field (16 bits).
--df : Set Don't Fragment flag.
--mf : Set More Fragments flag.
--ttl <hops> : Set time to live [0-255].
--badsum-ip : Use a random invalid checksum.
--ip-options <S|R [route]|L [route]|T|U ...> : Set IP options
--ip-options <hex string> : Set IP options
--mtu <size> : Set MTU. Packets get fragmented if MTU is
small enough.
IPv6 OPTIONS:
-6, --IPv6 : Use IP version 6.
--dest-ip : Set destination IP address (used as an
alternative to {target specification}).
--hop-limit : Set hop limit (same as IPv4 TTL).
--traffic-class <class> : : Set traffic class.
--flow <label> : Set flow label.
ETHERNET OPTIONS:
--dest-mac <mac> : Set destination mac address. (Disables
ARP resolution)
--source-mac <mac> : Set source MAC address.
--ether-type <type> : Set EtherType value.
PAYLOAD OPTIONS:
--data <hex string> : Include a custom payload.
--data-string <text> : Include a custom ASCII text.
--data-length <len> : Include len random bytes as payload.
ECHO CLIENT/SERVER:
--echo-client <passphrase> : Run Nping in client mode.
--echo-server <passphrase> : Run Nping in server mode.
--echo-port <port> : Use custom <port> to listen or connect.
--no-crypto : Disable encryption and authentication.
--once : Stop the server after one connection.
--safe-payloads : Erase application data in echoed packets.
TIMING AND PERFORMANCE:
Options which take <time> are in seconds, or append 'ms' (milliseconds),
's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m, 0.25h).
--delay <time> : Adjust delay between probes.
--rate <rate> : Send num packets per second.
MISC:
-h, --help : Display help information.
-V, --version : Display current version number.
-c, --count <n> : Stop after <n> rounds.
-e, --interface <name> : Use supplied network interface.
-H, --hide-sent : Do not display sent packets.
-N, --no-capture : Do not try to capture replies.
--privileged : Assume user is fully privileged.
--unprivileged : Assume user lacks raw socket privileges.
--send-eth : Send packets at the raw Ethernet layer.
--send-ip : Send packets using raw IP sockets.
--bpf-filter <filter spec> : Specify custom BPF filter.
OUTPUT:
-v : Increment verbosity level by one.
-v[level] : Set verbosity level. E.g: -v4
-d : Increment debugging level by one.
-d[level] : Set debugging level. E.g: -d3
-q : Decrease verbosity level by one.
-q[N] : Decrease verbosity level N times
--quiet : Set verbosity and debug level to minimum.
--debug : Set verbosity and debug to the max level.
EXAMPLES:
nping scanme.nmap.org
nping --tcp -p 80 --flags rst --ttl 2 192.168.1.1
nping --icmp --icmp-type time --delay 500ms 192.168.254.254
nping --echo-server "public" -e wlan0 -vvv
nping --echo-client "public" echo.nmap.org --tcp -p1-1024 --flags ack

SEE THE MAN PAGE FOR MANY MORE OPTIONS, DESCRIPTIONS, AND EXAMPLES

ndiff - 实用工具来比较的Nmap扫描结果

1
2
3
4
5
6
7
8
9
10
root@kali:~# ndiff -h
Usage: /usr/bin/ndiff [option] FILE1 FILE2
Compare two Nmap XML files and display a list of their differences.
Differences include host state changes, port state changes, and changes to
service and OS detection.

-h, --help display this help
-v, --verbose also show hosts and ports that haven't changed.
--text display output in text format (default)
--xml display output in XML format

NCAT - 串联并重定向插座

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
root@kali:~# ncat -h
Ncat 6.40 ( http://nmap.org/ncat )
Usage: ncat [options] [hostname] [port]

Options taking a time assume seconds. Append 'ms' for milliseconds,
's' for seconds, 'm' for minutes, or 'h' for hours (e.g. 500ms).
-4 Use IPv4 only
-6 Use IPv6 only
-U, --unixsock Use Unix domain sockets only
-C, --crlf Use CRLF for EOL sequence
-c, --sh-exec <command> Executes the given command via /bin/sh
-e, --exec <command> Executes the given command
--lua-exec <filename> Executes the given Lua script
-g hop1[,hop2,...] Loose source routing hop points (8 max)
-G <n> Loose source routing hop pointer (4, 8, 12, ...)
-m, --max-conns <n> Maximum <n> simultaneous connections
-h, --help Display this help screen
-d, --delay <time> Wait between read/writes
-o, --output <filename> Dump session data to a file
-x, --hex-dump <filename> Dump session data as hex to a file
-i, --idle-timeout <time> Idle read/write timeout
-p, --source-port port Specify source port to use
-s, --source addr Specify source address to use (doesn't affect -l)
-l, --listen Bind and listen for incoming connections
-k, --keep-open Accept multiple connections in listen mode
-n, --nodns Do not resolve hostnames via DNS
-t, --telnet Answer Telnet negotiations
-u, --udp Use UDP instead of default TCP
--sctp Use SCTP instead of default TCP
-v, --verbose Set verbosity level (can be used several times)
-w, --wait <time> Connect timeout
--append-output Append rather than clobber specified output files
--send-only Only send data, ignoring received; quit on EOF
--recv-only Only receive data, never send anything
--allow Allow only given hosts to connect to Ncat
--allowfile A file of hosts allowed to connect to Ncat
--deny Deny given hosts from connecting to Ncat
--denyfile A file of hosts denied from connecting to Ncat
--broker Enable Ncat's connection brokering mode
--chat Start a simple Ncat chat server
--proxy <addr[:port]> Specify address of host to proxy through
--proxy-type <type> Specify proxy type ("http" or "socks4")
--proxy-auth <auth> Authenticate with HTTP or SOCKS proxy server
--ssl Connect or listen with SSL
--ssl-cert Specify SSL certificate file (PEM) for listening
--ssl-key Specify SSL private key (PEM) for listening
--ssl-verify Verify trust and domain name of certificates
--ssl-trustfile PEM file containing trusted SSL certificates
--version Display Ncat's version information and exit

See the ncat(1) manpage for full options, descriptions and usage examples

NMAP - 网络映射

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
root@kali:~# nmap -h
Nmap 6.40 ( http://nmap.org )
Usage: nmap [Scan Type(s)] [Options] {target specification}
TARGET SPECIFICATION:
Can pass hostnames, IP addresses, networks, etc.
Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
-iL <inputfilename>: Input from list of hosts/networks
-iR <num hosts>: Choose random targets
--exclude <host1[,host2][,host3],...>: Exclude hosts/networks
--excludefile <exclude_file>: Exclude list from file
HOST DISCOVERY:
-sL: List Scan - simply list targets to scan
-sn: Ping Scan - disable port scan
-Pn: Treat all hosts as online -- skip host discovery
-PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports
-PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes
-PO[protocol list]: IP Protocol Ping
-n/-R: Never do DNS resolution/Always resolve [default: sometimes]
--dns-servers <serv1[,serv2],...>: Specify custom DNS servers
--system-dns: Use OS's DNS resolver
--traceroute: Trace hop path to each host
SCAN TECHNIQUES:
-sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans
-sU: UDP Scan
-sN/sF/sX: TCP Null, FIN, and Xmas scans
--scanflags <flags>: Customize TCP scan flags
-sI <zombie host[:probeport]>: Idle scan
-sY/sZ: SCTP INIT/COOKIE-ECHO scans
-sO: IP protocol scan
-b <FTP relay host>: FTP bounce scan
PORT SPECIFICATION AND SCAN ORDER:
-p <port ranges>: Only scan specified ports
Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
-F: Fast mode - Scan fewer ports than the default scan
-r: Scan ports consecutively - don't randomize
--top-ports <number>: Scan <number> most common ports
--port-ratio <ratio>: Scan ports more common than <ratio>
SERVICE/VERSION DETECTION:
-sV: Probe open ports to determine service/version info
--version-intensity <level>: Set from 0 (light) to 9 (try all probes)
--version-light: Limit to most likely probes (intensity 2)
--version-all: Try every single probe (intensity 9)
--version-trace: Show detailed version scan activity (for debugging)
SCRIPT SCAN:
-sC: equivalent to --script=default
--script=<Lua scripts>: <Lua scripts> is a comma separated list of
directories, script-files or script-categories
--script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts
--script-args-file=filename: provide NSE script args in a file
--script-trace: Show all data sent and received
--script-updatedb: Update the script database.
--script-help=<Lua scripts>: Show help about scripts.
<Lua scripts> is a comma separted list of script-files or
script-categories.
OS DETECTION:
-O: Enable OS detection
--osscan-limit: Limit OS detection to promising targets
--osscan-guess: Guess OS more aggressively
TIMING AND PERFORMANCE:
Options which take <time> are in seconds, or append 'ms' (milliseconds),
's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).
-T<0-5>: Set timing template (higher is faster)
--min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes
--min-parallelism/max-parallelism <numprobes>: Probe parallelization
--min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies
probe round trip time.
--max-retries <tries>: Caps number of port scan probe retransmissions.
--host-timeout <time>: Give up on target after this long
--scan-delay/--max-scan-delay <time>: Adjust delay between probes
--min-rate <number>: Send packets no slower than <number> per second
--max-rate <number>: Send packets no faster than <number> per second
FIREWALL/IDS EVASION AND SPOOFING:
-f; --mtu <val>: fragment packets (optionally w/given MTU)
-D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys
-S <IP_Address>: Spoof source address
-e <iface>: Use specified interface
-g/--source-port <portnum>: Use given port number
--data-length <num>: Append random data to sent packets
--ip-options <options>: Send packets with specified ip options
--ttl <val>: Set IP time-to-live field
--spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address
--badsum: Send packets with a bogus TCP/UDP/SCTP checksum
OUTPUT:
-oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,
and Grepable format, respectively, to the given filename.
-oA <basename>: Output in the three major formats at once
-v: Increase verbosity level (use -vv or more for greater effect)
-d: Increase debugging level (use -dd or more for greater effect)
--reason: Display the reason a port is in a particular state
--open: Only show open (or possibly open) ports
--packet-trace: Show all packets sent and received
--iflist: Print host interfaces and routes (for debugging)
--log-errors: Log errors/warnings to the normal-format output file
--append-output: Append to rather than clobber specified output files
--resume <filename>: Resume an aborted scan
--stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML
--webxml: Reference stylesheet from Nmap.Org for more portable XML
--no-stylesheet: Prevent associating of XSL stylesheet w/XML output
MISC:
-6: Enable IPv6 scanning
-A: Enable OS detection, version detection, script scanning, and traceroute
--datadir <dirname>: Specify custom Nmap data file location
--send-eth/--send-ip: Send using raw ethernet frames or IP packets
--privileged: Assume that the user is fully privileged
--unprivileged: Assume the user lacks raw socket privileges
-V: Print version number
-h: Print this help summary page.
EXAMPLES:
nmap -v -A scanme.nmap.org
nmap -v -sn 192.168.0.0/16 10.0.0.0/8
nmap -v -iR 10000 -Pn -p 80
SEE THE MAN PAGE (http://nmap.org/book/man.html) FOR MORE OPTIONS AND EXAMPLES

NMAP用法示例

在扫描详细模式(-v),启用操作系统检测,版本检测,脚本扫描,和traceroute(-A),版本检测(-sV)针对目标IP(192.168.1.1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
root@kali:~# nmap -v -A -sV 192.168.1.1

Starting Nmap 6.45 ( http://nmap.org ) at 2014-05-13 18:40 MDT
NSE: Loaded 118 scripts for scanning.
NSE: Script Pre-scanning.
Initiating ARP Ping Scan at 18:40
Scanning 192.168.1.1 [1 port]
Completed ARP Ping Scan at 18:40, 0.06s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 18:40
Completed Parallel DNS resolution of 1 host. at 18:40, 0.00s elapsed
Initiating SYN Stealth Scan at 18:40
Scanning router.localdomain (192.168.1.1) [1000 ports]
Discovered open port 53/tcp on 192.168.1.1
Discovered open port 22/tcp on 192.168.1.1
Discovered open port 80/tcp on 192.168.1.1
Discovered open port 3001/tcp on 192.168.1.1

nping用法示例

使用TCP 模式(-tcp)使用SYN标志探测端口22(-p 22)(-flags SYN)与2(TTL电2)在远程主机上的TTL(192.168.1.1)

ndiff用法示例

对比昨天的端口扫描(yesterday.xml)自即日起扫描(today.xml)

1
2
3
4
5
6
7
8
9
root@kali:~# ndiff yesterday.xml today.xml
-Nmap 6.45 scan initiated Tue May 13 18:46:43 2014 as: nmap -v -F -oX yesterday.xml 192.168.1.1
+Nmap 6.45 scan initiated Tue May 13 18:47:58 2014 as: nmap -v -F -oX today.xml 192.168.1.1

endian.localdomain (192.168.1.1, 00:01:6C:6F:DD:D1):
-Not shown: 96 filtered ports
+Not shown: 97 filtered ports
PORT STATE SERVICE VERSION
-22/tcp open ssh

NCAT用法示例

详细(-v),可以运行/ bin / bash的连接上(-exec“/斌/庆典”),只允许1个IP地址(-ALLOW 192.168.1.123),监听TCP端口4444(-l 4444)上,并让听众开上断开(-keep开)

1
2
3
4
5
6
7
8
9
root@kali:~# ncat -v --exec "/bin/bash" --allow 192.168.1.123 -l 4444 --keep-open
Ncat: Version 6.45 ( http://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 192.168.1.123.
Ncat: Connection from 192.168.1.123:39501.
Ncat: Connection from 192.168.1.15.
Ncat: Connection from 192.168.1.15:60393.
Ncat: New connection denied: not allowed

第一步:安装vsftp pam db4

yum install vsftpd pam* db4*-y

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

Installed:
  db4-cxx.i686 0:4.7.25-16.el6              db4-devel.i686 0:4.7.25-16.el6  db4-devel-static.i686 0:4.7.25-16.el6  db4-java.i686 0:4.7.25-16.el6   
  db4-tcl.i686 0:4.7.25-16.el6              pam-devel.i686 0:1.1.1-10.el6   pam_ldap.i686 0:185-11.el6             pam_pkcs11.i686 0:0.6.2-11.1.el6
  pam_ssh_agent_auth.i686 0:0.9-70.el6_2.2  vsftpd.i686 0:2.2.2-6.el6_2.1 

Dependency Installed:
  pcsc-lite-libs.i686 0:1.5.2-6.el6

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

通过setup对系统服务及防火墙进行配置,然后reboot系统
或者使用命令将vsftp配置为系统服务

chkconfig --level 35 vsftpd on

第二步:配置vsftpd服务的宿主

#useradd vsftpdadmin -s /sbin/nologin

这个vsftpdadmin只是用来替换root的,并不需要登录
PS:一般系统自带一个ftp用户

第三步:建立ftp虚拟宿主帐户

#useradd ftpuser -s /sbin/nologin

这ftpuser只个虚拟帐户的宿主,本身是不用登录的

第四步:配置vsftpd.conf

更改配置前最好备份一下然后再改

vim /etc/vsftpd/vsftpd.conf

修改下面红色字体的部分为蓝色字体的形式,紫色字体是配置原有的

anonymous_enable=YES  -->  anonymous_enable=NO   //不允许匿名用户访问,默认是允许。
#chroot_list_enable=YES  -->  chroot_list_enable=YES      //不允许FTP用户离开自己主目录,默认是被注释掉的。
#chroot_list_file=/etc/vsftpd/chroot_list --> chroot_list_file=/etc/vsftpd/chroot_list  //如果开启了chroot_list_enable=YES,那么一定要开启这个,这条是锁定登录用户只能家目录的位置,如果不开启用户登录时就会报500 OOPS的错。

注意:/etc/vsftp/chroot_list本身是不存在的,这要建立vim /etc/vsftp/chroot_list,然后将帐户输入一行一个,保存就可以了

local_enable=YES      //允许本地用户访问,默认就是YES,不用改
write_enable=YES      //允许写入,默认是YES,不用改
local_umask=022       //上传后文件的权限掩码,不用改
dirmessage_enable=YES //开启目录标语,默认是YES,开不开无所谓,我是默认就行
xferlog_enable=YES    //开启日志,默认是YES,不用改
connect_from_port_20=YES   //设定连接端口20
xferlog_std_format=YES   //设定vsftpd的服务日志保存路径,不用改
(这步后面要有几个操作才能运行,也就是touch这个文件(见第五步),因为它本身不存在,而且还要给文件写入的权限)
#idle_session_timeout=600  -->  idle_session_timeout=600  //会话超时,客户端连接到ftp但未操作,默认被注释掉,可根据个人情况修改
#async_abor_enable=YES  -->   async_abor_enable=YES     //支持异步传输功能,默认是注释掉的,去掉注释
#ascii_upload_enable=YES  -->   ascii_upload_enable=YES   //支持ASCII模式的下载功能,默认是注释掉的,去掉注释
#ascii_download_enable=YES  -->   ascii_download_enable=YES   //支持ASCII模式的上传功能,默认是注释掉的,去掉注释
#ftpd_banner=Welcome to blah FTP service  //FTP的登录欢迎语,本身是被注释掉的,去不去都行
#chroot_local_user=YES  --> chroot_local_user=YES    //禁止本地用户登出自己的FTP主目录,本身被注释掉,去掉注释
pam_service_name=vsftpd  //设定pam服务下vsftpdd的验证配置文件名,不用改
userlist_enable=YES    //拒绝登录用户名单,不用改
TCP_wrappers=YES    //限制主机对VSFTP服务器的访问,不用改(通过/etc/hosts.deny和/etc/hosts.allow这两个文件来配置)
增加
guest_enable=YES    //设定启用虚拟用户功能。
guest_username=ftpuser   //指定虚拟用户的宿主用户。
virtual_use_local_privs=YES   //设定虚拟用户的权限符合他们的宿主用户。
user_config_dir=/etc/vsftpd/vconf   //设定虚拟用户个人Vsftp的配置文件存放路径

第五步:建立日志文件

#touch /var/log/vsftpd.log    //日志文件
#chown vsftpdadmin.vsftpdadmin /var/log/vsftpd.log   //属于vsftpdadmin这个宿主

第六步:建立虚拟用户文件

#mkdir /etc/vsftpd/vconf/
#touch /etc/vsftpd/vconf/vir_user

第七步:建立虚拟用户

#vim /etc/vsftpd/vconf/vir_user
virtualuser           //用户名
12345678           //密码

注意:第一行用户名,第二行是上一行用户名的密码,其他人的以此类推

第八步:生成数据库

#db_load -T -t hash -f /etc/vsftpd/vconf/vir_user /etc/vsftpd/vconf/vir_user.db

第九步:设置数据库文件的访问权限

#chmod 600 /etc/vsftpd/vconf/vir_user.db
#chmod 600 /etc/vsftpd/vconf/vir_user

第十步:修改/etc/pam.d/vsftpd内容

echo "auth required pam_userdb.so db=/etc/vsftpd/vconf/vir_user" &gt; /etc/pam.d/vsftpd
echo "account required pam_userdb.so db=/etc/vsftpd/vconf/vir_user" &gt;&gt; /etc/pam.d/vsftpd

第十一步:创建用户的配置文件

注意:用户配置文件的名字要和创建的“虚拟用户”名字对应

#touch /etc/vsftpd/vconf/virtualuser
#vim /etc/vsftpd/vconf/virtualuser

输入:

local_root=/home/virtualuser           //虚拟用户的个人目录路径
anonymous_enable=NO
write_enable=YES
local_umask=022
anon_upload_enable=NO
anon_mkdir_write_enable=NO
idle_session_timeout=600
data_connection_timeout=120
max_clients=10
max_per_ip=5
local_max_rate=1048576     //本地用户的最大传输速度,单位是Byts/s,我设定的是10M

PS:
vsftpd可以对每个用户特别限制.
只要给那个用户建立一个设置文件,然后在文件里设置

在vsftpd.conf里加
user_config_dir=/etc/vsftpd/vsftpd_user_conf,这是文件夹.当然你可以自己选把用户文件放在哪
在此文件夹里新建一个文件,跟用户名相同.VSFTPD会比对用户名和用户设置文件.

在文件里加
local_root=PATH to directory就可以更改用户的home directory
local_max_rate=XXXX就可以限制此用户的带宽.
cmds_allowed=XXXXX, 此用户可以使用的指令

# ABOR - abort a file transfer
# CWD - change working directory
# DELE - delete a remote file
# LIST - list remote files
# MDTM - return the modification time of a file
# MKD - make a remote directory
# NLST - name list of remote directory
# PASS - send password
# PASV - enter passive mode
# PORT - open a data port
# PWD - print working directory
# QUIT - terminate the connection
# RETR - retrieve a remote file
# RMD - remove a remote directory
# RNFR - rename from
# RNTO - rename to
# SITE - site-specific commands
# SIZE - return the size of a file
# STOR - store a file on the remote host
# TYPE - set transfer type
# USER - send username
#
# less common commands:
# ACCT* - send account information
# APPE - append to a remote file
# CDUP - CWD to the parent of the current directory
# HELP - return help on using the server
# MODE - set transfer mode
# NOOP - do nothing
# REIN* - reinitialize the connection
# STAT - return server status
# STOU - store a file uniquely
# STRU - set file transfer structure
# SYST - return system type

参数说明:
LIST 文件或目录列表

STOR 存储文件

MKD 创建目录

CWD 改变目录

ABOR 终止进程

REST 断点续传


在线使用的脚本

local_root=/home/dbbackup
cmds_allowed=MKD,LIST,PASV,ABOR,REST,NLST,RMD,RNFR,FNTO,SIZE,PORT,STOR,QUIT
local_max_rate=80000000

前提配置文件中要开启:

tcp_wrappers=YES

限制ip访问,只使用hosts.allow文件即可,不用动hosts.deny文件

vsftpd:222.90.72.87 61.150.91.10:allow
vsftpd:all:deny

第十一步:建立虚拟用户目录

如果不建立虚拟用户的个人目录,那么所有的虚拟用户登录后所在的目录都是同一个目录下

# mkdir /home/virtualuser
# chown ftpuser.ftpuser ./virtualuser
# chmod 600 /home/virtualuser

配置就此完成,如果想增加新的用户,只要按照上面的第七步、第十步进行就可以了。

遇到的问题:

  1. 450:读取目录列表失败
    在配置完第一台vsftp后(上面的配置就是)再用同样的过程做第二台,完成后用客户端和浏览器死活无法登录报错:
    450:读取目录列表失败
    只有在命令提示符和Termin下通过ftp 192.168.88.30后ls没有问题
    对比了之前的配置,每一步都没错,难到是PASV问题,于是在vsftpd.conf加上了一句pasv_enable=NO,然后……没然后了,一切都正常了

  2. 中文乱码
    这个是老生常谈的问题,好象也一直没有什么好的解决办法,网上也有提出改i18n,不过客户提出不用改,他们公司主要都是英文档,也我也省事了,不过还是当个问题记录吧

  3. 500 OOPS:cannot change directory:/home/pmfile
    新建用户后登录报错,刚开始以为是selinux的问题,后来一想不对,其他的帐号都没事,肯定刚才己关闭了selinux(getenforce查看selinux,setenforce 0暂时关闭 ),那么就是权限问题了,果然是刚才忘了把权限给虚拟ftp宿主权限了:chown -R ftpuser.ftpuser /home/publicfile

  4. 530错误:Login incorrect.
    这是一个让我觉的搞笑的问题,第二台vsftp服务我用自己的本上的客户端(FileZilla)登录没问题,而客户用他的本登录就不行,用的软件都一样,不同的是我用的是Ubuntu,他用的是win7,但在win7的命令提示符下他却也能登录也能ls,不是权限问题,不是pam问题,这两块都着手试过,结果发现是客户在终端输入的密码错误,之前我还一再问他到底有没有输错密码,他也十分肯定的说没有,结果……

  5. 外网无法登录,550错误,错误: 读取目录列表失败
    这个问题很是挠头,在做完第二台服务器后让客户先从内网登录,一切都很正常,而从外网登录时就会出现“550 Permission denied.”“错误: 连接超时”“错误: 读取目录列表失败”,难到是权限?
    试来试去什么PASV、什么权限更改全做了(这一步是我着实不想做的,要是登录用户权限有问题内网也该无法登录),最后让客户的网管带我去查了一下他们路由器的配置,我才发现他们的内网映射没有开放TCP20端口,开放后就OK了

附录:

FTP命令详解

FTP的命令行格式为:ftp -v -d -i -n -g [主机名],其中

-v显示远程服务器的所有响应信息;

-n限制ftp的自动登录,即不使用;

.n etrc文件;

-d使用调试方式;

-g取消全局文件名。

ftp使用的内部命令如下(中括号表示可选项):

1.![cmd[args]]:在本地机中执行交互shell,exit回到ftp环境,如:!ls*.zip.

2.$ macro-ame[args]:执行宏定义macro-name.

3.account[password]:提供登录远程系统成功后访问系统资源所需的补充口令。

4.append local-file[remote-file]:将本地文件追加到远程系统主机,若未指定远程系统文件名,则使用本地文件名。

5.ascii:使用ascii类型传输方式。

6.bell:每个命令执行完毕后计算机响铃一次。

7.bin:使用二进制文件传输方式。

8.bye:退出ftp会话过程。

9.case:在使用mget时,将远程主机文件名中的大写转为小写字母。

10.cd remote-dir:进入远程主机目录。

11.cdup:进入远程主机目录的父目录。

12.chmod mode file-name:将远程主机文件file-name的存取方式设置为mode,如:chmod 777 a.out。

13.close:中断与远程服务器的ftp会话(与open对应)。

14.cr:使用asscii方式传输文件时,将回车换行转换为回行。

15.delete remote-file:删除远程主机文件。

16.debug[debug-value]:设置调试方式,显示发送至远程主机的每条命令,如:deb up 3,若设为0,表示取消debug。

17.dir[remote-dir][local-file]:显示远程主机目录,并将结果存入本地文件local-file。

18.disconnection:同close。

19.form format:将文件传输方式设置为format,缺省为file方式。

20.get remote-file[local-file]:将远程主机的文件remote-file传至本地硬盘的local-file。

21.glob:设置mdelete,mget,mput的文件名扩展,缺省时不扩展文件名,同命令行的-g参数。

22.hash:每传输1024字节,显示一个hash符号(#)。

23.help[cmd]:显示ftp内部命令cmd的帮助信息,如:help get。

24.idle[seconds]:将远程服务器的休眠计时器设为[seconds]秒。

25.image:设置二进制传输方式(同binary)。

26.lcd[dir]:将本地工作目录切换至dir。

27.ls[remote-dir][local-file]:显示远程目录remote-dir,并存入本地文件local-file。

28.macdef macro-name:定义一个宏,遇到macdef下的空行时,宏定义结束。

29.mdelete[remote-file]:删除远程主机文件。

30.mdir remote-files local-file:与dir类似,但可指定多个远程文件,如:mdir *.o.*.zipoutfile

31.mget remote-files:传输多个远程文件。

32.mkdir dir-name:在远程主机中建一目录。

33.mls remote-file local-file:同nlist,但可指定多个文件名。

34.mode[modename]:将文件传输方式设置为modename,缺省为stream方式。

35.modtime file-name:显示远程主机文件的最后修改时间。

36.mput local-file:将多个文件传输至远程主机。

37.newer file-name:如果远程机中file-name的修改时间比本地硬盘同名文件的时间更近,则重传该文件。

38.nlist[remote-dir][local-file]:显示远程主机目录的文件清单,并存入本地硬盘的local-file。

39.nmap[inpattern outpattern]:设置文件名映射机制,使得文件传输时,文件中的某些字符相互转换,如:nmap $1.$2.$3[$1,$2].[$2,$3],则传输文件a1.a2.a3时,文件名变为a1,a2。该命令特别适用于远程主机为非UNIX机的情况。

40.ntrans[inchars[outchars]]:设置文件名字符的翻译机制,如ntrans 1R,则文件名LLL将变为RRR。

41.open host[port]:建立指定ftp服务器连接,可指定连接端口。

42.passive:进入被动传输方式。

43.prompt:设置多个文件传输时的交互提示。

44.proxy ftp-cmd:在次要控制连接中,执行一条ftp命令,该命令允许连接两个ftp服务器,以在两个服务器间传输文件。第一条ftp命令必须为open,以首先建立两个服务器间的连接。

45.put local-file[remote-file]:将本地文件local-file传送至远程主机。

46.pwd:显示远程主机的当前工作目录。

47.quit:同bye,退出ftp会话。

48.quote arg1,arg2...:将参数逐字发至远程ftp服务器,如:quote syst.

49.recv remote-file[local-file]:同get。

50.reget remote-file[local-file]:类似于get,但若local-file存在,则从上次传输中断处续传。

51.rhelp[cmd-name]:请求获得远程主机的帮助。

52.rstatus[file-name]:若未指定文件名,则显示远程主机的状态,否则显示文件状态。

53.rename[from][to]:更改远程主机文件名。

54.reset:清除回答队列。

55.restart marker:从指定的标志marker处,重新开始get或put,如:restart 130。

56.rmdir dir-name:删除远程主机目录。

57.runique:设置文件名唯一性存储,若文件存在,则在原文件后加后缀..1,.2等。

58.send local-file[remote-file]:同put。

59.sendport:设置PORT命令的使用。

60.site arg1,arg2...:将参数作为SITE命令逐字发送至远程ftp主机。

61.size file-name:显示远程主机文件大小,如:site idle 7200。

62.status:显示当前ftp状态。

63.struct[struct-name]:将文件传输结构设置为struct-name,缺省时使用stream结构。

64.sunique:将远程主机文件名存储设置为唯一(与runique对应)。

65.system:显示远程主机的操作系统类型。

66.tenex:将文件传输类型设置为TENEX机的所需的类型。

67.tick:设置传输时的字节计数器。

68.trace:设置包跟踪。

69.type[type-name]:设置文件传输类型为type-name,缺省为ascii,如:type binary,设置二进制传输方式。

70.umask[newmask]:将远程服务器的缺省umask设置为newmask,如:umask 3。

71.user user-name[password][account]:向远程主机表明自己的身份,需要口令时,必须输入口令,如:user anonymous my@email。

72.verbose:同命令行的-v参数,即设置详尽报告方式,ftp服务器的所有响应都将显示给用户,缺省为on.

73.?[cmd]:同help。

最近有内存使用报警的邮件发出,之后杀掉了内存占用高的进程,使内存恢复正常
但是发现某些程序被杀掉了,有过怀疑是被人手动杀掉的,看日志后发现应该是内存占用过大,系统自动杀掉的

内存耗尽会调用oom 对进程进行评估 并选择一个进程杀死 以释放内存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
dmesg

Jun 26 08:45:47 localhost kernel: [6409835.925696] curl invoked oom-killer: gfp_mask=0x280da, order=0, oom_adj=0, oom_score_adj=0
Jun 26 08:45:48 localhost kernel: [6409835.925705] curl cpuset=/ mems_allowed=0-1
Jun 26 08:45:48 localhost kernel: [6409835.925711] Pid: 3640, comm: curl Not tainted 3.2.0-41-generic #66-Ubuntu
Jun 26 08:45:48 localhost kernel: [6409835.925715] Call Trace:
Jun 26 08:45:48 localhost kernel: [6409835.925729] [<ffffffff8111c281>] dump_header+0x91/0xe0
Jun 26 08:45:48 localhost kernel: [6409835.925734] [<ffffffff8111c605>] oom_kill_process+0x85/0xb0
Jun 26 08:45:48 localhost kernel: [6409835.925740] [<ffffffff8111c9aa>] out_of_memory+0xfa/0x220
...


Jun 26 08:45:48 localhost kernel: [6409836.005515] Out of memory: Kill process 13655 (sh) score 1 or sacrifice child
Jun 26 08:45:48 localhost kernel: [6409836.027998] Killed process 13657 (python) total-vm:1710324kB, anon-rss:2324kB, file-rss:360kB

系统限制用户内存使用量

1
2
3
4
cat /etc/security/limits.conf

ubuntu soft as 1200000
ubuntu hard as 1500000

系统内存情况

1
2
3
4
5
6
free

total used free shared buffers cached
Mem: 1015664 851624 164040 148 216548 378456
-/+ buffers/cache: 256620 759044
Swap: 999996 3344 996652

申请内存的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
test.c

#include<stdio.h>
#include<stdlib.h>
size_t maximum=0;
int main(int argc,char *argv[])
{
void * block;
void * tmpblock;
size_t blocksize[]={1024*1024, 1024, 1};
int i,count;
for(i=0;i<3;i++){
for(count=1;;count++){
block = malloc(maximum+blocksize[i]*count);
if(block){
tmpblock = block;
maximum += blocksize[i]*count;
free(block);
}else{
break;
}
}
}
printf("maximum malloc size = %lf GB\n",maximum*1.0 / 1024.0 / 1024.0 / 1024.0);
printf("the address is %x\n",tmpblock);
printf("the address end is %x\n", tmpblock + maximum);
//while(1);
}

编译运行后的结果

1
2
3
4
5
6
gcc -o malloc  test.c
./malloc

maximum malloc size = 1.101562 GB
the address is 618c2010
the address end is a80c2010

去掉交换内存后的情况

1
2
3
4
5
6
free

total used free shared buffers cached
Mem: 1015664 856708 158956 384 216580 379532
-/+ buffers/cache: 260596 755068
Swap: 0 0 0

系统内存使用情况

1
2
3
4
5
./malloc

maximum malloc size = 0.784881 GB
the address is 3dc48010
the address end is 6fffff56

这个限制是包括交换内存在内的,系统会保留一定的内存供内核使用,用户空间能够申请的内存使用量达不到最大值

附注:
限制用户的内存和cpu使用还可以通过cgroup的方式进行, 这一点还不熟,希望以后可以有机会用到

Kafka初识

Kafka使用背景

在我们大量使用分布式数据库、分布式计算集群的时候,是否会遇到这样的一些问题:

  1. 我们想分析下用户行为(pageviews),以便我们设计出更好的广告位
  2. 我想对用户的搜索关键词进行统计,分析出当前的流行趋势
  3. 有些数据,存储数据库浪费,直接存储硬盘效率又低

这些场景都有一个共同点:
数据是由上游模块产生,上游模块,使用上游模块的数据计算、统计、分析,这个时候就可以使用消息系统,尤其是分布式消息系统!

Kafka的定义

What is Kafka:它是一个分布式消息系统,由linkedin使用scala编写,用作LinkedIn的活动流(Activity Stream)和运营数据处理管道(Pipeline)的基础。具有高水平扩展和高吞吐量。

Kafka和其他主流分布式消息系统的对比

定义解释:

  1. Java 和 scala都是运行在JVM上的语言。
  2. erlang和最近比较火的和go语言一样是从代码级别就支持高并发的一种语言,所以RabbitMQ天生就有很高的并发性能,但是 有RabbitMQ严格按照AMQP进行实现,受到了很多限制。kafka的设计目标是高吞吐量,所以kafka自己设计了一套高性能但是不通用的协议,他也是仿照AMQP( Advanced Message Queuing Protocol 高级消息队列协议)设计的。
  3. 事物的概念:在数据库中,多个操作一起提交,要么操作全部成功,要么全部失败。举个例子, 在转账的时候付款和收款,就是一个事物的例子,你给一个人转账,你转成功,并且对方正常行收到款项后,这个操作才算成功,有一方失败,那么这个操作就是失败的。
    对应消在息队列中,就是多条消息一起发送,要么全部成功,要么全部失败。3个中只有ActiveMQ支持,这个是因为,RabbitMQ和Kafka为了更高的性能,而放弃了对事物的支持 。
  4. 集群:多台服务器组成的整体叫做集群,这个整体对生产者和消费者来说,是透明的。其实对消费系统组成的集群添加一台服务器减少一台服务器对生产者和消费者都是无感之的。
  5. 负载均衡,对消息系统来说负载均衡是大量的生产者和消费者向消息系统发出请求消息,系统必须均衡这些请求使得每一台服务器的请求达到平衡,而不是大量的请求,落到某一台或几台,使得这几台服务器高负荷或超负荷工作,严重情况下会停止服务或宕机。
  6. 动态扩容是很多公司要求的技术之一,不支持动态扩容就意味着停止服务,这对很多公司来说是不可以接受的。

注:
阿里巴巴的Metal,RocketMQ都有Kafka的影子,他们要么改造了Kafka或者借鉴了Kafka,最后Kafka的动态扩容是通过Zookeeper来实现的。

Zookeeper是一种在分布式系统中被广泛用来作为:分布式状态管理、分布式协调管理、分布式配置管理、和分布式锁服务的集群。kafka增加和减少服务器都会在Zookeeper节点上触发相应的事件kafka系统会捕获这些事件,进行新一轮的负载均衡,客户端也会捕获这些事件来进行新一轮的处理。

Kafka相关概念

AMQP协议

Advanced Message Queuing Protocol (高级消息队列协议)

The Advanced Message Queuing Protocol (AMQP):是一个标准开放的应用层的消息中间件(Message Oriented Middleware)协议。AMQP定义了通过网络发送的字节流的数据格式。因此兼容性非常好,任何实现AMQP协议的程序都可以和与AMQP协议兼容的其他程序交互,可以很容易做到跨语言,跨平台。

上面说的3种比较流行的消息队列协议,要么支持AMQP协议,要么借鉴了AMQP协议的思想进行了开发、实现、设计。

一些基本的概念

  1. 消费者:(Consumer):从消息队列中请求消息的客户端应用程序
  2. 生产者:(Producer) :向broker发布消息的应用程序
  3. AMQP服务端(broker):用来接收生产者发送的消息并将这些消息路由给服务器中的队列,便于fafka将生产者发送的消息,动态的添加到磁盘并给每一条消息一个偏移量,所以对于kafka一个broker就是一个应用程序的实例

kafka支持的客户端语言:Kafka客户端支持当前大部分主流语言,包括:C、C++、Erlang、Java、.net、perl、PHP、Python、Ruby、Go、Javascript
可以使用以上任何一种语言和kafka服务器进行通信(即辨析自己的consumer从kafka集群订阅消息也可以自己写producer程序)

Kafka架构

生产者生产消息、kafka集群、消费者获取消息这样一种架构

kafka集群中的消息,是通过Topic(主题)来进行组织的

一些基本的概念:

  1. 主题(Topic):一个主题类似新闻中的体育、娱乐、教育等分类概念,在实际工程中通常一个业务一个主题。
  2. 分区(Partition):一个Topic中的消息数据按照多个分区组织,分区是kafka消息队列组织的最小单位,一个分区可以看作是一个FIFO( First Input First Output的缩写,先入先出队列)的队列。
    kafka分区是提高kafka性能的关键所在,当你发现你的集群性能不高时,常用手段就是增加Topic的分区,分区里面的消息是按照从新到老的顺序进行组织,消费者从队列头订阅消息,生产者从队列尾添加消息。
  3. 备份(Replication):为了保证分布式可靠性,kafka0.8开始对每个分区的数据进行备份(不同的Broker上),防止其中一个Broker宕机造成分区上的数据不可用。

kafka0.7是一个很大的改变:1、增加了备份2、增加了控制借点概念,增加了集群领导者选举 。

###Zookeeper集群搭建
Kafka集群是把状态保存在Zookeeper中的,首先要搭建Zookeeper集群。

软件环境

(3台服务器-我的测试)
192.168.7.100 server1
192.168.7.101 server2
192.168.7.107 server3

  1. Linux服务器一台、三台、五台、(2*n+1),Zookeeper集群的工作是超过半数才能对外提供服务,3台中超过两台超过半数,允许1台挂掉 ,是否可以用偶数,其实没必要。
    如果有四台那么挂掉一台还剩下三台服务器,如果在挂掉一个就不行了,这里记住是超过半数。
  2. Java jdk1.7 zookeeper是用java写的所以他的需要JAVA环境,java是运行在java虚拟机上的
  3. Zookeeper的稳定版本Zookeeper 3.4.6版本

配置&安装Zookeeper

下面的操作是:3台服务器统一操作

  1. 安装Java
    yum list java*
    yum -y install java-1.7.0-openjdk*
  2. 下载Zookeeper

首先要注意在生产环境中目录结构要定义好,防止在项目过多的时候找不到所需的项目

1
2
3
4
5
#我的目录统一放在/opt下面
#首先创建Zookeeper项目目录
mkdir zookeeper #项目目录
mkdir zkdata #存放快照日志
mkdir zkdatalog#存放事物日志

下载Zookeeper

1
2
3
4
5
6
7
#下载软件
cd /opt/zookeeper/

wget http://mirrors.cnnic.cn/apache/zookeeper/zookeeper-3.4.6/zookeeper-3.4.6.tar.gz

#解压软件
tar -zxvf zookeeper-3.4.6.tar.gz

修改配置文件

进入到解压好的目录里面的conf目录中,查看

1
2
3
4
5
6
7
#进入conf目录
/opt/zookeeper/zookeeper-3.4.6/conf
#查看
[[email protected]]$ ll
-rw-rw-r--. 1 1000 1000 535 Feb 20 2014 configuration.xsl
-rw-rw-r--. 1 1000 1000 2161 Feb 20 2014 log4j.properties
-rw-rw-r--. 1 1000 1000 922 Feb 20 2014 zoo_sample.cfg

#zoo_sample.cfg 这个文件是官方给我们的zookeeper的样板文件,给他复制一份命名为zoo.cfg,zoo.cfg是官方指定的文件命名规则。

3台服务器的配置文件

1
2
3
4
5
6
7
8
9
10
11
tickTime=2000
initLimit=10
syncLimit=5
dataDir=/opt/zookeeper/zkdata
dataLogDir=/opt/zookeeper/zkdatalog
clientPort=12181
server.1=192.168.7.100:12888:13888
server.2=192.168.7.101:12888:13888
server.3=192.168.7.107:12888:13888
#server.1 这个1是服务器的标识也可以是其他的数字, 表示这个是第几号服务器,用来标识服务器,这个标识要写到快照目录下面myid文件里
#192.168.7.107为集群里的IP地址,第一个端口是master和slave之间的通信端口,默认是2888,第二个端口是leader选举的端口,集群刚启动的时候选举或者leader挂掉之后进行新的选举的端口默认是3888

配置文件解释:

1
2
3
4
5
6
7
8
9
10
11
12
#tickTime:
这个时间是作为 Zookeeper 服务器之间或客户端与服务器之间维持心跳的时间间隔,也就是每个 tickTime 时间就会发送一个心跳。
#initLimit:
这个配置项是用来配置 Zookeeper 接受客户端(这里所说的客户端不是用户连接 Zookeeper 服务器的客户端,而是 Zookeeper 服务器集群中连接到 Leader 的 Follower 服务器)初始化连接时最长能忍受多少个心跳时间间隔数。当已经超过 5个心跳的时间(也就是 tickTime)长度后 Zookeeper 服务器还没有收到客户端的返回信息,那么表明这个客户端连接失败。总的时间长度就是 5*2000=10 秒
#syncLimit:
这个配置项标识 Leader 与Follower 之间发送消息,请求和应答时间长度,最长不能超过多少个 tickTime 的时间长度,总的时间长度就是5*2000=10秒
#dataDir:
快照日志的存储路径
#dataLogDir:
事物日志的存储路径,如果不配置这个那么事物日志会默认存储到dataDir制定的目录,这样会严重影响zk的性能,当zk吞吐量较大的时候,产生的事物日志、快照日志太多
#clientPort:
这个端口就是客户端连接 Zookeeper 服务器的端口,Zookeeper 会监听这个端口,接受客户端的访问请求。修改他的端口改大点

创建myid文件

1
2
3
4
5
6
#server1
echo "1" > /opt/zookeeper/zkdata/myid
#server2
echo "2" > /opt/zookeeper/zkdata/myid
#server3
echo "3" > /opt/zookeeper/zkdata/myid

重要配置说明

  1. myid文件和server.myid 在快照目录下存放的标识本台服务器的文件,他是整个zk集群用来发现彼此的一个重要标识。
  2. zoo.cfg 文件是zookeeper配置文件 在conf目录里。
  3. log4j.properties文件是zk的日志输出文件 在conf目录里用java写的程序基本上有个共同点日志都用log4j,来进行管理。
  4. zkEnv.sh和zkServer.sh文件

    zkServer.sh 主的管理程序文件
    zkEnv.sh 是主要配置,zookeeper集群启动时配置环境变量的文件

  5. 还有一个需要注意

    ZooKeeper server will not remove old snapshots and log files when using the default configuration (see > > > autopurge below), this is the responsibility of the operator
    zookeeper不会主动的清除旧的快照和日志文件,这个是操作者的责任。

但是可以通过命令去定期的清理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/bin/bash 

#snapshot file dir
dataDir=/opt/zookeeper/zkdata/version-2
#tran log dir
dataLogDir=/opt/zookeeper/zkdatalog/version-2

#Leave 66 files
count=66
count=$[$count+1]
ls -t $dataLogDir/log.* | tail -n +$count | xargs rm -f
ls -t $dataDir/snapshot.* | tail -n +$count | xargs rm -f

#以上这个脚本定义了删除对应两个目录中的文件,保留最新的66个文件,可以将他写到crontab中,设置为每天凌晨2点执行一次就可以了。


#zk log dir del the zookeeper log
#logDir=
#ls -t $logDir/zookeeper.log.* | tail -n +$count | xargs rm -f

其他方法:

第二种:使用ZK的工具类PurgeTxnLog,它的实现了一种简单的历史文件清理策略,可以在这里看一下他的使用方法 http://zookeeper.apache.org/doc/r3.4.6/zookeeperAdmin.html

第三种:对于上面这个执行,ZK自己已经写好了脚本,在bin/zkCleanup.sh中,所以直接使用这个脚本也是可以执行清理工作的。

第四种:从3.4.0开始,zookeeper提供了自动清理snapshot和事务日志的功能,通过配置 autopurge.snapRetainCount 和 autopurge.purgeInterval 这两个参数能够实现定时清理了。这两个参数都是在zoo.cfg中配置的:

autopurge.purgeInterval 这个参数指定了清理频率,单位是小时,需要填写一个1或更大的整数,默认是0,表示不开启自己清理功能。
autopurge.snapRetainCount 这个参数和上面的参数搭配使用,这个参数指定了需要保留的文件数目。默认是保留3个。

推荐使用第一种方法,对于运维人员来说,将日志清理工作独立出来,便于统一管理也更可控。毕竟zk自带的一些工具并不怎么给力。

启动服务并查看

  1. 启动服务

    1
    2
    3
    4
    #进入到Zookeeper的bin目录下
    cd /opt/zookeeper/zookeeper-3.4.6/bin
    #启动服务(3台都需要操作)
    ./zkServer.sh start
  2. 检查服务状态

    1
    2
    #检查服务器状态
    ./zkServer.sh status

通过status就能看到状态:

1
2
3
4
./zkServer.sh status
JMX enabled by default
Using config: /opt/zookeeper/zookeeper-3.4.6/bin/../conf/zoo.cfg #配置文件
Mode: follower #他是否为领导

zk集群一般只有一个leader,多个follower,主一般是相应客户端的读写请求,而从主同步数据,当主挂掉之后就会从follower里投票选举一个leader出来。

可以用“jps”查看zk的进程,这个是zk的整个工程的main

1
2
3
#执行命令jps
20348 Jps
4233 QuorumPeerMain

Kafka集群搭建

软件环境

  1. linux一台或多台,大于等于2
  2. 已经搭建好的zookeeper集群
  3. 软件版本kafka_2.11-0.9.0.1.tgz

创建目录并下载安装软件

1
2
3
4
5
6
7
8
9
10
11
#创建目录
cd /opt/
mkdir kafka #创建项目目录
cd kafka
mkdir kafkalogs #创建kafka消息目录,主要存放kafka消息

#下载软件
wget http://apache.opencas.org/kafka/0.9.0.1/kafka_2.11-0.9.0.1.tgz

#解压软件
tar -zxvf kafka_2.11-0.9.0.1.tgz

修改配置文件

进入到config目录

1
cd /opt/kafka/kafka_2.11-0.9.0.1/config/

主要关注:server.properties 这个文件即可,我们可以发现在目录下:

有很多文件,这里可以发现有Zookeeper文件,我们可以根据Kafka内带的zk集群来启动,但是建议使用独立的zk集群

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-rw-r--r--. 1 root root 5699 Feb 22 09:41 192.168.7.101
-rw-r--r--. 1 root root 906 Feb 12 08:37 connect-console-sink.properties
-rw-r--r--. 1 root root 909 Feb 12 08:37 connect-console-source.properties
-rw-r--r--. 1 root root 2110 Feb 12 08:37 connect-distributed.properties
-rw-r--r--. 1 root root 922 Feb 12 08:38 connect-file-sink.properties
-rw-r--r--. 1 root root 920 Feb 12 08:38 connect-file-source.properties
-rw-r--r--. 1 root root 1074 Feb 12 08:37 connect-log4j.properties
-rw-r--r--. 1 root root 2055 Feb 12 08:37 connect-standalone.properties
-rw-r--r--. 1 root root 1199 Feb 12 08:37 consumer.properties
-rw-r--r--. 1 root root 4369 Feb 12 08:37 log4j.properties
-rw-r--r--. 1 root root 2228 Feb 12 08:38 producer.properties
-rw-r--r--. 1 root root 5699 Feb 15 18:10 server.properties
-rw-r--r--. 1 root root 3325 Feb 12 08:37 test-log4j.properties
-rw-r--r--. 1 root root 1032 Feb 12 08:37 tools-log4j.properties
-rw-r--r--. 1 root root 1023 Feb 12 08:37 zookeeper.properties

修改配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
broker.id=0  #当前机器在集群中的唯一标识,和zookeeper的myid性质一样
port=19092 #当前kafka对外提供服务的端口默认是9092
host.name=192.168.7.100 #这个参数默认是关闭的,在0.8.1有个bug,DNS解析问题,失败率的问题。
num.network.threads=3 #这个是borker进行网络处理的线程数
num.io.threads=8 #这个是borker进行I/O处理的线程数
log.dirs=/opt/kafka/kafkalogs/ #消息存放的目录,这个目录可以配置为“,”逗号分割的表达式,上面的num.io.threads要大于这个目录的个数这个目录,如果配置多个目录,新创建的topic他把消息持久化的地方是,当前以逗号分割的目录中,那个分区数最少就放那一个
socket.send.buffer.bytes=102400 #发送缓冲区buffer大小,数据不是一下子就发送的,先回存储到缓冲区了到达一定的大小后在发送,能提高性能
socket.receive.buffer.bytes=102400 #kafka接收缓冲区大小,当数据到达一定大小后在序列化到磁盘
socket.request.max.bytes=104857600 #这个参数是向kafka请求消息或者向kafka发送消息的请请求的最大数,这个值不能超过java的堆栈大小
num.partitions=1 #默认的分区数,一个topic默认1个分区数
log.retention.hours=168 #默认消息的最大持久化时间,168小时,7天
message.max.byte=5242880 #消息保存的最大值5M
default.replication.factor=2 #kafka保存消息的副本数,如果一个副本失效了,另一个还可以继续提供服务
replica.fetch.max.bytes=5242880 #取消息的最大直接数
log.segment.bytes=1073741824 #这个参数是:因为kafka的消息是以追加的形式落地到文件,当超过这个值的时候,kafka会新起一个文件
log.retention.check.interval.ms=300000 #每隔300000毫秒去检查上面配置的log失效时间(log.retention.hours=168 ),到目录查看是否有过期的消息如果有,删除
log.cleaner.enable=false #是否启用log压缩,一般不用启用,启用的话可以提高性能
zookeeper.connect=192.168.7.100:12181,192.168.7.101:12181,192.168.7.107:1218 #设置zookeeper的连接端口

上面是参数的解释,实际的修改项为:

1
2
3
4
5
6
7
8
9
10
11
12
#broker.id=0  每台服务器的broker.id都不能相同

#hostname
host.name=192.168.7.100

#在log.retention.hours=168 下面新增下面三项
message.max.byte=5242880
default.replication.factor=2
replica.fetch.max.bytes=5242880

#设置zookeeper的连接端口
zookeeper.connect=192.168.7.100:12181,192.168.7.101:12181,192.168.7.107:12181

启动Kafka集群并测试

  1. 启动服务
    1
    2
    3
    4
    #从后台启动Kafka集群(3台都需要启动)
    cd
    /opt/kafka/kafka_2.11-0.9.0.1//bin #进入到kafka的bin目录
    ./kafka-server-start.sh -daemon ../config/server.properties

检查服务是否启动

1
2
3
4
#执行命令jps
20348 Jps
4233 QuorumPeerMain
18991 Kafka

创建Topic来验证是否创建成功

更多请看官方文档:http://kafka.apache.org/documentation.html

1
2
3
4
5
6
7
8
9
10
11
12
13
#创建Topic
./kafka-topics.sh --create --zookeeper 192.168.7.100:12181 --replication-factor 2 --partitions 1 --topic shuaige
#解释
--replication-factor 2 #复制两份
--partitions 1 #创建1个分区
--topic #主题为shuaige

'''在一台服务器上创建一个发布者'''
#创建一个broker,发布者
./kafka-console-producer.sh --broker-list 192.168.7.100:19092 --topic shuaige

'''在一台服务器上创建一个订阅者'''
./kafka-console-consumer.sh --zookeeper localhost:12181 --topic shuaige --from-beginning

测试(在发布者那里发布消息看看订阅者那里是否能正常收到~):

其他命令

大部分命令可以去官方文档查看

查看topic

1
2
./kafka-topics.sh --list --zookeeper localhost:12181
#就会显示我们创建的所有topic

查看topic状态

1
2
3
4
5
6
7
/kafka-topics.sh --describe --zookeeper localhost:12181 --topic shuaige
#下面是显示信息
Topic:ssports PartitionCount:1 ReplicationFactor:2 Configs:
Topic: shuaige Partition: 0 Leader: 1 Replicas: 0,1 Isr: 1
#分区为为1 复制因子为2 他的 shuaige的分区为0
#Replicas: 0,1 复制的为0,1
#

OK kafka集群搭建完毕

其他说明标注

日志说明

默认kafka的日志是保存在/opt/kafka/kafka_2.10-0.9.0.0/logs目录下的,这里说几个需要注意的日志

1
2
3
4
server.log #kafka的运行日志
state-change.log #kafka他是用zookeeper来保存状态,所以他可能会进行切换,切换的日志就保存在这里

controller.log #kafka选择一个节点作为“controller”,当发现有节点down掉的时候它负责在游泳分区的所有节点中选择新的leader,这使得Kafka可以批量的高效的管理所有分区节点的主从关系。如果controller down掉了,活着的节点中的一个会备切换为新的controller.

上面的大家你完成之后可以登录zk来查看zk的目录情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#使用客户端进入zk
./zkCli.sh -server 127.0.0.1:12181 #默认是不用加’-server‘参数的因为我们修改了他的端口

#查看目录情况 执行“ls /”
[zk: 127.0.0.1:12181(CONNECTED) 0] ls /

#显示结果:[consumers, config, controller, isr_change_notification, admin, brokers, zookeeper, controller_epoch]

上面的显示结果中:只有zookeeper是,zookeeper原生的,其他都是Kafka创建的

#标注一个重要的
[zk: 127.0.0.1:12181(CONNECTED) 1] get /brokers/ids/0
{"jmx_port":-1,"timestamp":"1456125963355","endpoints":["PLAINTEXT://192.168.7.100:19092"],"host":"192.168.7.100","version":2,"port":19092}
cZxid = 0x1000001c1
ctime = Mon Feb 22 15:26:03 CST 2016
mZxid = 0x1000001c1
mtime = Mon Feb 22 15:26:03 CST 2016
pZxid = 0x1000001c1
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x152e40aead20016
dataLength = 139
numChildren = 0
[zk: 127.0.0.1:12181(CONNECTED) 2]

#还有一个是查看partion
[zk: 127.0.0.1:12181(CONNECTED) 7] get /brokers/topics/shuaige/partitions/0
null
cZxid = 0x100000029
ctime = Mon Feb 22 10:05:11 CST 2016
mZxid = 0x100000029
mtime = Mon Feb 22 10:05:11 CST 2016
pZxid = 0x10000002a
cversion = 1
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 0
numChildren = 1
[zk: 127.0.0.1:12181(CONNECTED) 8]