加入人人都是产品经理【起点学院】产品经理实战训练营,BAT产品总监手把手带你学产品

一看就明白的爬虫入门讲解-基础理论篇

关于爬虫内容的分享,我会分成两篇,六个部分来分享,分别是:

  1. 我们的目的是什么
  2. 内容从何而来
  3. 了解网络请求
  4. 一些常见的限制方式
  5. 尝试解决问题的思路
  6. 效率问题的取舍

本文先聊聊前三个部分。

一、我们的目的是什么

一般来讲对我们而言需要抓取的是某个网站或者某个应用的内容,提取有用的价值,内容一般分为两部分,非结构化的文本,或者结构化的文本。

关于非结构化的数据

1.1 HTML文本(包含javascript代码)

HTML文本基本上是传统爬虫过程中最常见的,也就是大多数时候会遇到的情况,例如抓取一个网页,得到的是HTML,然后需要解析一些常见的元素,提取一些关键的信息。HTML其实理应属于结构化的文本组织,但是又因为一般我们需要的关键信息并非直接可以得到,需要进行对HTML的解析查找,甚至一些字符串操作才能得到,所以还是归类于非结构化的数据处理中。

常见解析方式如下:

CSS选择器

现在的网页样式比较多,所以一般的网页都会有一些CSS的定位,例如class,id等等,或者我们根据常见的节点路径进行定位,例如腾讯首页的财经部分:

这里id就为finance,我们用css选择器,就是"#finance"就得到了财经这一块区域的html,同理,可以根据特定的css选择器可以获取其他的内容。

XPATH

XPATH是一种页面元素的路径选择方法,利用chrome可以快速得到,如:

一看就明白的爬虫入门讲解-基础理论篇

copy XPATH 就能得到——//*[@id="finance"]

正则表达式

正则表达式,用标准正则解析,一般会把HTML当做普通文本,用指定格式匹配当相关文本,适合小片段文本,或者某一串字符,或者HTML包含javascript的代码,无法用CSS选择器或者XPATH。

字符串分隔

同正则表达式,更为偷懒的方法,不建议使用。

1.2 一段文本

例如一篇文章,或者一句话,我们的初衷是提取有效信息,所以如果是滞后处理,可以直接存储,如果是需要实时提取有用信息,常见的处理方式如下:

分词

根据抓取的网站类型,使用不同词库,进行基本的分词,然后变成词频统计,类似于向量的表示,词为方向,词频为长度。

NLP

自然语言处理,进行语义分析,用结果表示,例如正负面等。

关于结构化的数据

结构化的数据是最好处理,一般都是类似JSON格式的字符串,直接解析JSON数据就可以了,提取JSON的关键字段即可

二、内容从何而来

过去我们常需要获取的内容主要来源于网页,一般来讲,我们决定进行抓取的时候,都是网页上可看到的内容,但是随着这几年移动互联网的发展,我们也发现越来越多的内容会来源于移动app,所以爬虫就不止局限于一定要抓取解析网页,还有就是模拟移动app的网络请求进行抓取,所以这一部分我会分两部分进行说明。

1 网页内容

网页内容一般就是指我们最终在网页上看到的内容,但是这个过程其实并不是网页的代码里面直接包含内容这么简单,所以对于很多新人而言,会遇到很多问题,比如:

明明在页面用Chrome或者Firefox进行审查元素时能看到某个HTML标签下包含内容,但是抓取的时候为空。

很多内容一定要在页面上点击某个按钮或者进行某个交互操作才能显示出来。

所以对于很多新人的做法是用某个语言别人模拟浏览器操作的库,其实就是调用本地浏览器或者是包含了一些执行javascript的引擎来进行模拟操作抓取数据,但是这种做法显然对于想要大量抓取数据的情况下是效率非常低下,并且对于技术人员本身而言也相当于在用一个盒子,那么对于这些内容到底是怎么显示在网页上的呢?主要分为以下几种情况:

网页包含内容

这种情况是最容易解决的,一般来讲基本上是静态网页已经写死的内容,或者动态网页,采用模板渲染,浏览器获取到HTML的时候已经是包含所有的关键信息,所以直接在网页上看到的内容都可以通过特定的HTML标签得到

javascript代码加载内容

这种情况是由于虽然网页显示时,内容在HTML标签里面,但是其实是由于执行js代码加到标签里面的,所以这个时候内容在js代码里面的,而js的执行是在浏览器端的操作,所以用程序去请求网页地址的时候,得到的response是网页代码和js的代码,所以自己在浏览器端能看到内容,解析时由于js未执行,肯定找到指定HTML标签下内容肯定为空,这个时候的处理办法,一般来讲主要是要找到包含内容的js代码串,然后通过正则表达式获得相应的内容,而不是解析HTML标签。

Ajax异步请求

这种情况是现在很常见的,尤其是在内容以分页形式显示在网页上,并且页面无刷新,或者是对网页进行某个交互操作后,得到内容。那我们该如何分析这些请求呢?这里我以Chrome的操作为例,进行说明:

一看就明白的爬虫入门讲解-基础理论篇

所以当我们开始刷新页面的时候就要开始跟踪所有的请求,观察数据到底是在哪一步加载进来的。然后当我们找到核心的异步请求的时候,就只用抓取这个异步请求就可以了,如果原始网页没有任何有用信息,也没必要去抓取原始网页了。

2 App内容

因为现在移动应用越来越多,很多有用信息都在App里面,另外解析非结构化文本和结构文本对比而言,结构化文本会简单多了,不同去找内容,去过多分析解析,所有既有网站又有App的话,推荐抓取App,大多数情况下基本上只是一些JSON数据的API了。那么App的数据该如何抓取呢?通用的方法就是抓包,基本的做法就是电脑安装抓包软件,配置好端口,然后记下ip,手机端和电脑在同一个局域网里面,然后在手机的网络连接里面设置好代理,这个时候打开App进行一些操作,如果有网络数据请求,则都会被抓包软件记下,就如上Chrome分析网络请求一样,你可以看到所有的请求情况,可以模拟请求操作。这里Mac上我推荐软件Charles,Windows推荐Fiddler2。

具体如何使用,之后我再做详述,可能会涉及到HTTPS证书的问题。

三、了解网络请求

刚刚一直在宽泛的提到一些我们需要找到请求,进行请求,对于请求只是一笔带过,但请求是很重要的一部分,包括如何绕过限制,如何发送正确地数据,都需要对的请求,这里就要详细的展开说下请求,以及如何模拟请求。

我们常说爬虫其实就是一堆的HTTP请求,找到待爬取的链接,不管是网页链接还是App抓包得到的API链接,然后发送一个请求包,得到一个返回包(也有HTTP长连接,或者Streaming的情况,这里不考虑),所以核心的几个要素就是:

  1. URL
  2. 请求方法(POST, GET)
  3. 请求包headers
  4. 请求包内容
  5. 返回包headers

在用Chrome进行网络请求捕获或者用抓包工具分析请求时,最重要的是弄清楚URL,请求方法,然后headers里面的字段,大多数出问题就出在headers里面,最常限制的几个字段就是User-Agent, Referer,Cookie 另外Base Auth也是在headers里面加了Autheration的字段。

请求内容也就是post时需要发送的数据,一般都是将Key-Value进行urlencode返回包headers大多数会被人忽视,可能只得到内容就可以了,但是其实很多时候,很多人会发现明明url,请求方法还有请求包的内容都对了,为什么没有返回内容,或者发现请求被限制,其实这里大概有两个原因:

  • 一个是返回包的内容是空的,但是在返回包的headers的字段里面有个Location,这个Location字段就是告诉浏览器重定向,所以有时候代码没有自动跟踪,自然就没有内容了;
  • 另外一个就是很多人会头疼的Cookie问题,简单说就是浏览器为什么知道你的请求合法的,例如已登录等等,其实就是可能你之前某个请求的返回包的headers里面有个字段叫Set-Cookie,Cookie存在本地,一旦设置后,除非过期,一般都会自动加在请求字段上,所以Set-Cookie里面的内容就会告诉浏览器存多久,存的是什么内容,在哪个路径下有用,Cookie都是在指定域下,一般都不跨域,域就是你请求的链接host。

所以分析请求时,一定要注意前四个,在模拟时保持一致,同时观察第五个返回时是不是有限制或者有重定向。

【自从去年到现在已经收集了上百种版本的Linux和Unix,至于Unix就不想说了,没有Linux的功底是很难驾驭Unix的,我在这里只把小于360M的Linux以及一些非Linux但是很像Linux的版本也发布一下,我本人喜欢安静,如果你想要这些迷你版本的Linux光盘的话,建议去官网下载就OK了。英语不行的话随时带个字典。有些没有桌面,想知道哪些没有桌面的话请自己网上查资料!下面就是绝大部分小于361M的Linux及其非Linux名单,参考时间为2011年12月份,最近的新版本可能有变!】

Linux没有最小只有更小----361M以下的Linux名单

Vecket:361M
webc:313M
ging:312m
GoblinX:311M
dfly:293M
MirBSD:290M
MidnightBSD:265M
pud:265M
Porteus:261M
caos:241M
crux:237M
grml-medium:224M
OpenBSD 5.0:224M
NetBSD:224M
SLAX:213M
MorphingMorphix:212M
bsdeviant:208M
frenzy:199M
CDlinux:194M
debris:190M
FRANKIE:187M
pmagic:185M
Macpup:168M
formilux:166M
RIPLinuX:157M
jOS:151M
gentoo:128M
clonezilla:127M
vyatta:124M
LPS(Lightweight Portable Security):123M
PuppyLinux:123M
unity:121M
feather:119M
gparted:116M
qrky linux:113M
FreeNAS:103M
browserlinux:96M
milax:95M
austrumi:95M
stresslinux:90M
xpud:65M
ttylinux:63M
turnkey:60
MXebian:52M
dsl(Damn Small Linux):51M
luitlinux:51M
bbc:48M
[奶瓶]beini:45M
AstLinux:40M
slitaz:30M
4MLinux:30M
geexbox:24m
FreeNOS:18M
TinyCore:12M
visopsys:11M
Micro Core Linux :8M
HelenOS:8m
bsd4me:5M
VitasV:4M
minopsos:1.4M
MenuetOS:0.6M
......

想学习Linux桌面系统的话使用Fedora或者Ubuntu或者Debain等等这些著名的发行版本,功能非常齐全,软件包安装非常方便。想学习Linux服务器搭建的话建议使用CentOS,Fedora等等服务器操作系统行业比较著名的版本。
想找个随身的Linux就去上面的小于361M的Linux名单里找找吧,喜欢桌面的也有很小的,比如visopsys才11M也是有桌面的,汇编语言写的系统MenuetOS(0.6M)的也是有桌面的。

慢慢玩吧,Linux世界总有你想要的。

转:http://blog.sina.com.cn/s/blog_99be711101011tu8.html

导读:在百度site或通过关键词搜索网站时显示的Description不是自己写的而是显示随机抓取的内容,百度不抓取Description而显示随机内容原因何在?

百度不抓取description

2012百度算法更新时间非常频繁,3月、5月、6月、8月、9月、10月几乎从3月份开始便一直在不停的更新,不停的K站。在更新中对网站的要求也越来越严、越来越全面,不少站长应该已经发现了一个小问题,在site或通过关键词搜索网站时百度显示的并非自己Description标签中所写的,而是随机生成的内容。

很多人讲,出现这个可能是代码标签问题、双Meta问题等等,但测试过就会发现还是解决不了问题。所以,问题很可能出在百度对算法的更新上。

文本时代的算法中,keywords和description扮演着重要的作用,高频率、高密度出现会更容易获得好的排名,于是曾经关键词叠加是很多seoer都在做的事,甚至于现在,很多seo新手仍然喜欢在description里罗列关键词。然而,搜索引擎算法已经从文本时代到链接时代又到了用户时代了,keywords及description所能起到的作用已经很小了,甚至已经在有意在惩罚这些seo行为了。

Description的作用在于概括的向用户介绍网页内容,而一般的叠加式方法其可读性很差,无法用来概括网页内容。在这种情况下,搜索引擎出一种专门针对Description可读性判断的算法不无可能。通过算法,对于被判定可读性较差的Description不予采用而随机生成。

另外,笨鸟分析过众多网站,发现关键词叠加是最容易导致搜索引擎不采用Description标签内容而随机抓取生成的因素。从这点上我们可以猜想,百度Description不抓取而显示随机内容的原因在于Description的可读性过差。

Keywords的作用已经几乎没有了是大多seoer的共识,而Description对于关键词排名的作用大多数人却并不否定。想让Description对关键词排名起到作用,首先需要让百度认可并正常显示。

搜索点击率是排名的一大因素,在搜索结果中出现相关关键词飘红有助于吸引用户点击,而如果用户看过去时发现这是一段根本无法读通的句子,相信点击率也会随之下降吧。对于百度显示的68个纯汉字,作弊空间太小了,叠加关键词明显已经out了,做好可读性应该是撰写Description的第一要素。

几条关于如何写好Description的规范:

1、避免关键词堆砌,以可读性为第一要义

同一关键词叠加最好不要超过三次,可遵循“四不过三,三不过四,二不过五”定律;

2、开门见山,开头提及主关键词

在最开始的10个字内最好提及主关键词,越往前的字获得的权重相对越高;

3、控制字数,避免过长

在百度搜索结果中,仅能显示68个左右的汉字,尽量将需要展示的内容控制在这个范围内;

4、合理安排词汇排序

关键词的顺序决定了其获得的权重也是不一样的,建议可以根据搜索相关关键词查看排名前20的所选择的词汇及其组合顺序;

5、吸引力

在简短的文字中要体现吸引力,如可以使用权威性词中国首家、最专业等;

结语:百度不抓取Description显示随机内容,这是百度对网站进行惩罚的一种信号,同时也不利于点击率,建议可进行修改优化,以用户可读性为第一要义。

http://www.centoscn.com/CentosServer/test/2014/1120/4153.html

OpenVPN是一个用于创建虚拟专用网络(Virtual Private Network)加密通道的免费开源软件。使用OpenVPN可以方便地在家庭、办公场所、住宿酒店等不同网络访问场所之间搭建类似于局域网的专用网络通道。

使用OpenVPN配合特定的代理服务器,可用于访问Youtube、FaceBook、Twitter等受限网站,也可用于突破公司的网络限制。

一、服务器端安装及配置

服务器环境:干净的CentOS6.3 64位系统

内网IP:10.143.80.116

外网IP:203.195.xxx.xxx

OpenVPN版本:OpenVPN 2.3.2 x86_64-redhat-linux-gnu

    1、安装前准备

# 关闭selinux
setenforce 0
sed -i '/^SELINUX=/c\SELINUX=disabled' /etc/selinux/config
# 安装openssl和lzo,lzo用于压缩通讯数据加快传输速度
yum -y install openssl openssl-devel
yum -y install lzo
# 安装epel源
rpm -ivh http://mirrors.sohu.com/fedora-epel/6/x86_64/epel-release-6-8.noarch.rpm
sed -i 's/^mirrorlist=https/mirrorlist=http/' /etc/yum.repos.d/epel.repo

    2、安装及配置OpenVPN和easy-rsa

# 安装openvpn和easy-rsa
yum -y install openvpn easy-rsa
# 修改vars文件
cd /usr/share/easy-rsa/2.0/
vim vars
# 修改注册信息,比如公司地址、公司名称、部门名称等。
export KEY_COUNTRY="CN"
export KEY_PROVINCE="Shandong"
export KEY_CITY="Qingdao"
export KEY_ORG="MyOrganization"
export KEY_EMAIL="me@myhost.mydomain"
export KEY_OU="MyOrganizationalUnit"
# 初始化环境变量
source vars
# 清除keys目录下所有与证书相关的文件
# 下面步骤生成的证书和密钥都在/usr/share/easy-rsa/2.0/keys目录里
./clean-all
# 生成根证书ca.crt和根密钥ca.key(一路按回车即可)
./build-ca
# 为服务端生成证书和密钥(一路按回车,直到提示需要输入y/n时,输入y再按回车,一共两次)
./build-key-server server
# 每一个登陆的VPN客户端需要有一个证书,每个证书在同一时刻只能供一个客户端连接,下面建立2份
# 为客户端生成证书和密钥(一路按回车,直到提示需要输入y/n时,输入y再按回车,一共两次)
./build-key client1
./build-key client2
# 创建迪菲·赫尔曼密钥,会生成dh2048.pem文件(生成过程比较慢,在此期间不要去中断它)
./build-dh
# 生成ta.key文件(防DDos攻击、UDP淹没等恶意攻击)
openvpn --genkey --secret keys/ta.key

查看keys目录下生成的文件:

wKioL1RhllmyOZW9AAKmWJ5x4tg383.jpg

    3、创建服务器端配置文件

# 在openvpn的配置目录下新建一个keys目录
mkdir /etc/openvpn/keys
# 将需要用到的openvpn证书和密钥复制一份到刚创建好的keys目录中
cp /usr/share/easy-rsa/2.0/keys/{ca.crt,server.{crt,key},dh2048.pem,ta.key/etc/openvpn/keys/
# 复制一份服务器端配置文件模板server.conf到/etc/openvpn/
cp /usr/share/doc/openvpn-2.3.2/sample/sample-config-files/server.conf /etc/openvpn/
# 查看server.conf里的配置参数
grep '^[^#;]' /etc/openvpn/server.conf
# 编辑server.conf
vim /etc/openvpn/server.conf
port 1194
# 改成tcp,默认使用udp,如果使用HTTP Proxy,必须使用tcp协议
proto tcp
dev tun
# 路径前面加keys,全路径为/etc/openvpn/keys/ca.crt
ca keys/ca.crt
cert keys/server.crt
key keys/server.key  # This file should be kept secret
dh keys/dh2048.pem
# 默认虚拟局域网网段,不要和实际的局域网冲突即可
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
# 10.0.0.0/8是我这台VPN服务器所在的内网的网段,读者应该根据自身实际情况进行修改
push "route 10.0.0.0 255.0.0.0"
# 可以让客户端之间相互访问直接通过openvpn程序转发,根据需要设置
client-to-client
# 如果客户端都使用相同的证书和密钥连接VPN,一定要打开这个选项,否则每个证书只允许一个人连接VPN
duplicate-cn
keepalive 10 120
tls-auth keys/ta.key 0 # This file is secret
comp-lzo
persist-key
persist-tun
# OpenVPN的状态日志,默认为/etc/openvpn/openvpn-status.log
status openvpn-status.log
# OpenVPN的运行日志,默认为/etc/openvpn/openvpn.log 
log-append openvpn.log
# 改成verb 5可以多查看一些调试信息
verb 5

4、配置内核和防火墙,启动服务

# 开启路由转发功能
sed -i '/net.ipv4.ip_forward/s/0/1/' /etc/sysctl.conf
sysctl -p
# 配置防火墙,别忘记保存
iptables -I INPUT -p tcp --dport 1194 -m comment --comment "openvpn" -j ACCEPT
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j MASQUERADE
service iptables save
# 启动openvpn并设置为开机启动
service openvpn start
chkconfig openvpn on

    5、创建客户端配置文件

# 复制一份client.conf模板命名为client.ovpn
cp /usr/share/doc/openvpn-2.3.2/sample/sample-config-files/client.conf client.ovpn
# 编辑client.ovpn
vim client.ovpn
client
dev tun
# 改为tcp
proto tcp
# OpenVPN服务器的外网IP和端口
remote 203.195.xxx.xxx 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
# client1的证书
cert client1.crt
# client1的密钥
key client1.key
ns-cert-type server
# 去掉前面的注释
tls-auth ta.key 1
comp-lzo
verb 3

二、Windows客户端安装及配置

客户端系统:Windows7 64位

内网IP:172.16.4.4

OpenVPN版本:OpenVPN 2.3.3 Windows 64位

    1、下载安装OpenVPN

OpenVPN 2.3.3 Windows 32位 安装文件:

http://swupdate.openvpn.org/community/releases/openvpn-install-2.3.3-I002-i686.exe

OpenVPN 2.3.3 Windows 64位 安装文件:

http://swupdate.openvpn.org/community/releases/openvpn-install-2.3.3-I002-x86_64.exe

    2、配置client

将OpenVPN服务器上的client.ovpn、ca.crt、client1.crt、client1.key、ta.key上传到Windows客户端安装目录下的config文件夹(C:\Program Files\OpenVPN\config)

    3、启动OpenVPN GUI

在电脑右下角的openvpn图标上右击,选择“Connect”。正常情况下应该能够连接成功,分配正常的IP。

wKiom1RhjGbijB7xAABMoQo3Tnc522.jpg

wKioL1RhjgyxiZ17AAIRIRCqqws094.jpg    

    4、测试

wKiom1RhjfPD8_AYAAGxUvt_PCA503.jpg

ping通服务器的内网IP,说明已经接入到服务器的内部网络。

到OpenVPN服务器上查看客户端的连接情况,查看状态文件/etc/openvpn/openvpn-status.log:

 

#!/usr/bin/expect
set ssh_user "ubnt"
set password "ubnt"
spawn ssh -l $ssh_user 192.168.1.20
expect_before "no)?" {
send "yes\r" }
sleep 0.5
expect "Enter passphrase for key*"
send "$password\r"
expect "*#"
send "reboot\r"
expect "*#"
send "echo\r"
exit

安装雪豹系统全攻略

http://blog.csdn.net/momo2010programer/article/details/6098874

转向Intel阵营为在PC安装Mac OS提供可能


 

 

泡泡网主板频道5月13日 从目前桌面级操作系统的格局来看,主要分为Windows、Mac OS以及Linux三大阵营。其中Windows阵营最为强大,占据全球整个桌面级操作系统90%以上的市场份额,苹果公司自有的操作系统Mac次之,拥有超过5%的市场份额,剩下的则基本上是Linux阵营的天下。

在这三种操作系统当中,Windows和Linux都是可以直接安装在个人电脑上的,它们本身在硬件方面并没有严格的限制,一般来说基于x86架构的PC都可以安装。而苹果公司的Mac OS系列操作系统则不同,它所面向的是苹果公司自己的电脑产品,并不在除苹果之外的硬件上提供支持。

都来啃苹果吧!PC安装雪豹系统全攻略

    对苹果电脑稍微有所了解的朋友应该知道,自1994年以来,苹果一直在使用IBM的PowerPC处理器,直到2006年苹果公司才正式决定放弃与IBM的合作,采用性价比更高的Intel处理器,也就是说转向了x86架构。采用Intel处理器对于苹果的转变来说是非常重要的一件事情,它不仅仅标志着苹果不会再受到IBM在芯片价格方面的制约,也为如今能在普通PC或笔记本电脑上安装Mac OS系统提供了可能。为什么这么说呢?

 

第2层隧道协议 (L2TP),是 VPN 隧道协议的一种,是 PPTP 的后续版本。L2TP 支持两端点间多隧道,但通常要由 IPSec 来提供加密和验证功能,可建立变动的客户端到固定服务器的连接。

一、安装 IPSec

IPSec 用于对 IP 数据包进行加密和验证,通常使用 Openswan 来实现 IPSec。

1.1、安装编译工具

1
apt-get -y install build-essential

1.2、安装 OpenSwan 依赖包

1
apt-get -y install libgmp3-dev flex bison

1.3、编译安装 OpenSwan

1
2
3
4
wget -c http://www.openswan.org/download/openswan-2.6.33.tar.gz
tar -zxf openswan-2.6.33.tar.gz
cd openswan-2.6.33
make programs install

1.4、编辑 IPSec 配置文件

注意将"192.168.1.102"换成服务器公网IP。

1
cp /etc/ipsec.conf /etc/ipsec.conf.old
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
cat >/etc/ipsec.conf<<EOF
version 2.0

config setup
    nat_traversal=yes
    virtual_private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12
    oe=off
    protostack=netkey

conn L2TP-PSK-NAT
    rightsubnet=vhost:%priv
    also=L2TP-PSK-noNAT

conn L2TP-PSK-noNAT
    authby=secret
    pfs=no
    auto=add
    keyingtries=3
    rekey=no
    ikelifetime=8h
    keylife=1h
    type=transport
    left=192.168.1.102
    leftprotoport=17/1701
    right=%any
    rightprotoport=17/%any
EOF

1.5、设置 PSK 预共享密钥

注意将"192.168.1.102"换成服务器公网IP。将"123456"换成你自己的PSK。

1
2
3
cat >/etc/ipsec.secrets<<EOF
192.168.1.102 %any: PSK "123456"
EOF

1.6、调整网络策略

for 循环语句,请一行一行地输入,输完后按回车。

1
2
3
4
5
for each in /proc/sys/net/ipv4/conf/*
do
echo 0 > $each/accept_redirects
echo 0 > $each/send_redirects
done

1.7、重启IPSec 服务

1
2
/etc/init.d/ipsec restart
/usr/local/sbin/ipsec verify

可尝试使用 L2TP/IPSec 客户端连接一次,以测试 IPSec 部分配置是否成功。

1
cat /var/log/auth.log | grep pluto

如出现"IPsec SA established transport mode"则成功了。

二、安装 L2TP

使用 xl2tpd 来实现 L2TP,另外要注意的是 xl2tpd 需要从 rp-l2tp 中提取 l2tp-control。

2.1、提取 l2tp-control

1
2
3
4
5
6
7
8
wget http://nchc.dl.sourceforge.net/project/rp-l2tp/rp-l2tp/0.4/rp-l2tp-0.4.tar.gz
tar zxvf rp-l2tp-0.4.tar.gz
cd rp-l2tp-0.4
./configure
make
cp handlers/l2tp-control /usr/local/sbin/
mkdir /var/run/xl2tpd/
ln -s /usr/local/sbin/l2tp-control /var/run/xl2tpd/l2tp-control

2.2、编译安装 xl2tpd

1
apt-get -y install libpcap-dev #安装依赖包
1
2
3
4
5
wget -c http://www.xelerance.com/wp-content/uploads/software/xl2tpd/xl2tpd-1.2.8.tar.gz
tar -zxf xl2tpd-1.2.8.tar.gz
cd xl2tpd-1.2.8
make install
mkdir /etc/xl2tpd

2.3、编辑 xl2tpd 配置文件

ip range 是连接上来的客户端所获得的服务器端内网的 IPv4 地址段。
local ip 是 pppX 所占用的那个 IP 地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cat >/etc/xl2tpd/xl2tpd.conf<<EOF
[global]
ipsec saref = yes

[lns default]
local ip = 10.10.11.1
ip range = 10.10.11.2-10.10.11.245
refuse chap = yes
refuse pap = yes
require authentication = yes
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
EOF

三、PPP 的安装配置

3.1、安装 ppp 包

1
apt-get -y install ppp

3.2、配置 options.xl2tpd

主要是改MS-DNS,其他默认。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cat >/etc/ppp/options.xl2tpd<<EOF
require-mschap-v2
ms-dns 8.8.8.8
ms-dns 8.8.4.4
asyncmap 0
auth
crtscts
lock
hide-password
modem
debug
name l2tpd
proxyarp
lcp-echo-interval 30
lcp-echo-failure 4
EOF

四、添加 VPN 用户

chap-secrets 文件为4段,分别是:用户名、服务器名称、密码、分配给客户端的IP。
服务器名可以是l2tpd 或 pptpd,*号代表全部。
密码以明文填写,不需进行加密。
最后的*号代表从remoteip指定的IP段随机分配

1
2
3
cat >>/etc/ppp/chap-secrets<<EOF
user * 123456 *
EOF

五、配置数据包转发

否则连接VPN后,只能访问服务器资源,而不能访问这台服务器以外的资源。

1
2
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g' /etc/sysctl.conf
sysctl -p

开启iptables转发

1
iptables -t nat -A POSTROUTING -j MASQUERADE

设置MTU

1
iptables -I FORWARD -p tcp --syn -i ppp+ -j TCPMSS --set-mss 1356

六、启动 xl2tpd 服务

1
2
/usr/local/sbin/xl2tpd
/usr/local/sbin/xl2tpd -D #以调式模式启动

参考资料:

1. http://www.linuxhomenetworking.com/wiki/index.php
2. http://www.linode.com/wiki/index.php/AndroidL2TPPSKServer
3. https://humou.net/blog/201102061326.html
4. http://b.gkp.cc/2010/06/19/setup-ipsec-l2tp-on-centos-55/
5. http://apple4.us/2010/05/setting-up-l2tp-vpn-on-debian-ubuntu.html

原文地址 : http://wangyan.org/blog/debian-l2tp-ipsec-vpn.html
本站遵循 : 知识共享署名-非商业性使用-相同方式共享 3.0 版权协议
版权声明 : 原创文章转载时,请务必以超链接形式标明 文章原始出处

shell> rpm --import http://www.jasonlitka.com/media/RPM-GPG-KEY-jlitka
shell> vi /etc/yum.repos.d/utterramblings.repo

[utterramblings]
name=Jason's Utter Ramblings Repo
baseurl=http://www.jasonlitka.com/media/EL$releasever/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://www.jasonlitka.com/media/RPM-GPG-KEY-jlitka

(3) 关闭yum fastestmirror 功能
shell> vi /etc/yum/pluginconf.d/fastestmirror.conf

enabled=0
yum -y install wget --noplugins
wget freevps.us/downloads/nginx-centos-6.sh -O - | bash

注意安装完成后 php-fpm 默认跑在 apache 用户上。

安装完成后,如果你需要的 PHP 扩展未安装,可输入如下命令查询:

yum list | grep ^php*

找到了扩展的名字,就可以直接安装了:

# 以 php memcache 扩展为例
yum install -y php-pecl-memcached

此外还遇到的问题是 DOMDocument 找不到,直接 yum 安装 php-xml:

yum install -y php-xml

所有扩展 yum 安装完成后都需要重新启动 / 载入 php-fpm。
贴下内容来看看(非最新版本,请直接下载 .sh 文件):

#!/bin/bash

##################
# disable apache #
##################
service httpd stop 
chkconfig httpd off
service xinetd stop
chkconfig xinetd off
service saslauthd stop
chkconfig saslauthd off
service sendmail stop
chkconfig sendmail off
service postfix stop
chkconfig postfix off

#Optimize yum on OpenVZ
if [ -e "/proc/user_beancounters" ]
then
  sed -i 's/plugins=1/plugins=0/' /etc/yum.conf
fi

#remove all current PHP and MySQL, will reinstall later. Also, remove apache 
yum -y remove httpd php mysql rsyslog sendmail postfix

###################
# Add a few repos #
###################
# install the Atomic repo for php and nginx (may use epel for nginx depending on version)
wget -q -O - http://www.atomicorp.com/installers/atomic | sh

# RPMForge for nginx dependencies
rpm -Uvh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm

#EPEL for syslog-ng and nginx (may use atomic for nginx depending on version)
rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm

################################
# Install PHP, NGINX and MySQL #
################################
#yum install GeoIP libGeoIP.so.1 --enablerepo=repoforge
yum -y install mysql-server php-fpm php-mysql php-gd nginx nano exim syslog-ng

#################
# install MySQL #
#################
#yum -y install mysql-server
cat > /etc/my.cnf <<END
[mysqld]
default-storage-engine = myisam
key_buffer = 8M
query_cache_size = 8M
query_cache_limit = 4M
max_connections=25
thread_cache=1
skip-innodb 
query_cache_min_res_unit=0
tmp_table_size = 4M
max_heap_table_size = 4M
table_cache=256
concurrent_insert=2 
END
echo  Do not worry if you see a error stopping MySQL or NGINX
/etc/init.d/mysqld stop
/etc/init.d/mysqld start

####################
# Set up NGINX PHP #
####################
cat > /etc/nginx/php <<END
index index.php index.html index.htm;

location ~ \.php$ {

   include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
  try_files \$uri =404;
    fastcgi_pass 127.0.0.1:9000;
    error_page 404 /404page.html; #makes nginx return it's default 404 
#	page instead of a blank page

} 
END

cat > /etc/nginx/nginx.conf <<END
user              nginx nginx;
worker_processes  2;

error_log         logs/error.log;

pid               logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    client_max_body_size 64M;
    sendfile        on;
    tcp_nopush      on;

    keepalive_timeout  3;

    gzip  on;
    gzip_comp_level 2;
    gzip_proxied any;
    gzip_types      text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    server_tokens off;

    include /etc/nginx/conf.d/*;
} 
END
rm /etc/nginx/conf.d/*
cat > /etc/nginx/conf.d/default.conf <<END
server {
    listen 80 default;
    server_name _;
    root /var/www/html;
    include php;

  } 
END
mkdir /usr/share/nginx/logs/
service nginx restart
chkconfig nginx on
chkconfig mysqld on

cat > /etc/php-fpm.d/www.conf <<END
; Start a new pool named 'www'.
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

; Set listen(2) backlog. A value of '-1' means unlimited.
; Default Value: -1
;listen.backlog = -1

; List of ipv4 addresses of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
listen.allowed_clients = 127.0.0.1

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0666
;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0666

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives:
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
; Note: This value is mandatory.
pm = dynamic

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes to be created when pm is set to 'dynamic'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI.
; Note: Used when pm is set to either 'static' or 'dynamic'
; Note: This value is mandatory.
pm.max_children = 5

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 1

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 1

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 3

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. By default, the status page shows the following
; information:
;   accepted conn    - the number of request accepted by the pool;
;   pool             - the name of the pool;
;   process manager  - static or dynamic;
;   idle processes   - the number of idle processes;
;   active processes - the number of active processes;
;   total processes  - the number of idle + active processes.
; The values of 'idle processes', 'active processes' and 'total processes' are
; updated each second. The value of 'accepted conn' is updated in real time.
; Example output:
;   accepted conn:   12073
;   pool:             www
;   process manager:  static
;   idle processes:   35
;   active processes: 65
;   total processes:  100
; By default the status page output is formatted as text/plain. Passing either
; 'html' or 'json' as a query string will return the corresponding output
; syntax. Example:
;   http://www.foo.bar/status
;   http://www.foo.bar/status?json
;   http://www.foo.bar/status?html
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set 
;pm.status_path = /status

; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;ping.path = /ping

; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
;ping.response = pong

; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0

; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0

; The log file for slow requests
; Default Value: /var/log/php-fpm.log.slow
;slowlog = /var/log/php-fpm.log.slow

; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: chrooting is a great security feature and should be used whenever 
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot = 

; Chdir to this directory at the start. This value must be an absolute path.
; Default Value: current directory or / when chroot
;chdir = /var/www

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Default Value: no
;catch_workers_output = yes

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'. 
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Default Value: nothing is defined by default except the values in php.ini and
;                specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 32M
php_admin_value[upload_max_filesize] = 32M
END

mkdir /var/www
mkdir /var/www/html/
useradd apache
service php-fpm start
chkconfig php-fpm on
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
service iptables save

wget freevps.us/downloads/setup-vhost.sh -O /bin/setup-vhost
chmod 755 /bin/setup-vhost
echo "alias nano='nano -w'" >> ~/.bashrc
clear
echo Installation done.
echo to create a vhost, run
echo setup-vhost example.com
echo do not include the www. subdomain.

什么是epel

如果既想获得 RHEL 的高质量、高性能、高可靠性,又需要方便易用(关键是免费)的软件包更新功能,那么 Fedora Project 推出的 EPEL(Extra Packages for Enterprise Linux)正好适合你。EPEL(http://fedoraproject.org/wiki/EPEL) 是由 Fedora 社区打造,为 RHEL 及衍生发行版如 CentOS、Scientific Linux 等提供高质量软件包的项目。

安装http://mirrors.sohu.com/fedora-epel/6/x86_64/epel-release-6-5.noarch.rpm

[root@centos6 ~]# ll /etc/yum.repos.d/
total 20
-rw-r--r--. 1 root root 1926 Jul 3 10:16 CentOS-Base.repo
-rw-r--r--. 1 root root 637 Jul 3 10:16 CentOS-Debuginfo.repo
-rw-r--r--. 1 root root 624 Oct 24 13:06 CentOS-Media.repo
-rw-r--r--. 1 root root 957 Oct 12 2010 epel.repo
-rw-r--r--. 1 root root 1056 Oct 12 2010 epel-testing.repo

查看epel.repo内容如下

[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 6 - $basearch - Debug
#baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch/debug
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-6&arch=$ba search
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 6 - $basearch - Source
#baseurl=http://download.fedoraproject.org/pub/epel/6/SRPMS
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-source-6&arch=$b asearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
gpgcheck=1

 

为什么要配置epel源呢

 

因为rhel6里很多开发包没有在iso里,在epel的源里!rhel6 是建立在fedra 12上的

感谢kevin的提醒

本文出自 “学习linux” 博客,请务必保留此出处http://tonychiu.blog.51cto.com/656605/696442