python socket模块的使用示例

发布时间:2019-08-22编辑:脚本学堂
这里为大家介绍python中socket模块的几个应用实例(打印dns查询、模拟简易的scp),供大家学习参考。

这里为大家介绍python中socket模块的几个应用实例(打印dns查询模拟简易的scp),供大家学习参考。

一、打印dns查询

复制代码 代码如下:

#!/usr/bin/python
import socket

def gethost_ex(host_ex):
        hostname_ex,alias_ex,address_ex = socket.gethostbyname_ex(host_ex)
        return hostname_ex,alias_ex,address_ex
def array_print(*arr):
        for item in arr:
                print '  ',item
        print

for host in ["www.baidu.com","www.sohu.com","www.google.com"]:
        print host
        try :
                hostname,alias,address = gethost_ex(host)
        except socket.error as e:
                print 'error',e
                continue
        print ' HostName:',hostname
        print ' Alias:'
        array_print(*alias)
        print ' Address:'
        array_print(*address)

#-------------------------------

二、模拟简易的scp
实现比较简单有两台机器间拷贝文件。

1)、server端:
 

复制代码 代码如下:

#!/usr/bin/python
import socket
import sys
import os

def filesplit(filename):
filesp = os.path.dirname(filename)
filespdir = "/root/tmp" + filesp
filespbase = "/root/tmp" + filename
return filespdir,filespbase

def makedir(dir):
if os.path.exists(dir):
return None
else:
dirname = os.path.dirname(dir)
if os.path.exists(dirname):
os.path.mkdir(dir)
else:
makedir(dirname)

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address = ('192.168.1.100',10000)
print >>sys.stderr,'starting up on %s port %s' % server_address

sock.bind(server_address)
sock.listen(10)
while True:
print >>sys.stderr,'waiting for a connection'
connection,client_address = sock.accept()
try :
print >>sys.stderr,'connection from',client_address
file = connection.recv(100)
filedir,filebase = filesplit(file)
makedir(filedir)
filecre = open(filebase,"w")
connection.sendall("start")
while True:
data  = connection.recv(2048)
if len(data) > 0:
filecre.write(data)
else:
break
filecre.close()
finally:
connection.close()

2)、户端:
 

复制代码 代码如下:

#!/usr/bin/python
import sys
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server_address = ('192.168.1.100',10000)
print >>sys.stderr,'connection to %s port %s' % server_address

try:
sock.connect(server_address)
except socket.error:
print >>sys.stderr,"connection to this server failued"
sys.exit(1)

file = raw_input("please input your filepath: ").rstrip()
try:
fd = open(file,"r")
except IOError:
print >>sys.stderr,"open %s failued" % file
sys.exit(1)

sock.sendall(file)
data = sock.recv(5)
if data == "start":
print >>sys.stderr,'start put file  "%s"' % file
try :
while True:
put_line = fd.read(2048)
if len(put_line) > 0:
sock.sendall(put_line)
else:
print "put % success" % file
break
finally:
sock.close()
else :
print "put file %s failure" % file
sys.exit(255)