您的位置:首页 > 理论基础 > 计算机网络

python 教程 第十七章、 网络编程

2011-10-13 12:20 513 查看
第十七章、 网络编程
1) FTP客户端

import ftplib

import os

import socket


HOST = '127.0.0.1'

DIRN = 'menus'

FILE = 'hello.txt'

USER = 'taojin'

PASS = 'pass123'


def main():

try:

f = ftplib.FTP(HOST)

f.login(user = USER, passwd = PASS)

f.cwd(DIRN)

f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)

except e:

print 'ERROR' + e

finally:

f.quit()

return


if __name__ == '__main__':

main()

2) Telnet客户端

import sys

import telnetlib


HOST = "172.22.11.229"

USER = "bbndserviceaccount"

PASS = "admin"


tn = telnetlib.Telnet(HOST)

tn.read_until("login:")

tn.write(USER + "\n")

tn.read_until("Password:")

tn.write(PASS + "\n")

tn.write("ls -a\n")

tn.write("exit\n")

print tn.read_all()

tn.close()

3) SSH客户端
环境设置
1).安装MinGW编译环境(mingw-get-inst-20110530.exe)
下载http://sourceforge.net/projects/mingw/
2).安装PyCrypto库(The Python Cryptography Toolkit)
下载https://www.dlitz.net/software/pycrypto/
解压放到python安装目录下的lib目录里
用MinGW编译pycrypto

D:\Python27\Lib\pycrypto-2.3>python setup.py build --compiler=mingw32

D:\Python27\Lib\pycrypto-2.3>python setup.py install

3).安装paramiko (SSH2 protocol for python)
下载http://www.lag.net/paramiko/
解压放到python安装目录下的lib目录里

D:\Python27\Lib\pycrypto-2.3>cd ..\paramiko-1.7.7.1

D:\Python27\Lib\paramiko-1.7.7.1>python setup.py install

import paramiko


ssh2 = paramiko.SSHClient()

ssh2.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh2.connect('172.22.11.229', 22, username='bbndserviceaccount', password='admin')

stdin, stdout, stderr = ssh2.exec_command('pwd')

for std in stdout.readlines():

print std

ssh2.close()

4) 电子邮件

POP编程

>>> from poplib import POP3


>>> p = POP3('pop.139.com')


>>> p.user('username')


'+OK core mail'


>>> p.pass_('password')


'+OK 3 message(s) [6115 byte(s)]'


>>> p.stat()


(3, 6115)


>>> rep, msg, siz = p.retr(3)


>>> rep, siz


('+OK 2571 octets', 2571)


>>> for eachLine in msg:


print eachLine

SMTP编程

>>> from smtplib import SMTP as smtp

>>> s = smtp('smtp.139.com')

>>> s.login('username', 'yourpass')

(235, 'Authentication successful')

>>> s.sendmail(username@139.com', ' username@qq.com', '''From: username@139.com\r\nTo: username @qq.com\r\nSubject: python mail title\r\n\r\nThis is python mail content.\r\n''')

{}

>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: