月度归档:2016年06月

使用iptables-persistent持久化iptables规则

正常情况下,我们写入的iptables规则将会在系统重启时消失。即使我们使用iptables-save命令将iptables规则存储到文件,在系统重启后也需要执行iptables-restore操作来恢复原有规则。(当然,你也可以通过在network中的if.post.up.d中配置启动规则来达到开机自动启动iptables的方法)

这里我们有一个更好的iptables持久化方案,让防火墙规则重启后依旧有效。即使用iptables-persistent工具。

首先,安装:

sudo apt-get install iptables-persistent

安装完后即可使用以下命令保存或载入规则:

Ubuntu 14.04

sudo invoke-rc.d iptables-persistent save
sudo invoke-rc.d iptables-persistent reload

或者

sudo /etc/init.d/iptables-persistent save 
sudo /etc/init.d/iptables-persistent reload

Ubuntu 16.04

sudo netfilter-persistent save
sudo netfilter-persistent reload

生成的规则将被存储在以下文件中

/etc/iptables/rules.v4
/etc/iptables/rules.v6

参考:How to save rules of the iptables?

在Ubuntu上配置PPTP VPN服务器

With a PPTP server, you can setup a VPN server easily. Having a virtual private network is beneficial to both individual users and businesses alike.

This tutorial explains how you can install a PPTP server on Ubuntu. The steps are generic, they should apply to almost all versions of Ubuntu.

Step 1: Installing pptpd

The first thing that we need to do is, naturally, install pptpd.

apt-get install pptpd

Installing PPTPD is that easy! Now we need to actually setup the PPTP server.

Step 2: Adding users

We don’t want everyone to be able to access our VPN of course; because of this, you can create users so that only the users with the correct password will be able to access your VPN. To add users, edit the file:

/etc/ppp/chap-secrets

The format is:

[username] [service] [password] [ip]

Username and password are pretty straightforward, service and IP are not though. Service is usually pptpd. If you just want to setup a VPN, use pptpd for the service – it will work. If you want to restrict the IP that a user can login from, you can use his/her IP. If you want connections from that account to be made from all IPs, you can use *.

Sample:

# Secrets for authentication using CHAP
# client        server  secret                  IP addresses
user001 * password001 *
user002 pptp password002 *
user003 * password001 123.123.123.123
# The first * means you can use both pptpd and l2tpd

Step 3: Edit the pptpd settings

There are a few things that we need to edit. Start by editing the following file:

/etc/pptpd/pptpd.conf

Look for the localip and remoteip settings. Remove the # (comment character) for both so that these settings will actually be recognized. Change localip to your server IP. If you don’t know your server IP, use ifconfig command

ifconfig

The remoteip is basically the IP range that clients (computers that are connected to your VPN) will be assigned. For example, if you want the following IP range: 192.168.120.231-235, your VPN server will be able to assign 192.168.120.232, 192.168.120.233, 192.168.120.234, and 192.168.120.235 to clients. It’s up to you what you want to use for this field.

Step 4: Update sysctl.conf

Find the line net.ipv4.ip_forward in the sysctl.conf file. We need to uncomment this line, so open the following file:

/etc/sysctl.conf

Make sure that it says net.ipv4.ip_forward=1, and not net.ipv4.ip_forward=0.

Then make changes active:

sysctl -p

Step 5: Restarting pptpd

At this point, everything will work. Restart pptpd.

service pptpd restart

Congratulations, you now have a PPTP server!

Ref:

使用python发送邮件

使用python能够非常方便的发送邮件。只需要引入smtplib这个模块即可。下面是简单的示例代码:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

mail_host="smtp.sendhost.com"
mail_user="sender@sendhost.com"
mail_pass="sender_password"

sender = 'send@receivehost.com'
receivers = ['receive@areceivehost.com']


def sendMail(content):
    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = Header("send_name", 'utf-8')
    message['To'] = Header("receive_name", 'utf-8')

    subject = 'sample_title'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP_SSL()
        #smtpObj.set_debuglevel(1)
        smtpObj.connect(mail_host, 465)
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print "Send Mail Succeed"
    except smtplib.SMTPException:
        print "Error: Send Mail Failed"

如果使用非SSL方式则使用smptlib.SMTP()方法。

uwsgi使用不同的python版本

As we have seen, uWSGI is composed of a small core and various plugins. Plugins can be embedded in the binary or loaded dynamically. When you build uWSGI for Python, a series of plugins plus the Python one are embedded in the final binary.

This could be a problem if you want to support multiple Python versions without building a binary for each one.

The best approach would be having a little binary with the language-independent features built in, and one plugin for each Python version that will be loaded on-demand.

In the uWSGI source directory:

make PROFILE=nolang

This will build a uwsgi binary with all the default plugins built-in except the Python one.

Now, from the same directory, we start building Python plugins:

PYTHON=python3.4 ./uwsgi --build-plugin "plugins/python python34"
PYTHON=python2.7 ./uwsgi --build-plugin "plugins/python python27"
PYTHON=python2.6 ./uwsgi --build-plugin "plugins/python python26"

You will end up with three files: python34_plugin.so, python27_plugin.so, python26_plugin.so. Copy these into your desired directory. (By default, uWSGI searches for plugins in the current working directory.)

Now in your configurations files you can simply add (at the very top) the plugins-dir and plugin directives.

[uwsgi]
plugins-dir = <path_to_your_plugin_directory>
plugin = python26

This will load the python26_plugin.so plugin library from the directory into which you copied the plugins.

From: Quickstart for Python/WSGI applications

使用uwsgi运行flask

由于python2.x和python3.x所用的命令和配置有所区别,在本文中如果有不一致的地方将特别标明。

首先更新一下系统和软件:

apt-get update
apt-get upgrade

安装pip

apt-get install pip    #python2.x
apt-get install pip3   #python3.x

(可选)如果是python3.x,为了方便这里统一一下pip命令,之后python3.x环境也可以直接执行pip命令

cd /usr/bin
ln -s pip3 pip

安装virtualenv虚拟环境

pip install virtualenv

下面我们在/var/www目录下创建一个flask项目:

mkdir -p /var/www/myproj/
cd /var/www/myproj/
vim manage.py

项目内容很简单,就是一个典型的flask app

# /var/www/myproj/manage.py
---

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(host='0.0.0.0')

下面我们要创建运行flask的虚拟环境。

首先创建一个虚拟环境:

cd /var/www/myproj/
virtualenv venv --no-site-packages    # 需求虚拟环境使用的python版本和系统环境相同
virtualenv -p /usr/bin/python3 venv   # 系统环境为python2.x, 虚拟环境为python3.x
virtualenv -p /usr/bin/python2 venv   # 系统环境为python3.x, 虚拟环境为python2.x

启动虚拟环境并安装flask:

cd /var/www/myproj/
. venv/bin/activate
(venv)# pip install flask

测试一下能否正常运行:

python manage.py

不报错即为正常。

下面安装uwsgi和nginx。

apt-get install nginx uwsgi
apt-get install uwsgi-plugin-python    # python2.x
apt-get install uwsgi-plugin-python3   # python3.x

创建一个socket用于链接nginx和uwsgi

cd /tmp/
touch myproj.sock
chown www-data:www-data myproj.sock

配置uwsgi

创建uwsgi配置文件/etc/uwsgi/apps-available/myproj.ini

[uwsgi]
vhost = true
socket = /tmp/myproj.sock
venv = /var/www/myproj/env
chdir = /var/www/myproj
module = manage     # flask的启动脚本名称
callable = app      # flask实例名称

如果flask的启动脚本为/var/www/myproj/run.py,flask的实例声明如下:

my_app = Flask(__name__)

则uwsgi配置文件中应做如下修改

module = run
callable = my_app

使配置生效

ln -s /etc/uwsgi/apps-available/myproj.ini /etc/uwsgi/apps-enabled/myproj.ini
service uwsgi restart

最后修改nginx配置文件/etc/nginx/sites-available/myproj

server {
    listen 80;
    server_tokens off;
    server_name www.myproj.com myproj.com;

     location / {
         include uwsgi_params;
         uwsgi_pass unix:/tmp/myproj.sock;
     }

     location /static {
         alias /var/www/myproj/static;
     }

     ## Only requests to our Host are allowed
     if ($host !~ ^(myproj.com|www.myproj.com)$ ) {
        return 444;
     }
}

使nginx配置生效

ln -s /etc/nginx/sites-available/myproj /etc/nginx/sites-enabled/myproj
service nginx restart

这样配置就结束了。最后是几个容易出现的问题:

  • myproj.sock文件的所有者不是www-data。由于uwsgi的默认用户是www-data,所以.sock需要保持一致。
  • 使用python3时未配置对应的插件和命令。uwsgi-plugin-python(3)这个脚本请安装对应版本。
  • 更多问题参见nginx和uwsgi的log,都在/var/log/目录下

参考:

Running flask with virtualenv, uwsgi, and nginx

How To Serve Flask Applications with uWSGI and Nginx on Ubuntu 14.04

 

设置bash alias别名及取消

设置bash_alias别名

之前在使用python3的时候有提到过如何将bash的默认python命令切换到python3。具体做法如下:

在用户目录创建 .bash_alias文件

vim ~/.bash_alias

在其中写入别名信息

alias python=python3

执行source命令生效

source ~/.bash_alias

此时执行python命令进入的shell就是python3了。

这样做带来的问题

但是,这样做之后会对虚拟环境产生影响,比如我写了这样一个别名:

alias python=python2.7

即将默认的python以python2.7执行。

那么,我如果创建一个python3的虚拟环境,并在其中执行python命令:

root@localhost:~# virtualenv -p /usr/bin/python3 env
root@localhost:~# . env/bin/activate
(env)root@localhost:~# python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

这里我们看到,所调用的python为2.7.6,即并没有使用虚拟环境中的python3。这就是由于我们手动设定bash_alias的结果

取消别名

取消别名十分简单,在命令行下直接执行unalias命令即可,比如:

(env)root@localhost:~# unalias python
(env)root@localhost:~# python
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

查看所有的alias可以直接键入alias命令

使用virtualenv创建python3环境

默认使用virtualenv创建的虚拟环境是python2.7的

virtualenv env

需要创建python3的环境只需要在创建环境的时候加上python3的路径即即可。

使用以下命令:

virtualenv -p /usr/bin/python3 env

虚拟环境就被创建在了env目录下。启动和退出的命令不变:

# start from env
. env/bin/activate
# quit from env
deactivate