Archive for the ‘Linux’ Category

ohana – 一个返回模拟 json 数据的 node http server

ohana – 一个返回模拟 json 数据的 node http server
ohana 是一个返回模拟 json 数据的 node http 服务器,默认集成了 mockjs 生成动态的 json 数据,支持 POST, GET, PUT, DELETE 四种请求。
github: https://github.com/Allenice/ohana
特点:
使用 mockjs 生成 json 数据
支持路由规则
可跨域访问
安装
npm config set registry http://registry.cnpmjs.org
npm install ohana
使用
var Server = require(“ohana”);
var server = new Server();
server.get(‘/article/’, {
delay: 200,
data: function(params, query) {
console.log(params);
console.log(query);
return {
“status”: “ok”,
“total_count”: 100,
“data|10″: [
{
"id|1-10000": 1,
"title": "@TITLE(5, 7)",
"author": "@NAME",
"post_time": "@DATETIME('yyyy-MM-dd HH:mm:ss')",
"read_count|0-1000": 100
}
]
}
}
});
server.listen(3000);
API
server.get(path, options)
匹配 GET 方式的请求。
path: 路由匹配地址
options:
delay: 延迟多少毫秒后返回,
data: 返回的数据,可以接受对象和方法, 方法中的参数 params 是路由匹配的参数,query 是提交或查询的参数。
server.post(path, options)
与 get 同理
server.delete(path, options)
与 get 同理
server.put(path, options)
与 get 同理
server.listen(port, host)
port: 服务器监听的网络端口
host: 主机
路由匹配规则:
Basic string:
“/articles” will only match routes that == “/articles”.
Named parameters:
“/articles/:title” will only match routes like “/articles/hello”, but *not* “/articles/”.
Optional named parameters:
“/articles/:title?” will match “/articles/hello” AND “/articles/”
Periods before optional parameters are also optional:
“/:n.:f?” will match “/1″ and “/1.json”
Splaaaat! :
“/assets/*” will match “/assets/blah/blah/blah.png” and “/assets/”.
“/assets/*.*” will match “/assets/1/2/3.js” as splats: ["1/2/3", "js"]
Mix splat with named parameters:
“/account/:id/assets/*” will match “/account/2/assets/folder.png” as params: {id: 2}, splats:["folder.png"]
Named RegExp:
“/lang/:lang([a-z]{2})” will match “/lang/en” but not “/lang/12″ or “/lang/eng”
Raw RegExp:
/^\/(\d{2,3}-\d{2,3}-\d{4})\.(\w*)$/ (note no quotes, this is a RegExp, not a string.) will match “/123-22-1234.json”. Each match group will be an entry in splats: ["123-22-1234", "json"]
参考: https://github.com/aaronblohowiak/routes.js
数据生成
ohana 默认集成了 mockjs,你可以使用 mockjs 生成 json 数据。当然你也可以使用其他的生成工具。
参考文档: http://mockjs.com/editor.html#help

ohana – 一个返回模拟 json 数据的 node http server
ohana 是一个返回模拟 json 数据的 node http 服务器,默认集成了 mockjs 生成动态的 json 数据,支持 POST, GET, PUT, DELETE 四种请求。
github: https://github.com/Allenice/ohana
特点:
使用 mockjs 生成 json 数据支持路由规则可跨域访问安装
npm config set registry http://registry.cnpmjs.orgnpm install ohana使用
var Server = require(“ohana”);var server = new Server();server.get(‘/article/’, {  delay: 200,  data: function(params, query) {    console.log(params);    console.log(query);    return {      “status”: “ok”,      “total_count”: 100,      “data|10″: [        {          "id|1-10000": 1,          "title": "@TITLE(5, 7)",          "author": "@NAME",          "post_time": "@DATETIME('yyyy-MM-dd HH:mm:ss')",          "read_count|0-1000": 100        }      ]    }  }});server.listen(3000);API
server.get(path, options)
匹配 GET 方式的请求。
path: 路由匹配地址options:delay: 延迟多少毫秒后返回,data: 返回的数据,可以接受对象和方法, 方法中的参数 params 是路由匹配的参数,query 是提交或查询的参数。server.post(path, options)
与 get 同理
server.delete(path, options)
与 get 同理
server.put(path, options)
与 get 同理
server.listen(port, host)
port: 服务器监听的网络端口host: 主机路由匹配规则:
Basic string:
“/articles” will only match routes that == “/articles”.Named parameters:
“/articles/:title” will only match routes like “/articles/hello”, but *not* “/articles/”.Optional named parameters:
“/articles/:title?” will match “/articles/hello” AND “/articles/”Periods before optional parameters are also optional:
“/:n.:f?” will match “/1″ and “/1.json”Splaaaat! :
“/assets/*” will match “/assets/blah/blah/blah.png” and “/assets/”.
“/assets/*.*” will match “/assets/1/2/3.js” as splats: ["1/2/3", "js"]Mix splat with named parameters:
“/account/:id/assets/*” will match “/account/2/assets/folder.png” as params: {id: 2}, splats:["folder.png"]Named RegExp:
“/lang/:lang([a-z]{2})” will match “/lang/en” but not “/lang/12″ or “/lang/eng”Raw RegExp:
/^\/(\d{2,3}-\d{2,3}-\d{4})\.(\w*)$/ (note no quotes, this is a RegExp, not a string.) will match “/123-22-1234.json”. Each match group will be an entry in splats: ["123-22-1234", "json"]参考: https://github.com/aaronblohowiak/routes.js
数据生成
ohana 默认集成了 mockjs,你可以使用 mockjs 生成 json 数据。当然你也可以使用其他的生成工具。参考文档: http://mockjs.com/editor.html#help

nginx php mysql 需要安装的扩展包

129  yum install gcc
134  yum install ncurses
135  yum install glibc-headers
136  yum install gcc-c++
142  yum -y install libxml2 libxml2-devel
143  yum install curl curl-devel
144  yum install openssl openssl-devel
145  yum install bzip2 bzip2-devel
146  yum install libjpeg libjpeg-devel
147  yum install libpng libpng-devel
148  yum install freetype-devel
149  yum install gmp-devel
150  yum install libmcrypt libmcrypt-devel
163  yum -y install pcre pcre-devel

php-fpm configure

./configure –prefix=/usr/local/php –with-config-file-path=/usr/local/php/etc –enable-fpm –with-fpm-user=administrator –with-fpm-group=administrator –enable-safe-mode

url提取url

$reg = “‘<\s*a\s.*?href\s*=\s*([\"\'])?(?(1)(.*?)\\1|([^\s\>]+))[^>]*>?(.*?)’isx”;

C语言实现的简单 Web 服务器

/*
* WebServer.c
*
*  Created on: Nov 3, 2012
*      Author: pavithra
*
* A web server in C language using only the standard libraries.
* The port number is passed as an argument.
*
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>
#define EOL “\r\n”
#define EOL_SIZE 2
typedef struct {
char *ext;
char *mediatype;
} extn;
//Possible media types
extn extensions[] ={
{“gif”, “image/gif” },
{“txt”, “text/plain” },
{“jpg”, “image/jpg” },
{“jpeg”,”image/jpeg”},
{“png”, “image/png” },
{“ico”, “image/ico” },
{“zip”, “image/zip” },
{“gz”,  ”image/gz”  },
{“tar”, “image/tar” },
{“htm”, “text/html” },
{“html”,”text/html” },
{“php”, “text/html” },
{“pdf”,”application/pdf”},
{“zip”,”application/octet-stream”},
{“rar”,”application/octet-stream”},
{0,0} };
/*
A helper function
*/
void error(const char *msg) {
perror(msg);
exit(1);
}
/*
A helper function
*/
int get_file_size(int fd) {
struct stat stat_struct;
if (fstat(fd, &stat_struct) == -1)
return (1);
return (int) stat_struct.st_size;
}
/*
A helper function
*/
void send_new(int fd, char *msg) {
int len = strlen(msg);
if (send(fd, msg, len, 0) == -1) {
printf(“Error in send\n”);
}
}
/*
This function recieves the buffer
until an “End of line(EOL)” byte is recieved
*/
int recv_new(int fd, char *buffer) {
char *p = buffer; // Use of a pointer to the buffer rather than dealing with the buffer directly
int eol_matched = 0; // Use to check whether the recieved byte is matched with the buffer byte or not
while (recv(fd, p, 1, 0) != 0) // Start receiving 1 byte at a time
{
if (*p == EOL[eol_matched]) // if the byte matches with the first eol byte that is ‘\r’
{
++eol_matched;
if (eol_matched == EOL_SIZE) // if both the bytes matches with the EOL
{
*(p + 1 – EOL_SIZE) = ‘\0′; // End the string
return (strlen(buffer)); // Return the bytes recieved
}
} else {
eol_matched = 0;
}
p++; // Increment the pointer to receive next byte
}
return (0);
}
/*
A helper function: Returns the
web root location.
*/
char* webroot() {
// open the file “conf” for reading
FILE *in = fopen(“conf”, “rt”);
// read the first line from the file
char buff[1000];
fgets(buff, 1000, in);
// close the stream
fclose(in);
char* nl_ptr = strrchr(buff, ‘\n’);
if (nl_ptr != NULL)
*nl_ptr = ‘\0′;
return strdup(buff);
}
/*
Handles php requests
*/
void php_cgi(char* script_path, int fd) {
send_new(fd, “HTTP/1.1 200 OK\n Server: Web Server in C\n Connection: close\n”);
dup2(fd, STDOUT_FILENO);
char script[500];
strcpy(script, “SCRIPT_FILENAME=”);
strcat(script, script_path);
putenv(“GATEWAY_INTERFACE=CGI/1.1″);
putenv(script);
putenv(“QUERY_STRING=”);
putenv(“REQUEST_METHOD=GET”);
putenv(“REDIRECT_STATUS=true”);
putenv(“SERVER_PROTOCOL=HTTP/1.1″);
putenv(“REMOTE_HOST=127.0.0.1″);
execl(“/usr/bin/php-cgi”, “php-cgi”, NULL);
}
/*
This function parses the HTTP requests,
arrange resource locations,
check for supported media types,
serves files in a web root,
sends the HTTP error codes.
*/
int connection(int fd) {
char request[500], resource[500], *ptr;
int fd1, length;
if (recv_new(fd, request) == 0) {
printf(“Recieve Failed\n”);
}
printf(“%s\n”, request);
// Check for a valid browser request
ptr = strstr(request, ” HTTP/”);
if (ptr == NULL) {
printf(“NOT HTTP !\n”);
} else {
*ptr = 0;
ptr = NULL;
if (strncmp(request, “GET “, 4) == 0) {
ptr = request + 4;
}
if (ptr == NULL) {
printf(“Unknown Request ! \n”);
} else {
if (ptr[strlen(ptr) - 1] == ‘/’) {
strcat(ptr, “index.html”);
}
strcpy(resource, webroot());
strcat(resource, ptr);
char* s = strchr(ptr, ‘.’);
int i;
for (i = 0; extensions[i].ext != NULL; i++) {
if (strcmp(s + 1, extensions[i].ext) == 0) {
fd1 = open(resource, O_RDONLY, 0);
printf(“Opening \”%s\”\n”, resource);
if (fd1 == -1) {
printf(“404 File not found Error\n”);
send_new(fd, “HTTP/1.1 404 Not Found\r\n”);
send_new(fd, “Server : Web Server in C\r\n\r\n”);
send_new(fd, “<html><head><title>404 Not Found</head></title>”);
send_new(fd, “<body><p>404 Not Found: The requested resource could not be found!</p></body></html>”);
//Handling php requests
} else if (strcmp(extensions[i].ext, “php”) == 0) {
php_cgi(resource, fd);
sleep(1);
close(fd);
exit(1);
} else {
printf(“200 OK, Content-Type: %s\n\n”,
extensions[i].mediatype);
send_new(fd, “HTTP/1.1 200 OK\r\n”);
send_new(fd, “Server : Web Server in C\r\n\r\n”);
if (ptr == request + 4) // if it is a GET request
{
if ((length = get_file_size(fd1)) == -1)
printf(“Error in getting size !\n”);
size_t total_bytes_sent = 0;
ssize_t bytes_sent;
while (total_bytes_sent < length) {
//Zero copy optimization
if ((bytes_sent = sendfile(fd, fd1, 0,
length – total_bytes_sent)) <= 0) {
if (errno == EINTR || errno == EAGAIN) {
continue;
}
perror(“sendfile”);
return -1;
}
total_bytes_sent += bytes_sent;
}
}
}
break;
}
int size = sizeof(extensions) / sizeof(extensions[0]);
if (i == size – 2) {
printf(“415 Unsupported Media Type\n”);
send_new(fd, “HTTP/1.1 415 Unsupported Media Type\r\n”);
send_new(fd, “Server : Web Server in C\r\n\r\n”);
send_new(fd, “<html><head><title>415 Unsupported Media Type</head></title>”);
send_new(fd, “<body><p>415 Unsupported Media Type!</p></body></html>”);
}
}
close(fd);
}
}
shutdown(fd, SHUT_RDWR);
}
int main(int argc, char *argv[]) {
int sockfd, newsockfd, portno, pid;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2) {
fprintf(stderr, “ERROR, no port provided\n”);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error(“ERROR opening socket”);
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error(“ERROR on binding”);
listen(sockfd, 5);
clilen = sizeof(cli_addr);
/*
Server runs forever, forking off a separate
process for each connection.
*/
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error(“ERROR on accept”);
pid = fork();
if (pid < 0)
error(“ERROR on fork”);
if (pid == 0) {
close(sockfd);
connection(newsockfd);
exit(0);
} else
close(newsockfd);
} /* end of while */
close(sockfd);
return 0; /* we never get here */
}

vim多窗口操作

vim 从 vim7 开始加入了多标签切换的功能, 相当于多窗口. 之前的版本虽然也有多文件编辑功能, 但是总之不如这个方便啦。

用法

:tabnew [++opt选项] [+cmd] 文件 建立对指定文件新的tab

:tabc 关闭当前的tab

:tabo 关闭所有其他的tab

:tabs 查看所有打开的tab

:tabp 前一个

:tabn 后一个

标准模式下: gt , gT 可以直接在tab之间切换。

linux下的抓包工具tcpdump

1. tcpdump -D 获取网络适配器列表,以下是在windows上获取到的结果:
1.\Device\PssdkLoopback (PSSDK Loopback Ethernet Emulation Adapter)
2.\Device\{CF587901-C85F-4FD6-896F-D977DEFE76EC} (Intel(R) PRO/100 VE Network Co
nnection)
2. tcpdump -i <需要监控的网络适配器编号>,例如我想监控lo(127.0.0.1),即上面列表中的1.\Device\PssdkLoopback: (windows上特有的,linux不适用)
tcpdump -i 1
如果不使用-i来定义监控适配器的话,默认使用列表中的第一个;
3. 监控主机为192.9.200.59上8000端口的tcp协议:
tcpdump host 192.9.200.59 and tcp port 8000
4. 如果想要显示数据包的内容,需要使用-X参数,如,我想要显示捕获的http数据包http header的内容:
tcpdump -X host 192.9.200.59 and tcp port 8000
显示结果如下:
22:13:19.717472 IP testhost59.12535 > liujuan59.8000: . 1:330(329) ack 1 win 327
8
0×0000: 4500 0171 e616 0000 8006 cb2b 0000 0000 E..q…….+….
0×0010: c009 c83b 30f7 1f40 0000 0002 0000 0002 …;0..@……..
0×0020: 5010 8000 b066 0000 504f 5354 202f 2048 P….f..POST./.H
0×0030: 5454 502f 312e 310d 0a43 6f6e 7465 6e74 TTP/1.1..Content
0×0040: 2d54 7970 653a 2074 6578 742f 786d 6c3b -Type:.text/xml;
0×0050: 2063 .c
可以看到该结果只显示了http头的一部分,没有显示全,是因为tcpdump默认将显示的数据长度截断了,可以使用-s后面加数据长度,来设置数据显示长度:
tcpdump -X -s 0 host 192.9.200.59 and tcp port 8000
以上的例子中,-s 0 表示自动设置长度使其能够显示所有数据。
5. 捕获的数据太多,不断刷屏,可能需要将数据内容记录到文件里,需要使用-w参数:
tcpdump -X -s 0 -w aaa host 192.9.200.59 and tcp port 8000
则将之前显示在屏幕中的内容,写入tcpdump可执行文件同级目录下的aaa文件中。
文件查看方式如下,需要使用-r参数:
tcpdump -X -s 0 -r aaa host 192.9.200.59 and tcp port 8000
如果这样写:
tcpdump -r aaa
则只能看到最简单的数据传输交互过程,看不到数据包内容,查看时也需要使用相应的参数。
6.总结
总结一下,tcpdump的参数分两个部分,选项(Options)和表达式(expression):
tcpdump[-adeflnNOpqRStuvxX] [-ccount]
[-Cfile_size] [-Ffile]
[-iinterface] [-mmodule] [-rfile]
[-ssnaplen] [-Ttype] [-wfile]
[-Ealgo:secret] [expression]

php服务器监控

1. 取出系统Kernel版本:
$sys_host_name = file(“/proc/sys/kernel/hostname”);
$sys_ostype = file(“/proc/sys/kernel/ostype”);
$sys_osrelease = file(“/proc/sys/kernel/osrelease”);
$sys_version_time = file(“/proc/sys/kernel/version”);

2. 取出CPU信息
$cpu_info = file(“/proc/cpuinfo”);

3. 取出系统内存和交换分区的信息
$memory_info = file(“/proc/meminfo”);
$meminfo = explode(” “, $memory_info[1]);

4. 取出PS进程信息,以推算出CPU和MEM的使用率
exec(“ps -aux”, $ps_info_result);
for ($i = 0; $i < count($ps_info_result); $i++) {
list($user[$i], $pid[$i], $cpu[$i], $mem[$i], $vsz[$i], $rss[$i], $tty[$i], $stat[$i], $start[$i], $time[$i], $command[$i]) = split(” +”, $ps_info_result[$i]);
//取出CPU用的总数(百分比)
$cpu_use_total = $cpu_use_total + $cpu[$i];
//取出MEM用的总数(百分比)
$mem_use_total = $mem_use_total + $mem[$i];
//取出MEM用的总数(KB)
$rss_use_total = $rss_use_total + $rss[$i];
}

vi快捷键

%s/vivian/sky/g(等同于 :g/vivian/s//sky/g) 替换每一行中所有 vivian 为 sky

如果替换的范围较大时,在所有的命令尾加一个c命令,强制每个替换需要用户进行确认,例如:s/old/new/c 或s/old/new/gc

Ctrl+R可以恢复对使用u命令的操作

dw删除当前字符到单词尾包括空格的所有字符

yw复制当前光标所在位置到单词尾字符的内容到vi缓存区,相当于复制一个单词

#yy例如:5yy就是复制5行 也可以写成 y5

以后继续补充。

LevelDB文章介绍

http://www.cnblogs.com/haippy/archive/2011/12/04/2276064.html