pyinotify结合ftplib自动上传新建的文件
生活随笔
收集整理的這篇文章主要介紹了
pyinotify结合ftplib自动上传新建的文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
應用場景:從國內往國外上傳,因國際帶寬影響,速度很慢,于是做了一個中轉FTP,而自動上傳需求也就誕生了。
代碼地址:https://github.com/coocla/linux/blob/master/ftp/autoupload_ftp.py??
sftp類型:https://github.com/coocla/linux/blob/master/sftp/autoupload_sftp.py
直接貼腳本:
#!/usr/bin/env?python #?-*-?coding:utf-8?-*- #?This?is?a?new?file?will?be?automatically?uploaded?to?the?ftp?python?script. #?Author:?http://blog.coocla.orgimport?pyinotify import?os from?ftplib?import?FTPWATCHDIR="/tmp/" HOST="xxxxx" USER="xxxxx" PASS="xxxxx" pid_file="/tmp/monitor_upload.pid" log_file="/tmp/monitor_upload.log"class?OnCreateClick(pyinotify.ProcessEvent):def?process_IN_CREATE(self,?event):abspath=os.path.join(event.path,?event.name)if?os.path.isdir(abspath):print?"create?directory:??%s"?%?event.nameelif?os.path.isfile(abspath):print?"create?file:??%s"?%?event.namerelname=abspath.split(WATCHDIR)[1]relpath=os.path.dirname(relname)upload(abspath,?relpath,?event.name)def?main():wm?=?pyinotify.WatchManager()notifier?=?pyinotify.Notifier(wm,?OnCreateClick())wm.add_watch(WATCHDIR,?pyinotify.IN_CREATE,?rec=True,?auto_add=True)notifier.loop(daemonize=True,?pid_file=pid_file,?stdout=log_file)def?upload(abspath,?relpath,?filename):ftp?=?FTP()ftp.connect(HOST)ftp.login(USER,?PASS)bufsize?=?1024ftp.cwd("xxxxxxx")try:ftp.cwd(relpath)except:for?remote_path?in?relpath.split(os.path.sep):ftp.mkd(remote_path)ftp.cwd(remote_path)filehandler?=?open(abspath,?"rb")try:ftp.storbinary("STOR?"?+?filename,?filehandler,?bufsize)print?"Upload?file?%s?success."?%?abspathexcept:print?"Upload?file?%s?error."?%?abspathfilehandler.close()ftp.quit()if?__name__?==?'__main__':if?os.path.isfile(pid_file):os.remove(pid_file)main()轉載于:https://blog.51cto.com/siliotto/1598148
總結
以上是生活随笔為你收集整理的pyinotify结合ftplib自动上传新建的文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到去医院检查是否怀孕
- 下一篇: 2015 CALLED THE INTE