Dave Python exercise 19-network client Programming

Source: Internet
Author: User
Tags ftp connection imap nntp remote ftp server rfc file transfer protocol mail exchange rsync

# Encoding = UTF-8 </P> <p >#### ****************** network client programming ****** * ************ </P> <p> # This article describes three Internet protocols-FTP, NNTP and POP3, and write their client programs. </P> <p> # *************** Part 1: * <br/> #1.1 file transmission Internet Protocol <br/> # The most popular thing on the Internet is file exchange. File exchange is everywhere. There are many protocols available for Internet transmission <br/> # file use. Most popular are File Transfer Protocol (FTP), Unix-to-Unix CoPy protocol (uucp), and Hypertext Transfer of web pages <br/> # protocol (HTTP ). In addition, there are (UNIX) remote file copy commands RCP (and more secure, more flexible SCP and rsync ). <Br/> # so far, HTTP, FTP, and SCP/rsync are still very popular. HTTP is mainly used to download webpage files and access the Web <br/> # service. Generally, you are not required to enter the user name and password to access files and services on the server. Http File Transfer <br/> # A request is mainly used to obtain a webpage (File Download ). <Br/> # In contrast, SCP and rsync require you to log on to the server. Otherwise, you cannot upload or download files. For FTP, like SCP/rsync <br/> #, files can be uploaded or downloaded, and the concept of UNIX multi-user is also adopted, you must enter a valid user name and password <br/>. However, FTP allows anonymous logon. </P> <p >## 1.2 File Transfer Protocol (FTP) <br/> # the file transfer protocol was developed by the late Jon Postel and Joyce Renault, it is recorded in RFC 959 (Request for <br/> # comment) and published on July 15, October 1985. It is mainly used to download public files anonymously. It can also be used to transfer files between two <br/> # computers, especially when using UNIX systems as file storage systems and other machines. Early <br/> # before the Internet became popular, FTP was one of the main methods for file transfer, software and source code download over the Internet. <Br/> # ftp requires that you enter the user name and password to access the remote FTP server, however, it also allows users without accounts to log on as anonymous users <br/>. However, the Administrator must first set the FTP server to allow anonymous users to log on. In this case, the anonymous user name is "anonymous". <br/> # The password is generally the user's e-mail address. Unlike a user who owns a specific account, it seems that FTP is exposed for <br/> # access. Commands that anonymous users can use over FTP are more restrictive than normal users. </P> <p> # generally, the connection is closed after the client is not active for more than 15 minutes (900 seconds. <Br/> # At the underlying layer, ftp only uses TCP. In addition, FTP is an example of "distinctive" in Client/Server programming. <Br/> # both the client and server use two sockets for communication: one is control and command port (port 21), and the other is data port (sometimes Port 20 ). </P> <p> # "sometimes" is because FTP has two modes: active and passive. The data port is used only on servers in active mode. <Br/> # After the server sets Port 20 as the data port, it "actively" connects to the data port of the client. In passive mode, the server <br/> # Only informs the client of its random port number. The client must establish a data connection. In this mode, you will see that <br/> # the FTP server is "passive" when establishing a data connection. Finally, an extended passive mode is available to support Internet Protocol (IPv6) addresses of version 6th <br/>. </P> <p >## 1.3 Python and FTP </P> <p> # import the ftplib module and instantiate an ftplib module when Python FTP is supported. FTP objects. <Br/> # This object is used for all FTP operations (such as logon, transfer file, and logout. Python pseudocode: <br/> # From ftplib import FTP <br/> # F = FTP ('ftp .python.org ') <br/> # F. login ('anonus us', 'Guess @ who.org ') <br/>#: <br/> # F. quit () </P> <p >## 1.4 </P> <p >## 1.4 ftplib. FTP method <br/> # ftp object method <br/> # method description <br/> # login (user = 'anonus us', passwd = '', acct = '') log on to the FTP server. All parameters are optional <br/> # PWD () to get the current working directory <br/> # CWD (PATH) set the current working directory to path <br/> # Dir ([path [,... [, CB]) displays the content in the path directory. The optional parameter CB is a callback function, which is Pass to retrlines () method <br/> # NLST ([path [,...]) similar to Dir (), but returns a list of file names instead of displaying these names <br/> # retrlines (CMD [, CB]) the given FTP command (such as "retr FILENAME") is used to download text files. The optional callback function CB is used to process each row of a file. <br/> # retrbinary (CMD, CB [, BS = 8192 [, Ra]) is similar to retrlines, this command only processes binary files. The callback function CB is used to process data downloaded from each block (the default block size is 8 KB. <Br/> # storlines (CMD, f) specifies the FTP command (for example, "stor FILENAME") and transmits the text file above. To specify a file object F <br/> # storbinary (CMD, F [, BS = 8192]), it is similar to storlines (), but this command is used to process binary files. To specify a file object F, the size of the uploaded part BS is 8kbs = 8192] by default.) <br/> # Rename (old, new) rename the remote file old to new <br/> # Delete (PATH) to delete the remote file in path <br/> # MKD (directory) create remote directory <br/> # RMD (directory) delete remote directory <br/> # Quit () close the connection and exit <br/> # In normal FTP communication, the commands to be used include login (), CWD (), Dir (), PWD (), STOR * (), RETR * () and quit (). </P> <p >## 1.5 FTP connection FTP example </P> <p> # From ftplib import FTP <br/> # F = FTP ('123. 168.1.168 ') <br/> # F. login ('tmp ', 'tmp') <br/> # F. dir () <br/> # print ('--- create a directory ----') <br/> # F. MKD ('Dave ') <br/> # F. dir () <br/> # F. quit () <br/> # --> output result <br/> # drw-RW-1 user group 0 Sep 19. <br/> # drw-RW-1 user group 0 Sep 19 15:38 .. <br/> # --- create a directory ---- <br/> # drw-RW-1 user group 0 Sep 19 3. <br/> # drw-RW-1 user group 0 Sep 19 :53 .. <br/> # drw-RW-1 user group 0 Sep 19 Dave </P> <p> # example of a client ftp program: download a file from ftp: dave.txt <br/> # import ftplib <br/> # import OS <br/> # import socket <br/> # host = '2017. 168.1.168 '<br/> # user = 'tmp' <br/> # Pwd = 'tmp '<br/> # dirn = 'Dave' <br/> # file = 'dave.txt '<br/> # def main (): <br/> # Try: <br/> # F = ftplib. FTP (host) <br/> # Sort T (S Ocket. error, socket. gaierror) as E: <br/> # print ('error: cannot reach "% s" '% host) <br/> # Return <br/> # print ('*** connected to host "% s"' % host) <br/>#< br/> # Try: <br/> # F. login (user, PWD) <br/> # Login T ftplib. error_perm: <br/> # print ('error: cannot login anonymously ') <br/> # F. quit () <br/> # Return <br/> # print ('*** logged in as [% s]' % USER) <br/> # Try: <br/> # F. CWD (dirn) <br/> # Skip t Ftplib. error_perm: <br/> # print ('error: cannot CD to "% s" '% dirn) <br/> # F. quit () <br/> # Return <br/> # print ('*** changed to "% s" folder' % dirn) <br/> # Try: <br/> # F. retrbinary ('retr % s' % file, open (file, 'wb '). write) <br/> # using t ftplib. error_perm: <br/> # print ('error: cannot read file "% s" '% file) <br/> # OS. unlink (File) <br/> # else: <br/> # print ('*** downloaded "% s" to CWD' % file) <B R/> # F. quit () <br/> # Return <br/> # If _ name _ = '_ main __': <br/> # Main () <br/> # --> output log: <br/> # *** connected to host "192.168.1.168" <br/> # *** logged in as [TMP] <br/> # *** changed to "Dave "folder <br/> # ***** downloaded" dave.txt "to CWD </P> <p> # ************** Part 2: network news *********************** </P> <p >## 2.1 Usenet and newsgroups <br/> # The Usenet news system is a globally archived bulletin board ". News groups with various themes, from poetry to politics <br/> # from natural linguistics to computer language, software to hardware, planting to cooking, recruitment, application, music, magic, break up and pray for love. <Br/> # news groups can be global-oriented or regional-oriented. <Br/> # the entire system is a large global network composed of a large number of computers. Computers share posts on Usenet. for example, <br/> # If a user sends a post to a local Usenet computer, the post will be spread to other connected computers, <br/> # upload the post to the computer connected to it until the post is published all over the world. <br/> # This post is sent to everyone. <br/> # each system has a list of newsgroups it has subscribed, it only receives posts from newsgroups it is interested in -- <br/> # Instead of all newsgroups on the server. The content of USENET newsgroup services depends on the service provider. Many of them are accessible to the public <br/> #. Some users are only allowed to use them, such as paying users, students of specific universities. If the Usenet System <br/> # is set by the Administrator, the user name and password may be required. The administrator can also set whether to allow upload only or download only <br/>. </P> <p >## 2.2 network news transmission Protocol (NNTP) <br/> # The Network News Transmission Protocol (NNTP) is used to download or post a message in a newsgroup ). It was created and recorded in RFC 977 by brain KANTOR (plus <br/> # University of lifonia Santiago) and Phil Lapsley (University of California at Berkeley). <br/>, released on April 9, February 1986. Subsequent Updates are recorded in RFC 2980 and published on April 9, October 2000. <Br/> # as another example of the Client/Server Architecture, NNTP and FTP operations are much easier. FTP requires <br/> # different ports for logon, data transmission, and control, while NNTP only uses one standard port 119 for communication. </P> <p >## 2.3 Python and NNTP </P> <p> # procedure: <br/> #1. connect to the server <br/> #2. log On (if needed) <br/> #3. send a request <br/> #4. exit </P> <p> # pseudocode: <br/> # From nntplib import NNTP <br/> # N = NNTP ('your. NNTP. server ') <br/> # R, C, F, L, G = n. group ('comp. lang. python ') <br/> #... <br/> # N. quit () </P> <p> # generally, after you log on, you need to call the group () method to select a newsgroup you are interested in. Method return service <br/> # server return information, number of articles, ID of the first and last articles, and group name. </P> <p >## 2.4 nntplib. NNTP class method <br/> # NNTP object method <br/> # method description <br/> # group (name) selects the name of a group and returns a tuples (RSP, CT, Fst, lst, group): <br/> # server return information, number of articles, the number of the first and last articles <br/> # code and group name. All data is strings. (The returned group should be the same as the name we passed in.) <br/> # xhdr (HDR, artrg, [ofile]) returns the list of HDR headers in the artrg ('header-tail' format) range of the article, or outputs the list to the file ofile. <br/> # Body (ID [, ofile]) the ID of the given Article. The ID can be the Message ID (placed in angle brackets) or an article number (a string). <br/> # Return a tuple (RSP, anum, mid, data): the server's returned information, article number (a string), message <br/> # ID (in angle brackets ), and the list of all rows in the article or output data to the file ofile. <Br/> # The head (ID) is similar to the body (), but the list of rows in the returned tuples only contains the title of the article. <Br/> # Article (ID) is the same as body (), but the list of rows in the returned tuples contains the title and content of the article. <Br/> # Stat (ID) directs the "Pointer" of the article to the ID (same as above, it is the ID of a message or the number of the article ). <Br/> # returns the same tuples (RSP, anum, and mid) as the body, but does not contain the data of the article. <Br/> # the usage of next () is similar to that of Stat (). Move the article pointer to the next article and return the tuples similar to stat (). <br/> # last () similar to stat (), move the article pointer to the last article and return a tuples similar to stat () <br/> # post (ufile) upload the content in the ufile object (using ufile. readline () and published in the current newsgroup. <Br/> # Quit () Close the connection, then exit </P> <p >## 2.5 interactive NNTP example </P> <p> # From nntplib import NNTP <br/> # N = NNTP ('your. NNTP. server ') <br/> # RSP, CT, Fst, lst, GRP = n. group ('comp. lang. python ') <br/> # RSP, anum, mid, Data = n. article ('200') <br/> # For eachline in data: <br/> # print (eachline) <br/> # N. quit () </P> <p> # *************** Part 3: email ************************ </P> <p >## 3.1 e-Mail System components and protocols <br/> # Send a computer to query an intermediate host, this Platform The host can reach the final receiving host. Then this intermediate host <br/> # Find a host closer to the target host. Therefore, there may be multiple hosts called "Hop <br/> # board" between the sending host and the target host. If you carefully check the email header you received, you will see a "Passport" mark, note <br/> # the location where the email is sent to you. <Br/> # in each component of the E-mail system. The main component is the message transmission proxy (MTA ). <Br/> # This is a server program running on the mail exchange host. It is responsible for mail routing, queuing, and sending. <Br/> # These are the stepping stone for emails from the source host to the target host. Therefore, it is also called "proxy" for "Information Transmission ". <Br/> # To get all the work done, MTA needs to know two things: 1) how to find the next MTA for which the message should go 2) how to <br/> # communicate with another MTA. First, the Domain Name Service (DNS) is used to find the MX of the target domain name (mail exchange) <br/>. This is not necessary for the last recipient, but it is necessary for other springboards. </P> <p >## 3.2 </P> <p >## 3.2.1 SMTP Simple Mail Transfer Protocol <br/> # SMTP appeared on January 1, 1982, created by the late Jonathan Postel (School of information, University of California), recorded in RFC 821, published on <br/> # November 1, August 1982. The subsequent modification was recorded in RFC 2821 and published on April 9, April 2001. </P> <p> # some well-known MTA that has implemented SMTP include: <br/> # <br/>### open source MTA <br/> # sendmail <br/> # Postfix <br/> # Exim <br/> # Qmail (free of charge) release, but not open source) <br/>#< br/>### commercial MTA <br/> # Microsoft Exchange <br/> # Lotus Notes Domino Mail Server </P> <p> # Note, although both implement the Minimum SMTP protocol defined in RFC 2821, most of them, especially some <br/> # commercial MTA, all added the unique features beyond the Protocol definition to the server. <Br/> # SMTP is the most common MTS used for message exchange between MTA instances on the Internet. It is used by MTA to transmit e-mail from one host <br/> # to another host. When you send an email, you must connect to an external SMTP server. At this time, your <br/> # email program is an SMTP client. Your SMTP server has become the first stepping stone for your messages. </P> <p >## 3.2.2 Python and SMTP <br/> # Python connects to stmp through the smtplib module. </P> <p> # Python pseudocode: <br/> # From smtplib import SMTP <br/> # N = SMTP ('smtp .yourdomain.com ') <br/> # Pass <br/> # N. quit () </P> <p> #3.2.3 smtplib. SMTP method <br/> # For most E-mail sending programs, only two methods are required: Sendmail () and quit (). <Br/> # all parameters of Sendmail () must comply with RFC 2822, that is, the e-mail address must be in the correct format, the message body must have a positive <br/> # Leading header, followed by two carriage return and line feed (\ r \ n) pairs. </P> <p> # SMTP object method <br/> # method description <br/> # Sendmail (from, to, MSG [, mopts, ropts]) send MSG from to (list or tuples ). ESMTP settings (mopts) and recipient settings (ropts) are optional. <Br/> # Quit () closes the connection and then exits <br/> # login (user, passwd) use the user and passwd password to log on to the SMTP server </P> <p >## 3.2.3 interactive SMTP example </P> <p> # import smtplib <br/> # <br /> # def prompt (prompt): <br/> # Return input (prompt ). strip () <br/> # fromaddr = prompt ("from:") <br/> # toaddrs = prompt (":"). split () <br/> # print ("enter message, end with ^ d (UNIX) or ^ Z (Windows ):") <br/> # Add the from: And to: headers at the start! <Br/> # MSG = ("from: % s \ r \ nto: % s \ r \ n" <br/> # % (fromaddr ,", ". join (toaddrs) <br/> # While true: <br/> # Try: <br/> # line = input () <br/> # limit t eoferror: <br/> # Break <br/> # if not line: <br/> # Break <br/> # MSG = MSG + LINE <br/> # print ("message length is", Len (MSG )) <br/> # Server = smtplib. SMTP ('smtp .gmail.com ') <br/> # server. starttls () # Start TLS mode, Gmail requirements <br/> # server. set_debuglevel (1) <br/> # server. login ('username', 'pwd') <br/> # server. sendmail (fromaddr, toaddrs, MSG) <br/> # server. quit () <br/> # --> output log <br/> # From: dvd.dba@gmail.com <br/> # To: dvd.dba@gmail.com <br/> # enter message, end with ^ d (UNIX) or ^ Z (Windows ): <br/> # David Dai <br/> # message length is 59 <br/> # Send: 'ehlo [192.168.3.115] \ r \ n' <br/> # reply: B '250 -mx.google.com at your service, [60.191.73.11] \ r \ N' <br/> # reply: B '250-size 35882577 \ r \ n' <br/> # reply: B '250-8bitmime \ r \ n' <br/> # reply: B' 250-AUTH LOGIN plain xoauth \ r \ n' <br/> # reply: B '250 enhancedstatuscodes \ r \ n' <br/> # reply: retcode (250); MSG: B' MX .google.com at your service, [60.191.73.11] \ nsize 35882577 \ n8bitmime \ nauth login plain xoauth \ nenhancedstatuscodes '<br/> # Send: 'auth plain login \ r \ n' <br/> # reply: B '235 2.7. 0 accepted \ r \ n' <br/> # reply: retcode (235); MSG: B '2. 7.0 accepted '<br/> # Send: 'mail from: <dvd.dba@gmail.com> size = 59 \ r \ n' <br/> # reply: B' 250 2.1.0 OK n10sm151_361pbe. 4 \ r \ n' <br/> # reply: retcode (250); MSG: B '2. 1.0 OK n10sm15da-361pbe. 4' <br/> # Send: 'RCPT TO: <dvd.dba@gmail.com> \ r \ n' <br/> # reply: B '250 2.1.5 OK n10sm151_361pbe. 4 \ r \ n' <br/> # reply: retcode (250); MSG: B '2. 1.5 OK n10sm15da-361pbe. 4 '<Br/> # Send: 'Data \ r \ n' <br/> # reply: B' 354 go ahead n10sm151_361pbe. 4 \ r \ n' <br/> # reply: retcode (354); MSG: B 'go ahead n10sm151_361pbe. 4' <br/> # data: (354, B 'go ahead n10sm151_361pbe. 4 ') <br/> # Send: B' from: dvd.dba@gmail.com \ r \ nto: dvd.dba@gmail.com \ r \ n \ r \ ndavid Dai \ r \ n. \ r \ n' <br/> # reply: B '250 2.0.0 OK 1316596683 n10sm151_361pbe. 4 \ r \ n' <br/> # reply: retcode (250); MSG: B '2. 0.0 OK 1316596683 n 10sm15da-361pbe. 4' <br/> # data: (250, B '2. 0.0 OK 1316596683 n10sm15da-361pbe. 4 ') <br/> # Send: 'Quit \ r \ n' <br/> # reply: B' 221 2.0.0 closing connection n10sm151_361pbe. 4 \ r \ n' <br/> # reply: retcode (221); MSG: B '2. 0.0 closing connection n10sm150000361pbe. 4' </P> <p >## 3.2.4 receive e-mail <br/> # Mail User proxy (Mua): Mua downloads the email from the server, in this process, they may be automatically deleted (or left on the server for manual deletion ). <Br/> # However, Mua must also be able to send emails. That is to say, when sending an email, it must be able to communicate directly with the MTA using SMTP. </P> <p >## 3.2.5 pop and imap </P> <p> # The first protocol used to download an email is Post Office Protocol (POP ), the record is recorded in RFC 918 and published on April 9, October 1984. The Post Office Protocol <br/> # (POP) aims to allow users' workstations to access emails on the mailbox server. Emails must be sent from the workstation via simple mail <br/> # The Transmission Protocol (SMTP) to the mail server ". The latest version of the POP protocol is 3rd, also known as POP3. </P> <p> # In a few years after pop, another Protocol emerged, called the interactive mail access protocol (IMAP ). The first version is experimental. <br/> # RFC 2nd was not published on April 9, 1064 until version 1988. The currently used IMAP version is imap4rev1, which is also widely used <br/>. In fact, Microsoft Exchange, which occupies the majority of mail servers in the world today, uses imap <br/> # as its download mechanism. The imap4rev1 protocol was defined in RFC 3501 and was published on April 9, March 2003. IMAP aims to provide a more <br/> # comprehensive solution. </P> <p >## 3.2.6 Python and POP3 <br/> # import poplib and instantiate poplib. POP3 class </P> <p> # The pseudocode of python is as follows: <br/> # From poplib import POP3 <br/> # P = POP3 ('pop. python. is. cool ') <br/> # P. user (...) <br/> # P. pass _(...) <br/> #... <br/> # P. quit () </P> <p> #3.2.7 example of interactive POP3 </P> <p> # import poplib <br/> # M = poplib. POP3 ('pop .qq.com ') <br/> # M. user ('username') <br/> # M. pass _ ('pwd') <br/> # nummessages = Len (M. list () [1]) <br/> # For I in range (nummessages): <br/> # For J in M. RETR (I + 1) [1]: <br/> # print (j) </P> <p> #3.2.7 poplib. POP3 method </P> <p> # common POP3 object methods <br/> # method description <br/> # user (LOGIN) sends the username login to the server, and wait for the server to wait for the user password to return information <br/> # Pass _ (passwd) to send the password passwd (used after user () login ). If logon fails, an exception is thrown. <br/> # Stat () returns the mail status, a 2-length tuples (msg_ct, mbox_siz ): the number of messages and the total size of messages, that is, the number of bytes <br/> # list ([msgnum]) Stat () extension, the server returns the message list (RSP, msg_list, rsp_siz) of 3 tuples: the server's returned information, message list, and returned information size. <Br/> # If msgnum is given, only data of the specified message is returned. <Br/> # RETR (msgnum) obtains the message msgnum from the server and sets its "read" flag. <Br/> # returns a triple (RSP, msglines, msgsiz) with a length of 3: the server's returned information, all rows of the message msgnum, number of bytes of a message <br/> # DELE (msgnum) marks the message msgnum as deleted. Most servers perform the delete operation after calling quit. <Br/> # log out of quit (), save the changes (for example, execute the "read" and "delete" tags), unlock the mailbox, and end the connection, then exit </P> <p> # at login, the user () method not only sends the user name to the server, you also need to wait for the server to wait for the Response Message of the User Password <br/>. If the pass _ () method fails to be authenticated, A poplib. error_proto exception is thrown. <Br/> # If the email address succeeds, a message starting with '+' is returned, for example, "+ OK ready". Then, the email address on the server is locked, until the quit () method is called. <Br/> # When the list () method is called, The msg_list format is: ['msgnum msgsiz',…], Msgnum and msgsiz indicate the number and size of each message. <Br/>

 

 

 

 

Bytes -------------------------------------------------------------------------------------------------------

Blog: http://blog.csdn.net/tianlesoftware

WEAVER: http://weibo.com/tianlesoftware

Email: dvd.dba@gmail.com

Dba1 group: 62697716 (full); dba2 group: 62697977 (full) dba3 group: 62697850 (full)

Super DBA group: 63306533 (full); dba4 group: 83829929 (full) dba5 group: 142216823 (full)

Dba6 group: 158654907 (full) dba7 group: 69087192 (full) dba8 group: 172855474

DBA super group 2: 151508914 dba9 group: 102954821 chat group: 40132017 (full)

-- Add the group to describe the relationship between Oracle tablespace and data files in the remarks section. Otherwise, the application is rejected.

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.