Python实现简单的文件传输与MySQL备份的脚本分享

yipeiwu_com5年前Python基础

用python实现简单Server/Client文件传输:

服务器端:

#!/usr/bin/python
import SocketServer, time
class MyServer(SocketServer.BaseRequestHandler):
userInfo = {
'leonis' : 'leonis',
'hudeyong' : 'hudeyong',
'mudan' : 'mudan' }
def handle(self):
print 'Connected from', self.client_address
while True:
receivedData = self.request.recv(8192)
if not receivedData:
continue
elif receivedData == 'Hi, server':
self.request.sendall('hi, client')
elif receivedData.startswith('name'):
self.clientName = receivedData.split(':')[-1]
if MyServer.userInfo.has_key(self.clientName):
self.request.sendall('valid')
else:
self.request.sendall('invalid')
elif receivedData.startswith('pwd'):
self.clientPwd = receivedData.split(':')[-1]
if self.clientPwd == MyServer.userInfo[self.clientName]:
self.request.sendall('valid')
time.sleep(5)
sfile = open('down.sh', 'rb')
while True:
data = sfile.read(1024)
if not data:
break
while len(data) > 0:
intSent = self.request.send(data)
data = data[intSent:]
time.sleep(3)
self.request.sendall('EOF')
else:
self.request.sendall('invalid')
elif receivedData == 'bye':
break
self.request.close()
print 'Disconnected from', self.client_address
print
if __name__ == '__main__':
print 'Server is started\nwaiting for connection…\n'
srv = SocketServer.ThreadingTCPServer(('ip', 50000), MyServer)
srv.serve_forever()

客户端:

import socket, time
class MyClient:
def __init__(self):
print 'Prepare for connecting…'
def connect(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('ip', 50000))
sock.sendall('Hi, server')
self.response = sock.recv(8192)
print 'Server:', self.response
self.s = raw_input("Server: Do you want get the 'thinking in python' file?(y/n):")
if self.s == 'y':
while True:
self.name = raw_input('Server: input our name:')
sock.sendall('name:' + self.name.strip())
self.response = sock.recv(8192)
if self.response == 'valid':
break
else:
print 'Server: Invalid username'
while True:
self.pwd = raw_input('Server: input our password:')
sock.sendall('pwd:' + self.pwd.strip())
self.response = sock.recv(8192)
if self.response == 'valid':
print 'please wait…'
f = open('down.sh', 'wb')
while True:
data = sock.recv(1024)
if data == 'EOF':
break
f.write(data)
f.flush()
f.close()
print 'download finished'
break
else:
print 'Server: Invalid password'
sock.sendall('bye')
sock.close()
print 'Disconnected'
if __name__ == '__main__':
client = MyClient()
client.connect()

由于担心服务器数据安全,所以写了这个脚本,结合上面分享的Server/Client 文件互传,可以备份网站数据到本地,安全又可靠

#!/usr/bin/python
# Filename: webbak.py
import os
import time
import tarfile
 
os.chdir('/home/web/') #切换目录
source = 'leonis'
bakdir = '/home/web/leonis/'
# mysql dump
dump = 'mysqldump'
dbuser = 'XXXXXXX'
dbpwd = 'XXXXXXXXXXX'
dbname = 'XXXXXXXX'
sqlfile = '/home/web/leonis/leonis.sql'
sql = "%s -u%s -p%s %s > %s" % (dump,dbuser,dbpwd,dbname,sqlfile)
if os.path.exists(sqlfile): 
  os.remove(sqlfile)
else:
  print 'then will dump sql file'
result = os.popen(sql)
if result:       #
 print ("SQL backup completed!")
else:
 print ("SQL backup failed!")
# gzip 压缩 以当日日期命名
filename = bakdir + time.strftime('%Y%m%d')+'.tar.gz'
tar = tarfile.open(filename,"w:gz")
tar.add(source)
tar.close()

相关文章

对python for 文件指定行读写操作详解

1.os.mknod(“test.txt”) #创建空文件 2.fp = open(“test.txt”,w) #直接打开一个文件,如果文件不存在则创建文件 3.关于open 模式: 详...

Python错误提示:[Errno 24] Too many open files的分析与解决

背景 最近在工作中发现了一个错误,在执行多线程扫描脚本的时候频繁出现下面这个错误 HTTPConnectionPool(host=‘t.tips', port=80): Max re...

Python制作微信好友背景墙教程(附完整代码)

Python制作微信好友背景墙教程(附完整代码)

引言 前段时间,微信朋友圈开始出现了一种晒照片新形式,微信好友墙,即在一张大图片中展示出自己的所有微信好友的头像。 效果如下图,出于隐私考虑,这里作了模糊处理。 是不是很炫,而且这还...

浅析python中的分片与截断序列

序列概念 在分片规则里list、tuple、str(字符串)都可以称为序列,都可以按规则进行切片操作 切片操作 注意切片的下标0代表顺序的第一个元素,-1代表倒序的第一个元素;且切片不...

用不到50行的Python代码构建最小的区块链

用不到50行的Python代码构建最小的区块链

译者注:随着比特币的不断发展,它的底层技术区块链也逐步走进公众视野,引起大众注意。本文用不到50行的Python代码构建最小的数据区块链,简单介绍了区块链去中心化的结构与其实现原理。...