#!/usr/bin/python3

__doc__ = """Execute a command on Windows remotely.

A simple wrapper around pywinrm with a command-line interface
similar to winexe based on Samba <https://sourceforge.net/projects/winexe/>."""

# Copyright (C) 2016 Ivan Zakharyaschev <imz@altlinux.org>
# (Licensed under the same terms of an MIT license as pywinrm itself.)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import argparse

argparser = argparse.ArgumentParser(
                description=__doc__,
                epilog='Example: winexe -U Administrator%password //HOST [--] ipconfig /all')
def parseUser(user_arg):
    #(user,sep,password) = user_arg.partition('%')
    i = user_arg.index('%') # raises an exception
    (user,password) = (user_arg[0:i],user_arg[i+1:])
    return (user,password)
argparser.add_argument('-U', '--user',
                       dest='user',
                       metavar='USER%PASSWORD',
                       type=parseUser,
                       help='username and optional password for login')
def parseHost(host_arg):
    if host_arg.startswith('//'):
        return host_arg[2:]
    else:
        raise argparse.ArgumentTypeError('A host must start with //: %s' % host_arg)
argparser.add_argument('host',
                       metavar='//HOST',
                       help='remote host specification')
argparser.add_argument('cmd',
                       help='the executable command to be run remotely')
argparser.add_argument('args',
                       nargs=argparse.REMAINDER,
                       metavar='arg',
                       help='the args for cmd')

def winrm_kwargs(args):
    kwargs = dict([])
    if args.user != None:
        kwargs['auth'] = args.user
    return kwargs

args = argparser.parse_args()
import sys
import winrm
s = winrm.Session(parseHost(args.host), **winrm_kwargs(args))
r = s.run_cmd(args.cmd, args.args)
print(s.std_err,file=sys.stderr)
print(s.std_out,file=sys.stdout)
sys.exit(s.status_code)
