分类目录归档:Linux

Openwrt路由器使用Python自动登录北航校园网

环境配置

关于在Openwrt上安装Python可以参考这里

https://wiki.openwrt.org/doc/software/python

使用本程序请先安装Python

代码内容

在~目录下写buaa.py,内容如下

import urllib
import urllib2
import hashlib
import os
 
 
#Here input your username and password
username = 'xxx'
password = 'xxx'


def check_network():
	response = urllib2.urlopen('http://www.offer4u.cn/ping', timeout=3)
	response.close()
	return response.getcode() == 204

def login(username,password):
	md5 = hashlib.md5()
	md5.update(password)
	password = md5.hexdigest()[8:-8];
	url = 'http://gw.buaa.edu.cn/cgi-bin/do_login'
	values = {'username':username,'password':password,'drop':'0','type':'1','n':'100'}
	data = urllib.urlencode(values)
	req = urllib2.Request(url, data)
	response = urllib2.urlopen(req, timeout=3)
	page_result= response.read()
	response.close()
	if page_result.isdigit() == True:
		return "\033[1;32m%s\033[0m" % "Login successful"
	elif page_result == "password_error":
		return "\033[1;31m%s\033[0m" % "Wrong password"
	else:
		return "\033[1;31m%s\033[0m" % "Unknown error" + page_result

def light(on):
	if on == 1:
		os.system('echo 1 > /sys/class/leds/y1\:blue\:internet/brightness')
	else:
		os.system('echo 0 > /sys/class/leds/y1\:blue\:internet/brightness')
#main
try:
	if check_network() == False:
		light(0)
		result = login(username,password)
		if "successful" in result:
			light(1)
		else:
			light(0)
		print result
	else:
		light(1)
		print "\033[1;34m%s\033[0m" % "Network connection is working"
except:
	light(0)
	print "\033[1;31m%s\033[0m" % "Processing error"

代码解析

  1. 该程序运行时,首先检测网络是否连通(check_network函数),如果网络不连通则进行(login函数),然后根据登录结果输出提示或错误,并控制路由器上的一个灯来表示网络是否连通
  2. 其中http://www.offer4u.cn/ping,这个网址将在网络正常情况下返回204HTTPCODE,这个工作方式和google的类似,本来可以用google.cn的但是由于北航内部有IPV6所以会导致该网址一直处于连通状态,所以用了国内的版本。
  3. 下面这部分是一个shell脚本,用来控制我用的路由器,联想Y1上面的Internet灯的开关,网络连通时让该灯亮起(echo 1),不连通则关闭(echo 0)该灯
    echo 0 > /sys/class/leds/y1\:blue\:internet/brightness

    如果你是其他的路由器,请打开/sys/class/leds/ 目录,找到你想控制的灯,修改y1\:blue\:internet 即可(这里的反斜杠是转义符)
    QQ截图20160304003544
    这款路由器推荐一下非常不错,支持U盘并且内存和运存等配置足够支持运行和安装很多软件,并且价格便宜,我买的时候才70多

  4. 我们可以在编写完后执行python -m py_compile buaa.py ,把py编译成pyc提升性能

持续运行

  1. 在使用的过程中可能会断网,甚至比如北航会在凌晨4点准时断网,所以我们需要启用crontab来持续运行该脚本
    crontab -e

    然后我们输入

    */1 * * * * python ~/buaa.pyc > /dev/null
    */1 * * * * sleep 20; python ~/buaa.pyc > /dev/null
    */1 * * * * sleep 40; python ~/buaa.pyc > /dev/null

    这样就会每隔20秒运行我们的脚本,如果网络断开就会自动连通,其中> /dev/null 是用来关闭输出
    其中Openwrt不会默认启动crontab,我们还需要执行一下命令

    /etc/init.d/cron start
    /etc/init.d/cron enable
  2. 我们可以在连接之后手动登录北航http://gw.buaa.edu.cn/index.php,来查看是否登录成功和用户及流量状况

Openwrt安装完整版vim,支持代码变色和缩进

Openwrt默认的是vi而不是vim,如果想使用必须安装vim-full,同时要安装vim-runtime

opkg update
opkg install vim-full vim-runtime

我们输入vim就可以看见安装成功

QQ截图20160303225938

然后执行下面的命令编辑vim配置

vim /usr/share/vim/vimrc

同时分享一下我的配置

set showcmd         " show (partial) command in status line
set showmatch       " show matching brackets
set incsearch       " incremental search
set autowrite       " automatically save before commands like :next and :make
set nocompatible    " use vim defaults instead of 100% vi compatibility
set backspace=indent,eol,start  " more powerful backspacing
set autoindent      " always set autoindenting on
set linebreak       " don't wrap words by default
set textwidth=0     " don't wrap lines by default
set ruler           " show the cursor position all the time

set backupskip+=/etc/crontabs.* " fix crontab -e

"set number       "设置行号
syntax on         "语法高亮
filetype on       "文件类型检测
set tabstop=4
set softtabstop=4
set shiftwidth=4

 

在Nginx下新建虚拟主机搭建wordpress(新手向)

搭建环境:

Nginx-1.8.0,安装目录:/usr/local/nginx

PHP-7.0,虚拟主机目录在/home/vhosts/

下载wordpress,建立虚拟主机目录

首先,我们进入虚拟主机目录,新建一个wordpress目录,下载wordpress并解压

cd /home/vhosts/
mkdir wordpress
cd wordpress
wget https://cn.wordpress.org/wordpress-4.4-zh_CN.zip
unzip wordpress-4.4-zh_CN.zip

然后我们把wordpress解压文件夹里面的文件移动到外面来,删除刚才下载的压缩包和wordpress-4.4-zh_CN.zip

mv wordpress/* ./
rm -rf wordpress*

然后我们把wordpress文件夹的权限和所有者更改一下(当前目录还为/home/vhosts/wordpress )

这里演示的是Nginxphp-fpm的用户和用户组均为nginx

chmod -R 755 ./
chown -R nginx.nginx ./

配置虚拟主机

然后,我们到Nginx的安装目录,到你虚拟主机的配置文件目录中增加一份配置(这里我新建了一个专门的目录来放虚拟主机配置文件,在/usr/local/nginx/vhosts 下)

cd /usr/local/nginx/vhosts
vi wordpress.conf

把下面的配置文件内容粘贴进去(用Windows的注意下回车和编码)

注意,其中的root目录为你wordpress虚拟主机的目录

server_name为监听的域名,这里用www.yourdomain.com做演示

server {
	listen			80;
	server_name		www.yourdomain.com;
	index			index.html index.htm index.php;
	root			/home/vhosts/wordpress;
	location ~ .*\.(gif|jpg|jpeg|png|bmp|ico|webp)$
	{
		expires 30d;
	}
	location ~ .*\.(woff|ttf|svg|otf|eot)$
	{
		expires 180d;
	}
	location ~ .*\.(js|css)?$
	{
		expires 12h;
	}
	location /
	{
		#支持wordpress的rewrite
		if (!-e $request_filename) { 
			rewrite ^(.*)$ /index.php/$1 last;
			break;
		}
	}
	location ~ \.php($|/)
	{
		fastcgi_pass 127.0.0.1:9000;
		fastcgi_index index.php;
		fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
		include	fastcgi_params;
	}
}

接着按下Esc,输入:wq 退出vi

MySQL配置

然后我们进入mysql

mysql -u root -p

输入你的密码之后,创建wordpress数据库

create database wordpress;

接着创建一个wordpress数据库的帐号,账号名为wp,密码为123456(修改成你自己的)

grant all privileges on wordpress.* to wp@localhost identified by '123456';

完成

然后我们重载入nginx

service nginx reload

现在,访问www.yourdomain.com,用刚才创建的数据库用户名和密码安装wordpress吧

htpasswd.py,用来生成Nginx或Apache密码访问数据库

#!/usr/bin/python
"""Replacement for htpasswd"""
# Original author: Eli Carter

import os
import sys
import random
from optparse import OptionParser

# We need a crypt module, but Windows doesn't have one by default.  Try to find
# one, and tell the user if we can't.
try:
    import crypt
except ImportError:
    try:
        import fcrypt as crypt
    except ImportError:
        sys.stderr.write("Cannot find a crypt module.  "
                         "Possibly http://carey.geek.nz/code/python-fcrypt/\n")
        sys.exit(1)


def salt():
    """Returns a string of 2 randome letters"""
    letters = 'abcdefghijklmnopqrstuvwxyz' \
              'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
              '0123456789/.'
    return random.choice(letters) + random.choice(letters)


class HtpasswdFile:
    """A class for manipulating htpasswd files."""

    def __init__(self, filename, create=False):
        self.entries = []
        self.filename = filename
        if not create:
            if os.path.exists(self.filename):
                self.load()
            else:
                raise Exception("%s does not exist" % self.filename)

    def load(self):
        """Read the htpasswd file into memory."""
        lines = open(self.filename, 'r').readlines()
        self.entries = []
        for line in lines:
            username, pwhash = line.split(':')
            entry = [username, pwhash.rstrip()]
            self.entries.append(entry)

    def save(self):
        """Write the htpasswd file to disk"""
        open(self.filename, 'w').writelines(["%s:%s\n" % (entry[0], entry[1])
                                             for entry in self.entries])

    def update(self, username, password):
        """Replace the entry for the given user, or add it if new."""
        pwhash = crypt.crypt(password, salt())
        matching_entries = [entry for entry in self.entries
                            if entry[0] == username]
        if matching_entries:
            matching_entries[0][1] = pwhash
        else:
            self.entries.append([username, pwhash])

    def delete(self, username):
        """Remove the entry for the given user."""
        self.entries = [entry for entry in self.entries
                        if entry[0] != username]


def main():
    """%prog [-c] -b filename username password
    Create or update an htpasswd file"""
    # For now, we only care about the use cases that affect tests/functional.py
    parser = OptionParser(usage=main.__doc__)
    parser.add_option('-b', action='store_true', dest='batch', default=False,
        help='Batch mode; password is passed on the command line IN THE CLEAR.'
        )
    parser.add_option('-c', action='store_true', dest='create', default=False,
        help='Create a new htpasswd file, overwriting any existing file.')
    parser.add_option('-D', action='store_true', dest='delete_user',
        default=False, help='Remove the given user from the password file.')

    options, args = parser.parse_args()

    def syntax_error(msg):
        """Utility function for displaying fatal error messages with usage
        help.
        """
        sys.stderr.write("Syntax error: " + msg)
        sys.stderr.write(parser.get_usage())
        sys.exit(1)

    if not options.batch:
        syntax_error("Only batch mode is supported\n")

    # Non-option arguments
    if len(args) < 2:
        syntax_error("Insufficient number of arguments.\n")
    filename, username = args[:2]
    if options.delete_user:
        if len(args) != 2:
            syntax_error("Incorrect number of arguments.\n")
        password = None
    else:
        if len(args) != 3:
            syntax_error("Incorrect number of arguments.\n")
        password = args[2]

    passwdfile = HtpasswdFile(filename, create=options.create)

    if options.delete_user:
        passwdfile.delete(username)
    else:
        passwdfile.update(username, password)

    passwdfile.save()


if __name__ == '__main__':
    main()

用法参考下面

Usage: htpasswd.py [-c] -b filename username password
    Create or update an htpasswd file

Options:
  -h, --help  show this help message and exit
  -b          Batch mode; password is passed on the command line IN THE CLEAR.
  -c          Create a new htpasswd file, overwriting any existing file.
  -D          Remove the given user from the password file.

在Nginx设置密码访问的配置

server {
        ***
        auth_basic              "Please enter the security code";
        auth_basic_user_file    /usr/local/nginx-1.8.0/htpasswd/mysql.db;
        ***
}

 

Linux编译安装PHP7

下载PHP7

这里是版本7.0.1,使用下面命令下载编译包然后解压

wget http://php.net/get/php-7.0.1.tar.gz/from/this/mirror -O php-7.0.1.tar.gz
tar zxvf php-7.0.1.tar.gz

安装必要的环境

yum -y install libxml2 libxml2-devel openssl openssl-devel curl-devel libjpeg-devel libpng-devel freetype-devel libmcrypt-devel

配置

./configure \
--prefix=/usr/local/php-7.0.1 \
--with-mcrypt \
--with-mhash \
--with-openssl \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-gd \
--with-iconv \
--with-zlib \
--enable-zip \
--enable-inline-optimization \
--disable-debug \
--disable-rpath \
--enable-shared \
--enable-xml \
--enable-bcmath \
--enable-shmop \
--enable-sysvsem \
--enable-mbregex \
--enable-mbstring \
--enable-ftp \
--enable-gd-native-ttf \
--enable-pcntl \
--enable-sockets \
--with-xmlrpc \
--enable-soap \
--without-pear \
--with-gettext \
--enable-session \
--with-curl \
--with-jpeg-dir \
--with-freetype-dir \
--enable-opcache \
--enable-fpm \
--with-fpm-user=nginx \
--with-fpm-group=nginx \
--disable-fileinfo

其中可以增加–with-mysql-sock=[dir] 来设置mysql的sock文件的位置,默认是/tmp/mysql.sock

–prefix 是你要安装的位置

编译和安装

make
make install

设置配置文件,还是刚才编译的目录中,执行

cp php.ini-production /usr/local/php-7.0.1/lib/php.ini
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
cp /usr/local/php-7.0.1/etc/php-fpm.conf.default /usr/local/php-7.0.1/etc/php-fpm.conf
cp /usr/local/php-7.0.1/etc/php-fpm.d/www.conf.default /usr/local/php-7.0.1/etc/php-fpm.d/www.conf

其中/usr/local/php-7.0.1/ 是你的安装位置,请替换成你自己的

添加服务并启动

chmod +x /etc/init.d/php-fpm
chkconfig --add php-fpm
chkconfig php-fpm on
service php-fpm start

环境变量

修改/etc/profile文件使其永久性生效,并对所有系统用户生效,在文件末尾加上如下两行代码

PATH=$PATH:/usr/local/php-7.0.1/bin
export PATH

Let’s Encrypt在XP下的支持问题

目前Let’s Encrypt在Windows XP下总共遇到了两种问题

第一种是因为不支持SNI,SNI允许HTTPS在握手的时候发送主机名,从而使得每个虚拟主机可以根据域名配置不同的证书,如下图所示

QQ图片20151222224447 - 副本 QQ图片20151222224452 - 副本

第二种,可能是因为交叉信任的原因,导致的是证书不信任,但是名称正确

QQ图片20151222224458

总之,还是淘汰XP系统吧