#!/bin/env python
from twisted.internet import reactor, protocol
import nmb
import sys


def disaster(failure):
    print 'FAILED. Reason: ',failure
    reactor.stop()


class MySession(nmb.NetBIOSSession):
    def connectionMade(self):
        print 'connection made'
        d = self.establishSession(self.factory.localName,
                                  self.factory.remoteName)
        d.addCallback(self.gotSession)
        d.addErrback(disaster)

    def gotSession(self, data):
        print 'got session', data
        #self.loseConnection()
        reactor.stop()

class MyNetBIOSFactory(protocol.ClientFactory):
    protocol = MySession
    
    def __init__(self, localName, remoteName):
        self.localName = localName
        self.remoteName = remoteName
        
    def startedConnecting(self, connector):
        print 'Started to connect.'
    
    def clientConnectionLost(self, connector, reason):
        print 'Lost connection.  Reason:', reason
        reactor.stop()
    
    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason
        reactor.stop()

def main(local, remote, remoteIP):
    f = MyNetBIOSFactory(local, remote)
    reactor.connectTCP(remoteIP, 139, f)
    reactor.run()


if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2], sys.argv[3])
