Home Backend Development PHP Tutorial php python ftp operation class

php python ftp operation class

Jul 25, 2016 am 08:51 AM

php python ftp operation class
  1. class Ftp {
  2. //FTP connection resource
  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. Initialization 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 Username
  25. * @param string $password Password
  26. * @param integer $port Server port, the default value is 21
  27. * @param boolean $pasv Whether to enable passive mode
  28. * @param boolean $ssl   Whether to use SSL connection
  29. * @param integer $timeout Timeout time
  30. */
  31. public function connect($host, $username = '', $password = '', $port = '21', $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 deletion
  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. * Return the file list of the 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 message
  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. * Detect directory name
  189. * @param string $url directory
  190. * @return Return array separated by /
  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. }
复制代码
  1. #!/usr/bin/python
  2. #coding=gbk
  3. '''
  4. ftp automatic download, automatic upload script, recursive directory operation possible
  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 Connect to %s' %(self.hostaddr)
  29. ftp.connect(self.hostaddr, self.port)
  30. print 'Successfully connected to %s' %(self.hostaddr)
  31. print 'Start logging in to %s' %( self.hostaddr)
  32. ftp.login(self.username, self.password)
  33. print 'Successfully logged in to %s' %(self.hostaddr)
  34. debug_print(ftp.getwelcome())
  35. except Exception:
  36. deal_error("Connect Or login failed")
  37. try:
  38. ftp.cwd(self.remotedir)
  39. except(Exception):
  40. deal_error('Failed to switch directories')
  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 files are the same size, no need to download' %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('Transmitted: %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 An 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' # Username
  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 executed backup n " %datenow
  155. debug_print(logstr)
  156. file.write(logstr)
  157. file.close()
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

See all articles