#!/usr/bin/env python3
# smbping -- attempt to connect to an SMB server with Kerberos authentication

import argparse
from pprint import pprint
import smbclient
import stat

parser = argparse.ArgumentParser()
parser.add_argument("-k", "--kerberos", action="store_true",
                    help="insist on Kerberos authentication")
parser.add_argument("target", nargs="+",
                    help="server hostname to ping, or UNC path to list")
args = parser.parse_args()

if args.kerberos:
    smbclient.ClientConfig(auth_protocol="kerberos")

for target in args.target:
    target = target.replace("/", "\\")
    if target.startswith(r"\\"):
        try:
            result = smbclient.stat(target)
            if stat.S_ISDIR(result.st_mode):
                result = smbclient.listdir(target)
                print("Contents of %s:" % target)
                pprint(sorted(result))
            else:
                result = smbclient.open_file(target, "r", share_access="rwd").read()
                print("Contents of %s:" % target)
                print(result)
        except Exception as e:
            exit("Failed to connect to \"%s\": %r" % (target, e))
    else:
        try:
            sess = smbclient.register_session(target)
            print("Connected via SMB to \"%s\" using %r." % (sess.connection.server_name,
                                                             sess.auth_protocol))
        except Exception as e:
            exit("Failed to connect to \"%s\": %r" % (target, e))

# It would be useful to list available shares when "\\foo" is provided, but
# apparently this involves some relatively complex RPC to the SRVSVC pipe,
# rather than being directly available at SMB level.
