wiki:Python/Snippet/ネットワーク

Version 1 (modified by nakiki, 13 years ago) (diff)

--

CGI

import CGIHTTPServer
import BaseHTTPServer
import SimpleHTTPServer

def serveForever(addr, HandlerClass = CGIHTTPServer.CGIHTTPRequestHandler,
        ServerClass = BaseHTTPServer.HTTPServer):
  HandlerClass.protocol_version = 'HTTP/1.0'
  httpd = ServerClass(addr, HandlerClass)
  sa = httpd.socket.getsockname()
  print "Serving HTTP on %s:%d" % (sa[0], sa[1])
  httpd.serve_forever()

if __name__ == '__main__':
  serveForever(('127.0.0.1', 8000))

FTPクライアント

import ftplib

ftp = ftplib.FTP('yourhost')
ftp.login('user', 'xxxxx')
f = open('xxxx.exe', 'wb')
ftp.retrbinary('RETR xxxx.exe', f.write)
f.close()

HTTPクライアント

import httplib

h = httplib.HTTPConnection('www.yahoo.com')
h.request('GET', '/index.html')
r = h.getresponse()
if r.status == httplib.OK:
  data = r.read()
  print data
print 'Status=', r.status

HTTPサーバ

import BaseHTTPServer
import SimpleHTTPServer

addr = ('127.0.0.1', 8000)
Server = BaseHTTPServer.HTTPServer
handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = Server(addr, handler)
httpd.serve_forever()

メールクライアント

import smtplib

server = smtplib.SMTP('localhost')
fromaddr = 'xxx@xxx.xxx.xxx'
toaddr = 'yyy@yyy.yyy.yyy'
msg = 'test message'
server.sendmail(fromaddr, toaddr, msg)
server.quit()