Python implements simple FTP client using ftplib

Source: Internet
Author: User

Python implements simple FTP client using ftplib

This example describes how to use ftplib to implement a simple FTP client in Python. Share it with you for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

#! /Usr/bin/python

#-*-Coding: UTF-8 -*-

From ftplib import FTP # load the ftp Module

Ftp = FTP () # Set Variables

Ftp. set_debuglevel (2) # enable debug level 2 and display details

Ftp. connect ("IP", "port") # connect to the ftp server and port

Ftp. login ("user", "password") # connection username and password

Print ftp. getwelcome () # print the welcome information

Ftp. cmd ("xxx/xxx") # change the remote directory

Bufsize = 1024 # Set the buffer size

Filename = "filename.txt" # files to be downloaded

File_handle = open (filename, "wb"). write

# Open a file locally in write mode

Ftp. retrbinaly ("RETR filename.txt", file_handle, bufsize)

# Receiving files from the server and writing them to a local file

Ftp. set_debuglevel (0) # disable debugging mode

Ftp. quit # exit ftp

Ftp. dir () # display file information in the directory

Ftp. mkd (pathname) # create a remote directory

Ftp. pwd () # Return the current location

Ftp. rmd (dirname) # delete a remote directory

Ftp. delete (filename) # delete a Remote File

Ftp. rename (fromname, toname) # Change fromname to toname.

Ftp. storbinaly ("STOR filename.txt", file_handel, bufsize) # upload the target file

A complete FTP instance:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

# Coding: UTF-8

From ctypes import *

Import OS

Import sys

Import ftplib

Class myFtp:

Ftp = ftplib. FTP ()

BIsDir = False

Path = ""

Def _ init _ (self, host, port = '21 '):

Self. ftp. set_debuglevel (2) # enable debug level 2 and display details

# Self. ftp. set_pasv (0) #0 Active Mode 1 # Passive Mode

Self. ftp. connect (host, port)

Def Login (self, user, passwd ):

Self. ftp. login (user, passwd)

Print self. ftp. welcome

Def DownLoadFile (self, LocalFile, RemoteFile ):

File_handler = open (LocalFile, 'wb ')

Self. ftp. retrbinary ("RETR % s" % (RemoteFile), file_handler.write)

File_handler.close ()

Return True

Def UpLoadFile (self, LocalFile, RemoteFile ):

If OS. path. isfile (LocalFile) = False:

Return False

File_handler = open (LocalFile, "rb ")

Self. ftp. storbinary ('stor % s' % RemoteFile, file_handler, 4096)

File_handler.close ()

Return True

Def UpLoadFileTree (self, LocalDir, RemoteDir ):

If OS. path. isdir (LocalDir) = False:

Return False

LocalNames = OS. listdir (LocalDir)

Print RemoteDir

Self. ftp. cwd (RemoteDir)

For Local in LocalNames:

Src = OS. path. join (LocalDir, Local)

If OS. path. isdir (src ):

Self. UpLoadFileTree (src, Local)

Else:

Self. UpLoadFile (src, Local)

Self. ftp. cwd ("..")

Return

Def DownLoadFileTree (self, LocalDir, RemoteDir ):

If OS. path. isdir (LocalDir) = False:

OS. makedirs (LocalDir)

Self. ftp. cwd (RemoteDir)

RemoteNames = self. ftp. nlst ()

For file in RemoteNames:

Local = OS. path. join (LocalDir, file)

If self. isDir (file ):

Self. DownLoadFileTree (Local, file)

Else:

Self. DownLoadFile (Local, file)

Self. ftp. cwd ("..")

Return

Def show (self, list ):

Result = list. lower (). split ("")

If self. path in result and "<dir>" in result:

Self. bIsDir = True

Def isDir (self, path ):

Self. bIsDir = False

Self. path = path

# This ues callback function, that will change bIsDir value

Self. ftp. retrlines ('LIST', self. show)

Return self. bIsDir

Def close (self ):

Self. ftp. quit ()

Ftp = myFtp ('********')

Ftp. Login ('*****','*****')

# Ftp. DownLoadFile ('test. TXT ', 'oss \ runtime. log') # OK

# Ftp. UpLoadFile ('runtime. log', 'oss \ runtime. log') # OK

# Ftp. DownLoadFileTree ('bcd', 'oss \ abc') # OK

# Ftp. UpLoadFileTree ('aaa', "others \\")

Ftp. close ()

Print "OK! "

I hope this article will help you with Python programming.

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.