0%

项目地址: https://github.com/onecer/Pyrsync

readme: https://uublog.com/article/20170630/pyrsync-readme/

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

打算用rsync同步,刚刚在写shell的时候,尝试了下,项目多了,目录多了。shell代码就眼花缭乱。

所以,这样封装了一下,备份的项目用yaml描述。100行代码,可以更方便的去管理备份源。

项目代码:

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
#!/usr/bin/env python
# coding:utf-8

# Author: phan

import os
import yaml
import commands
import time
import codecs

# 配置区域
# 日志路径
LOGFILE = '/var/log/pyrsync.log'
# 是否开启日志
ENABLE_LOG = True
# 啰嗦模式
VERBOSE_MODE = True

# 自定义常量
BASEDIR = os.path.dirname(__file__)

# 获取目录文件列表
def get_file_lists(dirpath):
filelists = []
for filename in os.listdir(dirpath):
filelists.append(os.path.join(dirpath,filename))
return filelists

# 获取当前时间
def get_time():
return time.strftime('%Y-%m-%d %H:%M:%S ',time.localtime(time.time()))

# 记录日志
def logger(line):
if ENABLE_LOG:
if os.path.isfile(LOGFILE):
with codecs.open(LOGFILE,'a','utf-8') as f:
f.write("{time}{logline}\n".format(time=get_time(), logline=line))
else:
with codecs.open(LOGFILE,'w','utf-8') as f:
f.write("{time}{logline}\n".format(time=get_time(), logline=line))

# 记录命令日志
def logger_commands(status,result):
logger('result:{status}'.format(status=status))
if VERBOSE_MODE:
logger(result)

# 执行命令
def runcommand(commandline):
return commands.getstatusoutput(commandline)

# 部署场景
def deploy_sences(isLocal,shellfile,actor=''):
commandline = os.path.join(BASEDIR, 'script', shellfile)
if isLocal:
(status,result) = runcommand(commandline)
logger_commands(status,result)
else:
upload_script = 'scp {command} {name}@{ip}:/tmp/pyrsync_{scriptName}'.format(
command=commandline,
name=actor['name'],
ip=actor['ip'],
scriptName=os.path.basename(commandline)
)
(status,result) = runcommand(upload_script)
logger_commands(status, result)
commandline = 'ssh {name}@{ip} "chmod u+x /tmp/pyrsync_{command} && /tmp/pyrsync_{command} && rm -f /tmp/pyrsync_{command}"'.format(
name=actor['name'],
ip=actor['ip'],
command=os.path.basename(commandline),
)
(status,result) = runcommand(commandline)
logger_commands(status, result)

# 同步文件
def sync_files(actor,sence):
rsyncCommand = 'rsync {action} --exclude-from="{exclude}" {name}@{ip}:{path} {savepath}'.format(
action=actor['action'],
exclude=os.path.join(BASEDIR,'exclude',sence['exclude']),
name=actor['name'],
ip=actor['ip'],
port=actor['port'],
path=sence['item'],
savepath=sence['savepath']
)
logger('Command:{command}'.format(command=rsyncCommand))
(status,result) = runcommand(rsyncCommand)
logger_commands(status,result)

# 执行剧本
def play_playbooks(filelists):
for filelist in filelists:
if os.path.isfile(filelist) and os.path.splitext(filelist)[-1]=='.yaml':
with open(filelist,'r') as f:
playbook = yaml.load(f)
sences = playbook['playbook']['sences']
for sence in sences:
if playbook['execute']['pre-local']:
deploy_sences(True,playbook['execute']['pre-local'])
if playbook['execute']['pre-remote']:
deploy_sences(False, playbook['execute']['pre-remote'],playbook['actor'])
sync_files(playbook['actor'],sence)
if playbook['execute']['post-remote']:
deploy_sences(False,playbook['execute']['post-remote'],playbook['actor'])
if playbook['execute']['post-local']:
deploy_sences(True,playbook['execute']['post-local'])

if __name__=='__main__':
play_playbooks(get_file_lists(os.path.join(BASEDIR,'playbook')))

配置格式如下:

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
actor:
name: root
ip: 192.168.168.19
port: 22
action: -avz

execute:
pre-local:
pre-remote: test.sh
post-remote:
post-local:

playbook:
sences:
- 1:
item: /data/web1/uploads
savepath: /backup/web1
exclude: cvs.txt
- 2:
item: /data/web2/uploads
savepath: /backup/web2
exclude: cvs.txt
- 3:
item: /data/web3/uploads
savepath: /backup/web3
exclude: cvs.txt
- 4:
item: /data/sql
savepath: /backup/sql
exclude: cvs.txt

安装

Pyrsync

调用rsync同步文件,从yaml文件读取配置。简化rsync使用,和方便管理备份项更改。未来将提供web界面添加yaml配置。

安装依赖

sudo pip install -r requirements.txt

sudo yum install -y rsync

使用说明

  • 新建项目yaml配置文件 cp playbook/default.yaml.template playbook/default.yaml

  • 配置好项目使用哪个账户复制,ip、备份目录之类的。

  • 要提前做好要备份的主机公钥认证,好让rsync不用输入密码。

  • 执行 ./pyrsync.py

最近公司大部分项目从SVN过渡到Git。所以代码自动化部署也有了更多的想象空间。

之前使用SVN更新代码到开发环境的时候,都是用crontab定时svn update。间隔是一分钟,虽然一分钟不算长,甚至有时候等待并不需要这么久。

但是总归是无法做到及时更新。算是自动主动更新,而Git有webhook的存在,就可以做到触发式更新。

我们代码是放在 git.oschina.net 码云上。

原理

每次git提交的时候,都会触发webhook,webhook会访问我们设置的URL。

URL触发我们的更新代码。

所以,我们还需要架一个网站,提供一个webhook访问的URL,访问的时候触发代码。

实践

时间原因,轮子就不自己造了,所以,我找到一份还不错的webhook管理平台。

安装git-webhook

环境: Centos7

这里用docker部署

1
2
3
4
5
6
7
8
9
10
11
12
# 安装启动docker
# yum install docker
# systemctl restart docker
# systemctl enable docker
# 安装 Docker Compose
# yum install docker-compose
# 下载源码
# git clone https://github.com/NetEaseGame/git-webhook.git
# 修改配置
# cd git-webhook
# cp app/config_docker_example.py app/config.py
# vim app/config.py

GITHUB: GitHub 登陆配置,可以到 OAuth applications 自行申请,登陆 Callback 地址为: your_domain/github/callback.

配置好后,就可以执行

1
# docker-compose up

第一次启动的时候会docker会pull几个需要的镜像,所以时间要长点。

以后启动的话,可以用docker-compose up -d 用deamon方式启动。

Nginx配置

启动后,docker 暴露出来的端口是 18340.访问的话,就是 http://ip:18340

所以我打算给它绑定一个域名,让它访问要更方便一点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server {
listen 80;
server_name webhook.xxx.com;

root html;
index index.html index.htm index.php;

location / {
proxy_pass http://127.0.0.1:18340/;

#Proxy Settings
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

至此git-webhook就安装好了。

用github账号登录进去,先添加服务器,再添加git仓库。得到的url填到git.oschina.net webhook那里就行了。

  • 添加好项目后,在箭头方向复制URL

复制路径

  • 登录码云,填写URL到webhook那里

填写URL

参考资料

GIT可以选择有很多,国外有github,国内有coding和git.oschina.net。

因为不可描述的原因,我们选了国内的。注册和管理其实和github很像。

我再做了ssh公钥认证后,将远程仓库git clone一份回本地。这样它就会自动生成一个.git目录了。

其实自己在本地现有的项目下用git remote add 也是可以的,但是感觉要略为麻烦点。

将SVN仓库代码更新至最新,复制多一份。

进入SVN代码目录,删除原来SVN的隐藏目录,.svn,这个内容占了很大空间。

1
find . -type d -name ".svn"|xargs rm -rf

将内容复制的到git目录,并提交去远程仓库。

1
2
3
git add -A
git commit -m "first commit"
git push origin master

done.

归类到工具吧,算是可以提升效率的东西。自己也折腾过,VIM配置插件还是挺麻烦的。直到看到这个,一键配置,这个项目再github居然有3K的star。

https://github.com/wklken/k-vim

安装方法不赘述,帮助文档有。

用来写Python和其它脚步,做些小修改,算是一个好的补充吧。毕竟大部分时候还是专业的IDE比较方便。

本机装了MariaDB,很久不用,把密码给忘记了。

然后刚刚把密码恢复了下,记录一份这里方便以后索引。

  1. 停止MySQL服务。

# systemctl stop mysql 我是Ubuntu 这里服务名是这个

  1. 用无权限管理方式启动

# mysqld_safe --skip-grant-tables &

  1. 登录修改密码

# mysql -uroot

修改密码的SQL

1
2
3
4
> use mysql;
> update user set password=PASSWORD("gjdEdufD93J") where User='root';
> flush privileges;
> quit
  1. 停止mysql进程

/etc/init.d/mysql stop

  1. 启动服务 systemctl restart mysql

done.

全部流程记录

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
fate phan # systemctl stop mysql
fate phan # mysqld_safe --skip-grant-tables &
[1] 14391
fate phan # 170527 11:46:39 mysqld_safe Logging to syslog.
170527 11:46:39 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

fate phan # mysql -uroot
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.0.29-MariaDB-0ubuntu0.16.04.1 Ubuntu 16.04

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> update user set password=PASSWORD("gjdEdufD93J") where User='root';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

MariaDB [mysql]> quit
Bye
fate phan # /etc/init.d/mysql stop
[ ok ] Stopping mysql (via systemctl): mysql.service.
fate phan # systemctl restart mysql

参考资料

写了一个脚本用fabric发布和运行java包。需要用到nohup,或者screen -d -m命令。

我习惯了nohup,但是执行完毕,没有出错,但是程序也压根没有执行。

最后才找到资料说是fabric执行nohup命令的时候,过早关闭session,导致出问题。

官方推荐的做法是在命令后面增加一点延迟,比如&& sheep 1或者用screen命令。

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
#!/usr/bin/env python
#coding:utf-8

from random import randint

"""
词的频次统计
统计重复的词的次数,用字典的形式展现
"""

data = [randint(0,10) for _ in xrange(0,20)]

print data

## 常规处理
# 根据键生成一个字典,赋值0
ddata = dict.fromkeys(data,0)

print ddata
# 迭代统计
for x in data:
ddata[x]+=1

print ddata

## 用collections 的counter

from collections import Counter

ddata2 = Counter(data)

# 统计最高的4位
print ddata2.most_common(4)

输出:

1
2
3
4
5
[1, 0, 5, 6, 6, 4, 8, 7, 3, 1, 2, 10, 9, 5, 9, 3, 10, 9, 5, 4]
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0}
{0: 1, 1: 2, 2: 1, 3: 2, 4: 2, 5: 3, 6: 2, 7: 1, 8: 1, 9: 3, 10: 2}
[(5, 3), (9, 3), (1, 2), (3, 2)]

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
#!/usr/bin/env python
#coding:utf-8

from random import randint

"""
列表筛选
生成一个有20个随机数的数组 data
从 data 列表中筛选出大于0的数字
"""

data = [randint(-100,100) for _ in xrange(10)]

print data

## 迭代
def test1(d):
s = []
for x in data:
if x >=0:
s.append(x)
return s

## 用filter
def test2(d):
return filter(lambda x:x>=0,d)

## 用列表解析
def test3(d):
return [x for x in data if x>=0]

print test1(data)
print test2(data)
print test3(data)

## 迭代最慢、列表解析最快

"""
字典的筛选
生成键值在56-100之间的随机数10个
找出大于90的数
"""

data = {x:randint(56,100) for x in xrange(1,11)}
print data

def test4(d):
return {k:v for k,v in d.iteritems() if v>=90}

print test4(data)

输出:

1
2
3
4
5
6
7
[61, -31, 2, -45, -1, 19, -41, -8, -17, 48]
[61, 2, 19, 48]
[61, 2, 19, 48]
[61, 2, 19, 48]
{1: 59, 2: 99, 3: 97, 4: 83, 5: 89, 6: 79, 7: 69, 8: 58, 9: 73, 10: 58}
{2: 99, 3: 97}

公司有块业务是靠socket提供端口供给业务查询的。

之前每次测试socket发送数据都略麻烦,所以自己用python搞了一次。

根据业务之前的逻辑,检测字段包含EOF结束读取。

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
import socket
#import codecs

#encoder = codecs.getencoder("utf-8")
senddata = '{"action":"compute","device":"ios","map":"0","start":"2017-05-19","day":"25","type":"17","orientation":"0","order_total_id":"950","store_id":"12"}EOF\n'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('dev.xxxx.net', 31))
s.send(senddata)

buffer = []
while True:
d = s.recv(65535)
if d:
buffer.append(d)
else:
break
if 'EOF' in d[-5:-1]:
break
# while True:
# d = s.recv(1024)
# if d:
# buffer.append(d)
# else:
# break
data = ''.join(buffer)
print data
s.close()

Python实现求第N位斐波那契数。迭代用来队列来保存,用其它也是可以的。

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
#!/bin/env python
#coding:utf-8
from collections import deque
import datetime

# 递归版
def fibonacci(num):
if num<=2:
return 1
else:
return fibonacci(num-1)+fibonacci(num-2)

# 迭代版
def fibonacci2(num):
s=deque()
result=0
for i in range(1,num+1):
if i<=2:
result=1
s.append(result)
else:
result=s[0]+s[1]
s.append(result)
s.popleft()
return result


n=40
print(datetime.datetime.now())
print('fibonacci(%d)=%d' % (n, fibonacci(n)))
print(datetime.datetime.now())
print('fibonacci2(%d)=%d' % (n, fibonacci2(n)))
print(datetime.datetime.now())

结果:

1
2
3
4
5
2017-05-19 18:00:52.194334
fibonacci(40)=102334155
2017-05-19 18:01:09.535270
fibonacci2(40)=102334155
2017-05-19 18:01:09.535328

递归效率还是比较底下,但是语法简明。