17.2 檔案傳輸
17.2.1 檔案傳輸網際協議
有很多協議可以供網際網路上傳輸檔案使用。最流行的有檔案傳輸協議(file transfer protocol, ftp)、unix-to-unix複製協議(unix-to-unix copy protocol, uucp)和網頁的超文字傳輸協議(hypertext transfer protocol, http)。另外,還有(unix下的)遠端檔案複製指令rcp(以及更安全、更靈活的scp和rsync)。
17.2.2 檔案傳輸協議(ftp)
ftp要求使用者輸入使用者名稱和密碼才能訪問遠端的ftp伺服器,但它也允許沒有帳號的使用者以匿名使用者登入。不過,管理員要先設定ftp伺服器允許匿名使用者登入。
其工作流程如下:
1.客戶端遠端連線的ftp伺服器。
2.客戶端輸入使用者名稱和密碼(或「匿名」和電子郵件位址)
3.客戶端做各種檔案傳輸和資訊查詢操作
4.客戶端登出遠端ftp伺服器,結束通訊
在底層上,ftp只使用tcp——它不使用udp。而且,ftp是客戶端/伺服器程式設計中很「與眾不同」的例子。客戶端和伺服器都使用兩個套接字來通訊:乙個是控制和命令埠(21號埠),另乙個是資料埠(有時是20號埠).
ftp有兩種模式:主動和被動。只有主動模式伺服器才使用資料埠。在伺服器把20號埠設定為資料埠後,它「主動」連線客戶端的資料埠。而被動模式中。伺服器只是告訴客戶端它的隨機埠的號碼,客戶端必須主動建立資料連線。在這種模式下,你會看到,ftp伺服器在建立資料連線時是「被動」的。
一般在客戶端超過15分鐘(900秒)不活動之後,連線就會被關閉。
17.2.3 python和ftp
在使用python的ftp支援時,你所需要做的就是匯入ftplib模組,並例項化乙個ftplib.ftp類物件。
import string
from ftplib import ftp
bufsize=1024
def get(filename):
command='retr '+filename
ftp.retrbinary(command,open(filename,'wb').write,bufsize)
print 'download successfully'
def put(filename):
command='stor '+filename
filehandler=open(filename,'rb')
ftp.storbinary(command,filehandler,bufsize)
filehandler.close()
print 'upload successfully'
def pwd():
print ftp.pwd()
def size(filename):
print ftp.size(filename)
def help():
print '''
******************************
****** python ftp
******************************
cd enter document
delete delete file
dir get files list
get download file
help help
mkdir create document
put upload file
pwd get current path
rename rename file name
rmdir delete document
size get file size
'''server=raw_input('enter ftp server info: ')
ftp=ftp(server)
username=raw_input('username:')
password=raw_input('password')
ftp.login(username,password)
print ftp.getwelcome()
actions=
while true:
print 'pyftp',
cmds=raw_input
cmd=string.split(cmds)
try:
if len(cmd)==1:
if string.lower(cmd[0])=='quit':
break
else:
actions[string.lower(cmd[0])]
elif len(cmd)==2:
actions[string.lower(cmd[0])](cmd[1])
elif len(cmd)==3:
actions[string.lower(cmd[0])](cmd[1],cmd[2])
else:
print 'type error'
except:
print 'command error'
ftp.quit()
17.2.7 ftp的其他方面
Python網路程式設計客戶端
程式設計流程 1 建立套接字 2 建立連線 3 傳送資料 資料要用二進位制個數編碼 4 接收資料,並設定資料流大小 import socket clientsocket socket.socket socket.af inet,socket.sock stream 建立連線 伺服器的位址和埠 hos...
網路聊天 客戶端(Winsock程式設計)
網路聊天 客戶端.cpp 定義控制台應用程式的入口點。include stdafx.h include include include pragma comment lib,ws2 32.lib using namespace std 接收伺服器發來的資料的程序 void recvproc sock...
python網路程式設計 HTTP客戶端
urllib和requests是python對http協議的應用,使用的兩個庫。urllib是python的標準內建庫,requests是乙個比urllib更強大的第三方庫。下面我們會使用乙個網域名稱為http httpbin.org的小型測試 來測試這兩個http客戶端。上面兩張分別是使用requ...