PHP Python FTP Operation class
- Class FTP {
- FTP Connection Resources
- Private $link;
- FTP Connection time
- Public $link _time;
- Error code
- Private $err _code = 0;
- Transfer Mode {text mode: FTP_ASCII, Binary mode: Ftp_binary}
- Public $mode = ftp_binary;
- /**
- Initialize class
- **/
- Public function Start ($data)
- {
- if (Empty ($data [' Port ']) $data [' port '] = ' 21 ';
- if (Empty ($data [' PASV '])) $data [' PASV '] =false;
- if (Empty ($data [' SSL '])) $data [' SSL '] = false;
- if (Empty ($data [' timeout ']) $data [' timeout '] = 30;
- return $this->connect ($data [' Server '], $data [' username '], $data [' Password '], $data [' Port '], $data [' PASV '], $data [ ' SSL ', $data [' timeout '];
- }
- /**
- * Connect to FTP server
- * @param string $host server address
- * @param string $username user name
- * @param string $password password
- * @param integer $port server port with a default value of 21
- * @param Boolean $PASV whether to turn on passive mode
- * @param boolean $ssl whether to use SSL connection
- * @param integer $timeout time-out
- */
- Public function Connect ($host, $username = ', $password = ', $port = ' + ', $PASV = False, $ssl = False, $timeout = 30) {
- $start = time ();
- if ($SSL) {
- if (! $this->link = @ftp_ssl_connect ($host, $port, $timeout)) {
- $this->err_code = 1;
- return false;
- }
- } else {
- if (! $this->link = @ftp_connect ($host, $port, $timeout)) {
- $this->err_code = 1;
- return false;
- }
- }
- if (@ftp_login ($this->link, $username, $password)) {
- if ($PASV)
- FTP_PASV ($this->link, true);
- $this->link_time = time ()-$start;
- return true;
- } else {
- $this->err_code = 1;
- return false;
- }
- Register_shutdown_function (Array (& $this, ' close ');
- }
- /**
- * Create Folder
- * @param string $dirname directory name,
- */
- Public function mkdir ($dirname) {
- if (! $this->link) {
- $this->err_code = 2;
- return false;
- }
- $dirname = $this->ck_dirname ($dirname);
- $nowdir = '/';
- foreach ($dirname as $v) {
- if ($v &&! $this->chdir ($nowdir. $v)) {
- if ($nowdir)
- $this->chdir ($nowdir);
- @ftp_mkdir ($this->link, $v);
- }
- if ($v)
- $nowdir. = $v. '/';
- }
- return true;
- }
- /**
- * Upload Files
- * @param string $remote Remote Storage address
- * @param string $local Local storage address
- */
- Public function put ($remote, $local) {
- if (! $this->link) {
- $this->err_code = 2;
- return false;
- }
- $dirname = PathInfo ($remote, pathinfo_dirname);
- if (! $this->chdir ($dirname)) {
- $this->mkdir ($dirname);
- }
- if (@ftp_put ($this->link, $remote, $local, $this->mode)) {
- return true;
- } else {
- $this->err_code = 7;
- return false;
- }
- }
- /**
- * Delete Folder
- * @param string $dirname directory Address
- * @param boolean $enforce Force delete
- */
- Public function RmDir ($dirname, $enforce = False) {
- if (! $this->link) {
- $this->err_code = 2;
- return false;
- }
- $list = $this->nlist ($dirname);
- if ($list && $enforce) {
- $this->chdir ($dirname);
- foreach ($list as $v) {
- $this->f_delete ($v);
- }
- } elseif ($list &&! $enforce) {
- $this->err_code = 3;
- return false;
- }
- @ftp_rmdir ($this->link, $dirname);
- return true;
- }
- /**
- * Delete the specified file
- * @param string $filename file name
- */
- Public Function Delete ($filename) {
- if (! $this->link) {
- $this->err_code = 2;
- return false;
- }
- if (@ftp_delete ($this->link, $filename)) {
- return true;
- } else {
- $this->err_code = 4;
- return false;
- }
- }
- /**
- * Returns a list of files for a given directory
- * @param string $dirname directory Address
- * @return Array file list data
- */
- Public Function Nlist ($dirname) {
- if (! $this->link) {
- $this->err_code = 2;
- return false;
- }
- if ($list = @ftp_nlist ($this->link, $dirname)) {
- return $list;
- } else {
- $this->err_code = 5;
- return false;
- }
- }
- /**
- * Change the current directory on the FTP server
- * @param string $dirname Modify the current directory on the server
- */
- Public Function ChDir ($dirname) {
- if (! $this->link) {
- $this->err_code = 2;
- return false;
- }
- if (@ftp_chdir ($this->link, $dirname)) {
- return true;
- } else {
- $this->err_code = 6;
- return false;
- }
- }
- /**
- * Get error messages
- */
- Public Function Get_error () {
- if (! $this->err_code)
- return false;
- $err _msg = Array (
- ' 1 ' = ' Server can not connect ',
- ' 2 ' = ' Not connect to server ',
- ' 3 ' = ' Can not delete non-empty folder ',
- ' 4 ' = ' Can not delete file ',
- ' 5 ' = ' Can not get file list ',
- ' 6 ' + ' Can not change the current directory on the server ',
- ' 7 ' = ' Can not upload files '
- );
- return $err _msg[$this->err_code];
- }
- /**
- * Detection Directory Name
- * @param string $url directory
- * @return The returned array by/separate
- */
- Private Function Ck_dirname ($url) {
- $url = Str_replace (', '/', $url);
- $urls = explode ('/', $url);
- return $urls;
- }
- /**
- * Close FTP connection
- */
- Public function Close () {
- Return @ftp_close ($this->link);
- }
- }
Copy Code
- #!/usr/bin/python
- #coding =GBK
- '''
- FTP automatic download, automatic upload script, can be recursive directory operation
- '''
- From Ftplib import FTP
- Import Os,sys,string,datetime,time
- Import socket
- Class Myftp:
- def __init__ (self, hostaddr, username, password, remotedir, port=21):
- SELF.HOSTADDR = hostaddr
- Self.username = Username
- Self.password = password
- Self.remotedir = Remotedir
- Self.port = Port
- SELF.FTP = FTP ()
- Self.file_list = []
- # Self.ftp.set_debuglevel (2)
- def __del__ (self):
- Self.ftp.close ()
- # self.ftp.set_debuglevel (0)
- def login (self):
- FTP = self.ftp
- Try
- Timeout = 60
- Socket.setdefaulttimeout (Timeout)
- FTP.SET_PASV (True)
- print ' Start connection to%s '% (SELF.HOSTADDR)
- Ftp.connect (SELF.HOSTADDR, Self.port)
- print ' Successfully connected to%s '% (SELF.HOSTADDR)
- print ' Start login to%s '% (SELF.HOSTADDR)
- Ftp.login (Self.username, Self.password)
- print ' successfully logged on to%s '% (SELF.HOSTADDR)
- Debug_print (Ftp.getwelcome ())
- Except Exception:
- Deal_error ("Connection or Login failed")
- Try
- FTP.CWD (Self.remotedir)
- Except (Exception):
- Deal_error (' failed to switch directory ')
- def is_same_size (self, LocalFile, remotefile):
- Try
- Remotefile_size = Self.ftp.size (remotefile)
- Except
- Remotefile_size =-1
- Try
- Localfile_size = Os.path.getsize (LocalFile)
- Except
- Localfile_size =-1
- Debug_print (' lo:%d re:%d '% (localfile_size, remotefile_size),)
- if remotefile_size = = Localfile_size:
- Return 1
- Else
- return 0
- def download_file (self, LocalFile, remotefile):
- If Self.is_same_size (LocalFile, RemoteFile):
- Debug_print ('%s ' file is the same size without downloading '%localfile ')
- Return
- Else
- Debug_print (' >>>>>>>>>>>> download file%s ... '%localfile)
- #return
- File_handler = open (LocalFile, ' WB ')
- Self.ftp.retrbinary (' RETR%s '% (remotefile), File_handler.write)
- File_handler.close ()
- def download_files (self, localdir= './', remotedir= './'):
- Try
- SELF.FTP.CWD (Remotedir)
- Except
- Debug_print (' directory%s does not exist, continue ... '%remotedir)
- Return
- If not Os.path.isdir (Localdir):
- Os.makedirs (Localdir)
- Debug_print (' Switch to directory%s '%self.ftp.pwd ())
- Self.file_list = []
- Self.ftp.dir (Self.get_file_list)
- Remotenames = Self.file_list
- #print (Remotenames)
- #return
- For item in Remotenames:
- filetype = item[0]
- filename = item[1]
- Local = Os.path.join (localdir, filename)
- if filetype = = ' d ':
- Self.download_files (local, filename)
- elif filetype = = '-':
- Self.download_file (local, filename)
- SELF.FTP.CWD ('.. ')
- Debug_print (' Return to upper directory%s '%self.ftp.pwd ())
- def upload_file (self, LocalFile, remotefile):
- If not Os.path.isfile (LocalFile):
- Return
- If Self.is_same_size (LocalFile, RemoteFile):
- Debug_print (' Skip [equal]:%s '%localfile)
- Return
- File_handler = open (LocalFile, ' RB ')
- Self.ftp.storbinary (' STOR%s '%remotefile, File_handler)
- File_handler.close ()
- Debug_print (' Delivered:%s '%localfile)
- def upload_files (self, localdir= './', Remotedir = './'):
- If not Os.path.isdir (Localdir):
- Return
- Localnames = Os.listdir (Localdir)
- SELF.FTP.CWD (Remotedir)
- For item in Localnames:
- src = os.path.join (localdir, item)
- If Os.path.isdir (SRC):
- Try
- SELF.FTP.MKD (item)
- Except
- Debug_print (' Directory already exists%s '%item)
- Self.upload_files (SRC, item)
- Else
- Self.upload_file (SRC, item)
- SELF.FTP.CWD ('.. ')
- def get_file_list (self, line):
- Ret_arr = []
- File_arr = Self.get_filename (line)
- If file_arr[1] not in ['. ', ' ... ']:
- Self.file_list.append (File_arr)
- def get_filename (self, line):
- pos = Line.rfind (': ')
- while (Line[pos]! = "):
- pos + = 1
- while (line[pos] = = "):
- pos + = 1
- File_arr = [Line[0], Line[pos:]]
- Return File_arr
- def debug_print (s):
- Print (s)
- def deal_error (E):
- TimeNow = Time.localtime ()
- Datenow = Time.strftime ('%y-%m-%d ', TimeNow)
- Logstr = '%s ' Error occurred:%s '% (Datenow, E)
- Debug_print (LOGSTR)
- File.write (LOGSTR)
- Sys.exit ()
- if __name__ = = ' __main__ ':
- File = Open ("Log.txt", "a")
- TimeNow = Time.localtime ()
- Datenow = Time.strftime ('%y-%m-%d ', TimeNow)
- Logstr = Datenow
- # Configure the following variables
- hostaddr = ' localhost ' # FTP address
- Username = ' Test ' # User name
- Password = ' Test ' # password
- Port = 21 # port number
- rootdir_local = '. ' + os.sep + ' bak/' # Local Directory
- Rootdir_remote = './' # remote Directory
- f = myftp (hostaddr, username, password, rootdir_remote, port)
- F.login ()
- F.download_files (rootdir_local, Rootdir_remote)
- TimeNow = Time.localtime ()
- Datenow = Time.strftime ('%y-%m-%d ', TimeNow)
- Logstr + = "-%s successfully performed a backup \ n"%datenow
- Debug_print (LOGSTR)
- File.write (LOGSTR)
- File.close ()
Copy Code |