Python實現簡單的檔案傳輸與MySQL備份的指令碼分享

來源:互聯網
上載者:User
用python實現簡單Server/Client檔案傳輸:

伺服器端:

#!/usr/bin/pythonimport SocketServer, timeclass MyServer(SocketServer.BaseRequestHandler):userInfo = {'leonis' : 'leonis','hudeyong' : 'hudeyong','mudan' : 'mudan' }def handle(self):print 'Connected from', self.client_addresswhile True:receivedData = self.request.recv(8192)if not receivedData:continueelif 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:breakwhile 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':breakself.request.close()print 'Disconnected from', self.client_addressprintif __name__ == '__main__':print 'Server is started\nwaiting for connection…\n'srv = SocketServer.ThreadingTCPServer(('ip', 50000), MyServer)srv.serve_forever()

用戶端:

import socket, timeclass 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.responseself.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':breakelse: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':breakf.write(data)f.flush()f.close()print 'download finished'breakelse: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.pyimport osimport timeimport tarfile os.chdir('/home/web/') #切換目錄source = 'leonis'bakdir = '/home/web/leonis/'# mysql dumpdump = '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()
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.