#!/usr/bin/env python
# -*- mode: python; tab-width: 4 -*-
# $Id: smblistshare,v 1.4 2001/11/06 16:17:28 miketeo Exp $
#
# Copyright (C) 2001 Michael Teo <michaelteo@bigfoot.com>
# smblistshare - list the shared devices on a SMB machine
#
# This software is provided 'as-is', without any express or implied warranty. 
# In no event will the author be held liable for any damages arising from the 
# use of this software.
#
# Permission is granted to anyone to use this software for any purpose, 
# including commercial applications, and to alter it and redistribute it 
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not 
#    claim that you wrote the original software. If you use this software 
#    in a product, an acknowledgment in the product documentation would be
#    appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be 
#    misrepresented as being the original software.
#
# 3. This notice cannot be removed or altered from any source distribution.
#

import os, sys, string, getopt, getpass
import smb, nmb

VERSION = '0.1.0'



DEVICE_TYPE_NAMES = { smb.SHARED_DISK: 'Disk',
                      smb.SHARED_PRINT_QUEUE: 'Printer',
                      smb.SHARED_DEVICE: 'Device',
                      smb.SHARED_IPC: 'IPC'
                      }


def print_usage_screen():
    print 'Usage: smblistshare [options]... <NetBIOS name> ...'
    print 'List the shared devices on a SMB machine'
    print
    print 'Options:'
    print '  -u user               connect using this user'
    print '  -B broadcast addr     the address to use for broadcasts'
    print '  -I remote IP addr     connect to this IP address for remote host'
    print '  --help                display this help and exit'
    print '  --version             output version information and exit'
    print 



def main():
    user = ''
    remote_ip_addr = None
    netbios = nmb.NetBIOS()
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'hu:B:I:', [ 'version' ])
        for k, v in optlist:
            if k == '-B':
                netbios.set_broadcastaddr(v)
            elif k == '-u':
                user = v
            elif k == '-I':
                remote_ip_addr = v
            elif k == '--version':
                print 'smblistshare version', VERSION,'(smb:', smb.CVS_REVISION, 'and nmb:', nmb.CVS_REVISION, ')'
                return
            elif k == '-h':
                raise getopt.error
    except getopt.error:
        print_usage_screen()
        return

    if not args:
        print_usage_screen()
        return
       
    for dest_name in args:
        if not remote_ip_addr:
            try:
                addrs = netbios.gethostbyname(dest_name)
                if not addrs:
                    return
            except nmb.NetBIOSTimeout:
                print 'Warning: Cannot resolve', dest_name
                return
            except nmb.NetBIOSError, ex:
                print ex[0], nmb.strerror(ex[1], ex[2])[1]
                return

            print 'Connecting to', dest_name, 'using', addrs[0].get_ip()
            remote = smb.SMB(dest_name, addrs[0].get_ip())
        else:
            print 'Connecting to', dest_name, 'using', remote_ip_addr
            remote = smb.SMB(dest_name, remote_ip_addr)
        
        if remote.is_login_required():
            if not user:
                user = getpass.getuser()
            password = getpass.getpass('Password for ' + user + '@' + dest_name + ': ')
            remote.login(user, password)
                
        print
        devices = remote.list_shared()
        if not devices:
            print 'No shared devices found'
        else:
            print 'Type   ', string.ljust('Share Name', 15), 'Comments'
            print '=======', '=' * 15, '========'
            for dev in devices:
                print string.ljust(DEVICE_TYPE_NAMES.get(dev.get_type(), 'Unknown'), 7), string.ljust(dev.get_name(), 15), dev.get_comment()
        print
    


if __name__ == '__main__':
    try:
        main()
    except nmb.NetBIOSError, ex:
        _, err_msg = nmb.strerror(ex[1], ex[2])
        print ex[0], ':', err_msg
    except smb.SessionError, ex:
        _, err_msg = smb.strerror(ex[1], ex[2])
        print ex[0], ':', err_msg
    except KeyboardInterrupt:
        pass

    
