`
sinxadmin
  • 浏览: 80388 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Networking

阅读更多
    
Example 5-1. TCP port checker
#!/usr/bin/env python
import socket
import re
import sys
def check_server(address, port):
    #create a TCP socket
    s = socket.socket()
    print "Attempting to connect to %s on port %s" % (address, port)
    try:
        s.connect((address, port))
        print "Connected to %s on port %s" % (address, port)
        return True
    except socket.error, e:
        print "Connection to %s on port %s failed: %s" % (address, port, e)
    return False
if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-a", "--address", dest="address", default='localhost',
        help="ADDRESS for server", metavar="ADDRESS")
    parser.add_option("-p", "--port", dest="port", type="int", default=80,
        help="PORT for server", metavar="PORT")
    (options, args) = parser.parse_args()
    print 'options: %s, args: %s' % (options, args)
    check = check_server(options.address, options.port)
    print 'check_server returned %s' % check
    sys.exit(not check)



Example 5-2. Socket-based web server checker
#!/usr/bin/env python
import socket
import re
import sys
def check_webserver(address, port, resource):
    #build up HTTP request string
    if not resource.startswith('/'):
        resource = '/' + resource
    request_string = "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n" % (resource, address)
    print 'HTTP request:'
    print '|||%s|||' % request_string
    #create a TCP socket
    s = socket.socket()
    print "Attempting to connect to %s on port %s" % (address, port)
    try:
        s.connect((address, port))
        print "Connected to %s on port %s" % (address, port)
        s.send(request_string)
        #we should only need the first 100 bytes or so
        rsp = s.recv(100)
        print 'Received 100 bytes of HTTP response'
        print '|||%s|||' % rsp
    except socket.error, e:
        print "Connection to %s on port %s failed: %s" % (address, port, e)
        return False
    finally:
        #be a good citizen and close your connection
        print "Closing the connection"
        s.close()
    lines = rsp.splitlines()
    print 'First line of HTTP response: %s' % lines[0]
    try:
        version, status, message = re.split(r'\s+', lines[0], 2)
        print 'Version: %s, Status: %s, Message: %s' % (version, status, message)
    except ValueError:
        print 'Failed to split status line'
        return False
    if status in ['200', '301']:
        print 'Success - status was %s' % status
        return True
    else:
        print 'Status was %s' % status
        return False
if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-a", "--address", dest="address", default='localhost',
        help="ADDRESS for webserver", metavar="ADDRESS")
    parser.add_option("-p", "--port", dest="port", type="int", default=80,
        help="PORT for webserver", metavar="PORT")
    parser.add_option("-r", "--resource", dest="resource", default='index.html',
        help="RESOURCE to check", metavar="RESOURCE")
    (options, args) = parser.parse_args()
    print 'options: %s, args: %s' % (options, args)
    check = check_webserver(options.address, options.port, options.resource)
    print 'check_webserver returned %s' % check
    sys.exit(not check)

Example 5-3. httplib-based web server checker
#!/usr/bin/env python
import httplib
import sys
def check_webserver(address, port, resource):
    #create connection
    if not resource.startswith('/'):
        resource = '/' + resource
    try:
        conn = httplib.HTTPConnection(address, port)
        print 'HTTP connection created successfully'
        #make request
        req = conn.request('GET', resource)
        print 'request for %s successful' % resource
        #get response
        response = conn.getresponse()
        print 'response status: %s' % response.status
    except sock.error, e:
        print 'HTTP connection failed: %s' % e
        return False
    finally:
        conn.close()
        print 'HTTP connection closed successfully'
    if response.status in [200, 301]:
        return True
    else:
        return False
if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-a", "--address", dest="address", default='localhost',
        help="ADDRESS for webserver", metavar="ADDRESS")
    parser.add_option("-p", "--port", dest="port", type="int", default=80,
        help="PORT for webserver", metavar="PORT")
    parser.add_option("-r", "--resource", dest="resource", default='index.html',
        help="RESOURCE to check", metavar="RESOURCE")
    (options, args) = parser.parse_args()
    print 'options: %s, args: %s' % (options, args)
    check = check_webserver(options.address, options.port, options.resource)
    print 'check_webserver returned %s' % check
    sys.exit(not check)



Example 5-4. FTP URL retriever using ftplib
#!/usr/bin/env python
from ftplib import FTP
import ftplib
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-a", "--remote_host_address", dest="remote_host_address",
    help="REMOTE FTP HOST.",
    metavar="REMOTE FTP HOST")
parser.add_option("-r", "--remote_file", dest="remote_file",
    help="REMOTE FILE NAME to download.",
    metavar="REMOTE FILE NAME")
parser.add_option("-l", "--local_file", dest="local_file",
    help="LOCAL FILE NAME to save remote file to", metavar="LOCAL FILE NAME")
parser.add_option("-u", "--username", dest="username",
    help="USERNAME for ftp server", metavar="USERNAME")
parser.add_option("-p", "--password", dest="password",
    help="PASSWORD for ftp server", metavar="PASSWORD")
(options, args) = parser.parse_args()
if not (options.remote_file and
        options.local_file and
        options.remote_host_address):
    parser.error('REMOTE HOST, LOCAL FILE NAME, ' \
    'and REMOTE FILE NAME are mandatory')
if options.username and not options.password:
    parser.error('PASSWORD is mandatory if USERNAME is present')
ftp = FTP(options.remote_host_address)
if options.username:
    try:
        ftp.login(options.username, options.password)
    except ftplib.error_perm, e:
        print "Login failed: %s" % e
        sys.exit(1)
else:
    try:
        ftp.login()
    except ftplib.error_perm, e:
        print "Anonymous login failed: %s" % e
    sys.exit(1)
try:
    local_file = open(options.local_file, 'wb')
    ftp.retrbinary('RETR %s' % options.remote_file, local_file.write)
finally:
    local_file.close()
    ftp.close()



Example 5-5. FTP URL retriever using urllib
#!/usr/bin/env python
"""
url retriever
Usage:
url_retrieve_urllib.py URL FILENAME
URL:
If the URL is an FTP URL the format should be:
ftp://[username[:password]@]hostname/filename
If you want to use absolute paths to the file to download,
you should make the URL look something like this:
ftp://user:password@host/%2Fpath/to/myfile.txt
Notice the '%2F' at the beginning of the path to the file.
FILENAME:
absolute or relative path to the filename to save downloaded file as
"""
import urllib
import sys
if '-h' in sys.argv or '--help' in sys.argv:
    print __doc__
    sys.exit(1)
if not len(sys.argv) == 3:
    print 'URL and FILENAME are mandatory'
    print __doc__
    sys.exit(1)
url = sys.argv[1]
filename = sys.argv[2]
urllib.urlretrieve(url, filename)



Example 5-6. Simple XML-RPC server
#!/usr/bin/env python
import SimpleXMLRPCServer
import os
def ls(directory):
    try:
        return os.listdir(directory)
    except OSError:
        return []
def ls_boom(directory):
    return os.listdir(directory)
def cb(obj):
    print "OBJECT::", obj
    print "OBJECT.__class__::", obj.__class__
    return obj.cb()
if __name__ == '__main__':
    s = SimpleXMLRPCServer.SimpleXMLRPCServer(('127.0.0.1', 8765))
    s.register_function(ls)
    s.register_function(ls_boom)
    s.register_function(cb)
    s.serve_forever()


Example 5-7. Simple Pyro server
#!/usr/bin/env python
import Pyro.core
import os
from xmlrpc_pyro_diff import PSACB
class PSAExample(Pyro.core.ObjBase):
    def ls(self, directory):
        try:
            return os.listdir(directory)
    except OSError:
        return []
    def ls_boom(self, directory):
        return os.listdir(directory)
    def cb(self, obj):
        print "OBJECT:", obj
        print "OBJECT.__class__:", obj.__class__
        return obj.cb()
if __name__ == '__main__':
    Pyro.core.initServer()
    daemon=Pyro.core.Daemon()
    uri=daemon.connect(PSAExample(),"psaexample")
    print "The daemon runs on port:",daemon.port
    print "The object's uri is:",uri
    daemon.requestLoop()


Example 5-8. Differences between XML-RPC and Pyro
import Pyro.core
import xmlrpclib
class PSACB:
    def __init__(self):
        self.some_attribute = 1
    def cb(self):
        return "PSA callback"
if __name__ == '__main__':
    cb = PSACB()
    print "PYRO SECTION"
    print "*" * 20
    psapyro = Pyro.core.getProxyForURI("PYROLOC://localhost:7766/psaexample")
    print "-->>", psapyro.cb(cb)
    print "*" * 20
    print "XML-RPC SECTION"
    print "*" * 20
    psaxmlrpc = xmlrpclib.ServerProxy('http://localhost:8765')
    print "-->>", psaxmlrpc.cb(cb)
    print "*" * 20



Example 5-9. Connecting to an SSH server and remotely executing a command
#!/usr/bin/env python
import paramiko
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
password = 'xxxYYYxxx'
if __name__ == "__main__":
    paramiko.util.log_to_file('paramiko.log')
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(hostname, port, username, password)
    stdin, stdout, stderr = s.exec_command('ifconfig')
    print stdout.read()
    s.close()


Example 5-10. Retrieving files from an SSH server
#!/usr/bin/env python
import paramiko
import os
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
password = 'xxxYYYxxx'
dir_path = '/home/jmjones/logs'
if __name__ == "__main__":
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    files = sftp.listdir(dir_path)
    for f in files:
        print 'Retrieving', f
        sftp.get(os.path.join(dir_path, f), f)
    t.close()


Example 5-11. Connecting to an SSH server and remotely executing a command—private keys
enabled
#!/usr/bin/env python
import paramiko
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
pkey_file = '/home/jmjones/.ssh/id_rsa'
if __name__ == "__main__":
    key = paramiko.RSAKey.from_private_key_file(pkey_file)
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(hostname, port, pkey=key)
    stdin, stdout, stderr = s.exec_command('ifconfig')
    print stdout.read()
    s.close()
   

Example 5-12. Retrieving files from an SSH server
#!/usr/bin/env python
import paramiko
import os
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
dir_path = '/home/jmjones/logs'
pkey_file = '/home/jmjones/.ssh/id_rsa'
if __name__ == "__main__":
    key = paramiko.RSAKey.from_private_key_file(pkey_file)
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, pkey=key)
    sftp = paramiko.SFTPClient.from_transport(t)
    files = sftp.listdir(dir_path)
    for f in files:
        print 'Retrieving', f
        sftp.get(os.path.join(dir_path, f), f)
    t.close()



Example 5-13. Port checker implemented in Twisted
#!/usr/bin/env python
from twisted.internet import reactor, protocol
import sys
class PortCheckerProtocol(protocol.Protocol):
    def __init__(self):
        print "Created a new protocol"
    def connectionMade(self):
        print "Connection made"
        reactor.stop()
class PortCheckerClientFactory(protocol.ClientFactory):
    protocol = PortCheckerProtocol
    def clientConnectionFailed(self, connector, reason):
        print "Connection failed because", reason
        reactor.stop()
if __name__ == '__main__':
    host, port = sys.argv[1].split(':')
    factory = PortCheckerClientFactory()
    print "Testing %s" % sys.argv[1]
    reactor.connectTCP(host, int(port), factory)
    reactor.run()


Example 5-14. Twisted Perspective Broker server
import os
from twisted.spread import pb
from twisted.internet import reactor
class PBDirLister(pb.Root):
    def remote_ls(self, directory):
        try:
            return os.listdir(directory)
        except OSError:
            return []
    def remote_ls_boom(self, directory):
        return os.listdir(directory)
if __name__ == '__main__':
    reactor.listenTCP(9876, pb.PBServerFactory(PBDirLister()))
    reactor.run()



Example 5-15. Twisted Perspective Broker client
#!/usr/bin/python
from twisted.spread import pb
from twisted.internet import reactor
def handle_err(reason):
    print "an error occurred", reason
    reactor.stop()
def call_ls(def_call_obj):
    return def_call_obj.callRemote('ls', '/home/jmjones/logs')
def print_ls(print_result):
    print print_result
    reactor.stop()
if __name__ == '__main__':
    factory = pb.PBClientFactory()
    reactor.connectTCP("localhost", 9876, factory)
    d = factory.getRootObject()
    d.addCallback(call_ls)
    d.addCallback(print_ls)
    d.addErrback(handle_err)
    reactor.run()



Example 5-16. Twisted Perspective Broker client—error
#!/usr/bin/python
from twisted.spread import pb
from twisted.internet import reactor
def handle_err(reason):
print "an error occurred", reason
reactor.stop()
def call_ls(def_call_obj):
    return def_call_obj.callRemote('ls_boom', '/foo')
def print_ls(print_result):
    print print_result
    reactor.stop()
if __name__ == '__main__':
    factory = pb.PBClientFactory()
    reactor.connectTCP("localhost", 9876, factory)
    d = factory.getRootObject()
    d.addCallback(call_ls)
    d.addCallback(print_ls)
    d.addErrback(handle_err)
    reactor.run()




分享到:
评论

相关推荐

    Computer Networking A Top-Down Approach (7th Edition)

    Unique among computer networking texts, the Seventh Edition of the popular Computer Networking: A Top Down Approach builds on the author’s long tradition of teaching this complex subject through a ...

    Cisco Networking Essentials 2nd Edition

    Cisco Networking Essentials, 2nd Edition provides the latest for those beginning a career in networking. This book provides the fundamentals of networking and leads you through the concepts, processes...

    Linux Kernel Networking Implementation and Theory

    Linux Kernel Networking takes you on a guided in-depth tour of the current Linux networking implementation and the theory behind it. Linux kernel networking is a complex topic, so the book won't ...

    cambridge.multimedia.networking

    The four most critical and indispensable components involved in a multimedia networking system are: (1) data compression (source encoding) of multimedia data sources, e.g., speech, audio, image, and ...

    Business Data Communications and Networking: A Research Perspective

    Research in the area of data communications and networking is well and alive as this collection of contributions show. The book has received enhanced contributions from the authors that published in ...

    High performance browser networking

    will improve networking Learn how to use Server Sent Events (SSE) for push updates, and WebSockets for XMPP chat Explore WebRTC for browser-to-browser applications such as P2P video chat Examine the ...

    Windows_Networking_Troubleshooting

    Determine the common causes of networking problems and how to avoid them Troubleshoot network connection problems Manage networking for Windows virtual machines Keep the mobile or BYOD worker ...

    Mastering Python Networking 【含代码】

    Mastering Python Networking English | 2017 | ISBN-10: 1784397008 | 446 pages | PDF + EPUB + MOBI (conv) | 9.76 Mb Key Features Build the skills to perform all networking tasks using Python with ease ...

    Fundamental Networking in Java

    the point of view of the Java API, and by discussing advanced networking programming techniques.1 The new I/O and networking features introduced in " 1.4 provide further justification for the ...

    Foundations of Modern Networking-Pearson Education(2016).epub

    A host of factors have converged to produce the latest revolution in computer and communications networking: Image Demand: Enterprises are faced with a surge of demands that focus their attention on ...

    OpenStack.Networking.Essentials.1785283278

    The OpenStack Networking API offers users the ability to create and manage both basic and complex network architectures that blend the virtual and physical network infrastructure. This book kicks off...

    networking

    networking Computer Networks, Computer Network Security, Artificial Intelligence

    Networking.Wireless.Sensors

    无线传感器网络 外国教程 Networking.Wireless.Sensors

    Learning RHEL Networking(PACKT,2015)

    RHEL networking lets you accomplish these tasks easily. This is a highly-detailed guide to help with your deployments on RHEL 7 or CentOS 7. This book, based on RHEL 7.1, will introduce to you the ...

    2019 Open Networking Summit(ONS).zip

    How Open Networking can Manage Large-Scale VPCs on Top of Clos Network Architecture Kernel-based Forwarding Plane for Network Service Mesh Lightning Talk:Cloud Native for Non-Coders Network Traffic ...

    Handbook of Peer-to-Peer Networking

    This book is written for researchers, professionals, and computer science and engineering students at the advanced undergraduate level and higher who are familiar with networking and network protocol ...

    computer Networking - A top down approach 6th

    Computer Networking continues with an early emphasis on application-layer paradigms and application programming interfaces (the top layer), encouraging a hands-on experience with protocols and ...

    Computer networking a top-down approach

    Computer networking a top-down approach The subject of computer networking is enormously complex, involving many concepts, protocols, and technologies that are woven together in an intricate manner. ...

    High Performance Browser Networking

    will improve networking Learn how to use Server Sent Events (SSE) for push updates, and WebSockets for XMPP chat Explore WebRTC for browser-to-browser applications such as P2P video chat Examine the ...

Global site tag (gtag.js) - Google Analytics