PHP Python FTP Operation class

Source: Internet
Author: User
Tags ftp connection ssl connection
PHP Python FTP Operation class
  1. Class FTP {
  2. FTP Connection Resources
  3. Private $link;
  4. FTP Connection time
  5. Public $link _time;
  6. Error code
  7. Private $err _code = 0;
  8. Transfer Mode {text mode: FTP_ASCII, Binary mode: Ftp_binary}
  9. Public $mode = ftp_binary;
  10. /**
  11. Initialize class
  12. **/
  13. Public function Start ($data)
  14. {
  15. if (Empty ($data [' Port ']) $data [' port '] = ' 21 ';
  16. if (Empty ($data [' PASV '])) $data [' PASV '] =false;
  17. if (Empty ($data [' SSL '])) $data [' SSL '] = false;
  18. if (Empty ($data [' timeout ']) $data [' timeout '] = 30;
  19. return $this->connect ($data [' Server '], $data [' username '], $data [' Password '], $data [' Port '], $data [' PASV '], $data [ ' SSL ', $data [' timeout '];
  20. }
  21. /**
  22. * Connect to FTP server
  23. * @param string $host server address
  24. * @param string $username user name
  25. * @param string $password password
  26. * @param integer $port server port with a default value of 21
  27. * @param Boolean $PASV whether to turn on passive mode
  28. * @param boolean $ssl whether to use SSL connection
  29. * @param integer $timeout time-out
  30. */
  31. Public function Connect ($host, $username = ', $password = ', $port = ' + ', $PASV = False, $ssl = False, $timeout = 30) {
  32. $start = time ();
  33. if ($SSL) {
  34. if (! $this->link = @ftp_ssl_connect ($host, $port, $timeout)) {
  35. $this->err_code = 1;
  36. return false;
  37. }
  38. } else {
  39. if (! $this->link = @ftp_connect ($host, $port, $timeout)) {
  40. $this->err_code = 1;
  41. return false;
  42. }
  43. }
  44. if (@ftp_login ($this->link, $username, $password)) {
  45. if ($PASV)
  46. FTP_PASV ($this->link, true);
  47. $this->link_time = time ()-$start;
  48. return true;
  49. } else {
  50. $this->err_code = 1;
  51. return false;
  52. }
  53. Register_shutdown_function (Array (& $this, ' close ');
  54. }
  55. /**
  56. * Create Folder
  57. * @param string $dirname directory name,
  58. */
  59. Public function mkdir ($dirname) {
  60. if (! $this->link) {
  61. $this->err_code = 2;
  62. return false;
  63. }
  64. $dirname = $this->ck_dirname ($dirname);
  65. $nowdir = '/';
  66. foreach ($dirname as $v) {
  67. if ($v &&! $this->chdir ($nowdir. $v)) {
  68. if ($nowdir)
  69. $this->chdir ($nowdir);
  70. @ftp_mkdir ($this->link, $v);
  71. }
  72. if ($v)
  73. $nowdir. = $v. '/';
  74. }
  75. return true;
  76. }
  77. /**
  78. * Upload Files
  79. * @param string $remote Remote Storage address
  80. * @param string $local Local storage address
  81. */
  82. Public function put ($remote, $local) {
  83. if (! $this->link) {
  84. $this->err_code = 2;
  85. return false;
  86. }
  87. $dirname = PathInfo ($remote, pathinfo_dirname);
  88. if (! $this->chdir ($dirname)) {
  89. $this->mkdir ($dirname);
  90. }
  91. if (@ftp_put ($this->link, $remote, $local, $this->mode)) {
  92. return true;
  93. } else {
  94. $this->err_code = 7;
  95. return false;
  96. }
  97. }
  98. /**
  99. * Delete Folder
  100. * @param string $dirname directory Address
  101. * @param boolean $enforce Force delete
  102. */
  103. Public function RmDir ($dirname, $enforce = False) {
  104. if (! $this->link) {
  105. $this->err_code = 2;
  106. return false;
  107. }
  108. $list = $this->nlist ($dirname);
  109. if ($list && $enforce) {
  110. $this->chdir ($dirname);
  111. foreach ($list as $v) {
  112. $this->f_delete ($v);
  113. }
  114. } elseif ($list &&! $enforce) {
  115. $this->err_code = 3;
  116. return false;
  117. }
  118. @ftp_rmdir ($this->link, $dirname);
  119. return true;
  120. }
  121. /**
  122. * Delete the specified file
  123. * @param string $filename file name
  124. */
  125. Public Function Delete ($filename) {
  126. if (! $this->link) {
  127. $this->err_code = 2;
  128. return false;
  129. }
  130. if (@ftp_delete ($this->link, $filename)) {
  131. return true;
  132. } else {
  133. $this->err_code = 4;
  134. return false;
  135. }
  136. }
  137. /**
  138. * Returns a list of files for a given directory
  139. * @param string $dirname directory Address
  140. * @return Array file list data
  141. */
  142. Public Function Nlist ($dirname) {
  143. if (! $this->link) {
  144. $this->err_code = 2;
  145. return false;
  146. }
  147. if ($list = @ftp_nlist ($this->link, $dirname)) {
  148. return $list;
  149. } else {
  150. $this->err_code = 5;
  151. return false;
  152. }
  153. }
  154. /**
  155. * Change the current directory on the FTP server
  156. * @param string $dirname Modify the current directory on the server
  157. */
  158. Public Function ChDir ($dirname) {
  159. if (! $this->link) {
  160. $this->err_code = 2;
  161. return false;
  162. }
  163. if (@ftp_chdir ($this->link, $dirname)) {
  164. return true;
  165. } else {
  166. $this->err_code = 6;
  167. return false;
  168. }
  169. }
  170. /**
  171. * Get error messages
  172. */
  173. Public Function Get_error () {
  174. if (! $this->err_code)
  175. return false;
  176. $err _msg = Array (
  177. ' 1 ' = ' Server can not connect ',
  178. ' 2 ' = ' Not connect to server ',
  179. ' 3 ' = ' Can not delete non-empty folder ',
  180. ' 4 ' = ' Can not delete file ',
  181. ' 5 ' = ' Can not get file list ',
  182. ' 6 ' + ' Can not change the current directory on the server ',
  183. ' 7 ' = ' Can not upload files '
  184. );
  185. return $err _msg[$this->err_code];
  186. }
  187. /**
  188. * Detection Directory Name
  189. * @param string $url directory
  190. * @return The returned array by/separate
  191. */
  192. Private Function Ck_dirname ($url) {
  193. $url = Str_replace (', '/', $url);
  194. $urls = explode ('/', $url);
  195. return $urls;
  196. }
  197. /**
  198. * Close FTP connection
  199. */
  200. Public function Close () {
  201. Return @ftp_close ($this->link);
  202. }
  203. }
Copy Code
  1. #!/usr/bin/python
  2. #coding =GBK
  3. '''
  4. FTP automatic download, automatic upload script, can be recursive directory operation
  5. '''
  6. From Ftplib import FTP
  7. Import Os,sys,string,datetime,time
  8. Import socket
  9. Class Myftp:
  10. def __init__ (self, hostaddr, username, password, remotedir, port=21):
  11. SELF.HOSTADDR = hostaddr
  12. Self.username = Username
  13. Self.password = password
  14. Self.remotedir = Remotedir
  15. Self.port = Port
  16. SELF.FTP = FTP ()
  17. Self.file_list = []
  18. # Self.ftp.set_debuglevel (2)
  19. def __del__ (self):
  20. Self.ftp.close ()
  21. # self.ftp.set_debuglevel (0)
  22. def login (self):
  23. FTP = self.ftp
  24. Try
  25. Timeout = 60
  26. Socket.setdefaulttimeout (Timeout)
  27. FTP.SET_PASV (True)
  28. print ' Start connection to%s '% (SELF.HOSTADDR)
  29. Ftp.connect (SELF.HOSTADDR, Self.port)
  30. print ' Successfully connected to%s '% (SELF.HOSTADDR)
  31. print ' Start login to%s '% (SELF.HOSTADDR)
  32. Ftp.login (Self.username, Self.password)
  33. print ' successfully logged on to%s '% (SELF.HOSTADDR)
  34. Debug_print (Ftp.getwelcome ())
  35. Except Exception:
  36. Deal_error ("Connection or Login failed")
  37. Try
  38. FTP.CWD (Self.remotedir)
  39. Except (Exception):
  40. Deal_error (' failed to switch directory ')
  41. def is_same_size (self, LocalFile, remotefile):
  42. Try
  43. Remotefile_size = Self.ftp.size (remotefile)
  44. Except
  45. Remotefile_size =-1
  46. Try
  47. Localfile_size = Os.path.getsize (LocalFile)
  48. Except
  49. Localfile_size =-1
  50. Debug_print (' lo:%d re:%d '% (localfile_size, remotefile_size),)
  51. if remotefile_size = = Localfile_size:
  52. Return 1
  53. Else
  54. return 0
  55. def download_file (self, LocalFile, remotefile):
  56. If Self.is_same_size (LocalFile, RemoteFile):
  57. Debug_print ('%s ' file is the same size without downloading '%localfile ')
  58. Return
  59. Else
  60. Debug_print (' >>>>>>>>>>>> download file%s ... '%localfile)
  61. #return
  62. File_handler = open (LocalFile, ' WB ')
  63. Self.ftp.retrbinary (' RETR%s '% (remotefile), File_handler.write)
  64. File_handler.close ()
  65. def download_files (self, localdir= './', remotedir= './'):
  66. Try
  67. SELF.FTP.CWD (Remotedir)
  68. Except
  69. Debug_print (' directory%s does not exist, continue ... '%remotedir)
  70. Return
  71. If not Os.path.isdir (Localdir):
  72. Os.makedirs (Localdir)
  73. Debug_print (' Switch to directory%s '%self.ftp.pwd ())
  74. Self.file_list = []
  75. Self.ftp.dir (Self.get_file_list)
  76. Remotenames = Self.file_list
  77. #print (Remotenames)
  78. #return
  79. For item in Remotenames:
  80. filetype = item[0]
  81. filename = item[1]
  82. Local = Os.path.join (localdir, filename)
  83. if filetype = = ' d ':
  84. Self.download_files (local, filename)
  85. elif filetype = = '-':
  86. Self.download_file (local, filename)
  87. SELF.FTP.CWD ('.. ')
  88. Debug_print (' Return to upper directory%s '%self.ftp.pwd ())
  89. def upload_file (self, LocalFile, remotefile):
  90. If not Os.path.isfile (LocalFile):
  91. Return
  92. If Self.is_same_size (LocalFile, RemoteFile):
  93. Debug_print (' Skip [equal]:%s '%localfile)
  94. Return
  95. File_handler = open (LocalFile, ' RB ')
  96. Self.ftp.storbinary (' STOR%s '%remotefile, File_handler)
  97. File_handler.close ()
  98. Debug_print (' Delivered:%s '%localfile)
  99. def upload_files (self, localdir= './', Remotedir = './'):
  100. If not Os.path.isdir (Localdir):
  101. Return
  102. Localnames = Os.listdir (Localdir)
  103. SELF.FTP.CWD (Remotedir)
  104. For item in Localnames:
  105. src = os.path.join (localdir, item)
  106. If Os.path.isdir (SRC):
  107. Try
  108. SELF.FTP.MKD (item)
  109. Except
  110. Debug_print (' Directory already exists%s '%item)
  111. Self.upload_files (SRC, item)
  112. Else
  113. Self.upload_file (SRC, item)
  114. SELF.FTP.CWD ('.. ')
  115. def get_file_list (self, line):
  116. Ret_arr = []
  117. File_arr = Self.get_filename (line)
  118. If file_arr[1] not in ['. ', ' ... ']:
  119. Self.file_list.append (File_arr)
  120. def get_filename (self, line):
  121. pos = Line.rfind (': ')
  122. while (Line[pos]! = "):
  123. pos + = 1
  124. while (line[pos] = = "):
  125. pos + = 1
  126. File_arr = [Line[0], Line[pos:]]
  127. Return File_arr
  128. def debug_print (s):
  129. Print (s)
  130. def deal_error (E):
  131. TimeNow = Time.localtime ()
  132. Datenow = Time.strftime ('%y-%m-%d ', TimeNow)
  133. Logstr = '%s ' Error occurred:%s '% (Datenow, E)
  134. Debug_print (LOGSTR)
  135. File.write (LOGSTR)
  136. Sys.exit ()
  137. if __name__ = = ' __main__ ':
  138. File = Open ("Log.txt", "a")
  139. TimeNow = Time.localtime ()
  140. Datenow = Time.strftime ('%y-%m-%d ', TimeNow)
  141. Logstr = Datenow
  142. # Configure the following variables
  143. hostaddr = ' localhost ' # FTP address
  144. Username = ' Test ' # User name
  145. Password = ' Test ' # password
  146. Port = 21 # port number
  147. rootdir_local = '. ' + os.sep + ' bak/' # Local Directory
  148. Rootdir_remote = './' # remote Directory
  149. f = myftp (hostaddr, username, password, rootdir_remote, port)
  150. F.login ()
  151. F.download_files (rootdir_local, Rootdir_remote)
  152. TimeNow = Time.localtime ()
  153. Datenow = Time.strftime ('%y-%m-%d ', TimeNow)
  154. Logstr + = "-%s successfully performed a backup \ n"%datenow
  155. Debug_print (LOGSTR)
  156. File.write (LOGSTR)
  157. File.close ()
Copy Code
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.