Merge pull request #19106 from jfindlay/split_win

Split windows commands
This commit is contained in:
Mike Place 2014-12-19 13:11:20 -07:00
commit 91edd75a03
13 changed files with 254 additions and 164 deletions

View File

@ -305,7 +305,8 @@ def _run(cmd,
env.setdefault('LC_ALL', 'C')
else:
# On Windows set the codepage to US English.
cmd = 'chcp 437 > nul & ' + cmd
if python_shell:
cmd = 'chcp 437 > nul & ' + cmd
if clean_env:
run_env = env

View File

@ -50,8 +50,8 @@ def list_():
winver = __grains__['osfullname']
for key in keys:
autoruns[key] = []
cmd = 'reg query ' + key
for line in __salt__['cmd.run'](cmd).splitlines():
cmd = ['reg', 'query', key]
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if line and line[0:4] != "HKEY" and line[0:5] != "ERROR": # Remove junk lines
autoruns[key].append(line)

View File

@ -35,8 +35,8 @@ def get_config():
profiles = {}
curr = None
cmd = 'netsh advfirewall show allprofiles'
for line in __salt__['cmd.run'](cmd).splitlines():
cmd = ['netsh', 'advfirewall', 'show', 'allprofiles']
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if not curr:
tmp = re.search('(.*) Profile Settings:', line)
if tmp:
@ -58,9 +58,8 @@ def disable():
salt '*' firewall.disable
'''
return __salt__['cmd.run'](
'netsh advfirewall set allprofiles state off'
) == 'Ok.'
cmd = ['netsh', 'advfirewall', 'set', 'allprofiles', 'state', 'off']
return __salt__['cmd.run'](cmd, python_shell=False) == 'Ok.'
def get_rule(name="all"):
@ -74,8 +73,8 @@ def get_rule(name="all"):
salt '*' firewall.get_rule "MyAppPort"
'''
ret = {}
cmd = 'netsh advfirewall firewall show rule name="{0}"'.format(name)
ret[name] = __salt__['cmd.run'](cmd)
cmd = ['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name={0}'.format(name)]
ret[name] = __salt__['cmd.run'](cmd, python_shell=False)
if ret[name].strip() == "No rules match the specified criteria.":
ret = False
@ -93,5 +92,10 @@ def add_rule(name, localport, protocol="tcp", action="allow", dir="in"):
salt '*' firewall.add_rule "test" "tcp" "8080"
'''
cmd = 'netsh advfirewall firewall add rule name="{0}" protocol={1} dir={2} localport={3} action={4}'.format(name, protocol, dir, localport, action)
return __salt__['cmd.run'](cmd) == 'Ok.'
cmd = ['netsh', 'advfirewall', 'firewall', 'add', 'rule',
'name={0}'.format(name),
'protocol={0}'.format(protocol),
'dir={0}'.format(dir),
'localport={0}'.format(localport),
'action={0}'.format(action)]
return __salt__['cmd.run'](cmd, python_shell=False) == 'Ok.'

View File

@ -27,9 +27,8 @@ def add(name, gid=None, system=False):
salt '*' group.add foo
'''
cmd = 'net localgroup {0} /add'.format(name)
ret = __salt__['cmd.run_all'](cmd)
cmd = ['net', 'localgroup', name, '/add']
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
return not ret['retcode']
@ -44,7 +43,8 @@ def delete(name):
salt '*' group.delete foo
'''
ret = __salt__['cmd.run_all']('net localgroup {0} /delete'.format(name))
cmd = ['net', 'localgroup', name, '/delete']
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
return not ret['retcode']
@ -59,7 +59,8 @@ def info(name):
salt '*' group.info foo
'''
lines = __salt__['cmd.run']('net localgroup {0}'.format(name)).splitlines()
cmd = ['net', 'localgroup', name]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
memberline = False
gr_mem = []
gr_name = ''
@ -97,7 +98,8 @@ def getent(refresh=False):
ret = []
ret2 = []
lines = __salt__['cmd.run']('net localgroup').splitlines()
cmd = ['net', 'localgroup']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
groupline = False
for line in lines:
if 'successfully' in line:
@ -109,7 +111,8 @@ def getent(refresh=False):
for item in ret:
members = []
gid = __salt__['file.group_to_gid'](item)
memberlines = __salt__['cmd.run']('net localgroup "{0}"'.format(item)).splitlines()
cmd = ['net', 'localgroup', item]
memberlines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
memberline = False
for line in memberlines:
if 'successfully' in line:

View File

@ -37,8 +37,8 @@ def _interface_configs():
'''
Return all interface configs
'''
cmd = 'netsh interface ip show config'
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['netsh', 'interface', 'ip', 'show', 'config']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
iface = ''
ip = 0
dns_flag = None
@ -108,8 +108,8 @@ def raw_interface_configs():
salt -G 'os_family:Windows' ip.raw_interface_configs
'''
cmd = 'netsh interface ip show config'
return __salt__['cmd.run'](cmd)
cmd = ['netsh', 'interface', 'ip', 'show', 'config']
return __salt__['cmd.run'](cmd, python_shell=False)
def get_all_interfaces():
@ -148,14 +148,14 @@ def is_enabled(iface):
salt -G 'os_family:Windows' ip.is_enabled 'Local Area Connection #2'
'''
cmd = 'netsh interface show interface name="{0}"'.format(iface)
cmd = ['netsh', 'interface', 'show', 'interface', 'name={0}'.format(iface)]
iface_found = False
for line in __salt__['cmd.run'](cmd).splitlines():
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if 'Connect state:' in line:
iface_found = True
return line.split()[-1] == 'Connected'
if not iface_found:
raise CommandExecutionError('Interface {0!r} not found')
raise CommandExecutionError('Interface {0!r} not found'.format(iface))
return False
@ -184,9 +184,8 @@ def enable(iface):
'''
if is_enabled(iface):
return True
__salt__['cmd.run'](
'netsh interface set interface "{0}" admin=ENABLED'.format(iface)
)
cmd = ['netsh', 'interface', 'set', 'interface', iface, 'admin=ENABLED']
__salt__['cmd.run'](cmd, python_shell=False)
return is_enabled(iface)
@ -202,9 +201,8 @@ def disable(iface):
'''
if is_disabled(iface):
return True
__salt__['cmd.run'](
'netsh interface set interface "{0}" admin=DISABLED'.format(iface)
)
cmd = ['netsh', 'interface', 'set', 'interface', iface, 'admin=DISABLED']
__salt__['cmd.run'](cmd, python_shell=False)
return is_disabled(iface)
@ -278,19 +276,19 @@ def set_static_ip(iface, addr, gateway=None, append=False):
'{1!r}'.format(addr, iface)
)
# Do not use raw string formatting (ex. {1!r}) for interface name, as the
# windows command shell does not like single quotes.
cmd = (
'netsh interface ip {0} address name="{1}" {2} '
'address={3}{4}'.format(
'add' if append else 'set',
iface,
'' if append else 'source=static',
addr,
' gateway={0}'.format(gateway) if gateway else '',
)
)
result = __salt__['cmd.run_all'](cmd)
cmd = ['netsh', 'interface', 'ip']
if append:
cmd.append('add')
else:
cmd.append('set')
cmd.extend(['address', 'name={0}'.format(iface)])
if not append:
cmd.append('source=static')
cmd.append('address={0}'.format(addr))
if gateway:
cmd.append('gateway={0}'.format(gateway))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Unable to set IP address: {0}'.format(result['stderr'])
@ -316,8 +314,8 @@ def set_dhcp_ip(iface):
salt -G 'os_family:Windows' ip.set_dhcp_ip 'Local Area Connection'
'''
cmd = 'netsh interface ip set address "{0}" dhcp'.format(iface)
__salt__['cmd.run'](cmd)
cmd = ['netsh', 'interface', 'ip', 'set', 'address', iface, 'dhcp']
__salt__['cmd.run'](cmd, python_shell=False)
return {'Interface': iface, 'DHCP enabled': 'Yes'}
@ -335,15 +333,16 @@ def set_static_dns(iface, *addrs):
addr_index = 1
for addr in addrs:
if addr_index == 1:
cmd = 'netsh int ip set dns "{0}" static {1} primary'.format(
iface,
addrs[0],
)
__salt__['cmd.run'](cmd)
cmd = ['netsh', 'int', 'ip', 'set', 'dns',
iface, 'static', addrs[0], 'primary']
__salt__['cmd.run'](cmd, python_shell=False)
addr_index = addr_index + 1
else:
cmd = 'netsh interface ip add dns name="{0}" addr="{1}" index={2}'
__salt__['cmd.run'](cmd.format(iface, addr, addr_index))
cmd = ['netsh', 'interface', 'ip', 'add', 'dns',
'name={0}'.format(iface),
'addr={0}'.format(addr),
'index={0}'.format(addr_index)]
__salt__['cmd.run'](cmd, python_shell=False)
addr_index = addr_index + 1
return {'Interface': iface, 'DNS Server': addrs}
@ -358,8 +357,8 @@ def set_dhcp_dns(iface):
salt -G 'os_family:Windows' ip.set_dhcp_dns 'Local Area Connection'
'''
cmd = 'netsh interface ip set dns "{0}" dhcp'.format(iface)
__salt__['cmd.run'](cmd)
cmd = ['netsh', 'interface', 'ip', 'set', 'dns', iface, 'dhcp']
__salt__['cmd.run'](cmd, python_shell=False)
return {'Interface': iface, 'DNS Server': 'DHCP'}
@ -391,7 +390,8 @@ def get_default_gateway():
try:
return next(iter(
x.split()[-1] for x in __salt__['cmd.run'](
'netsh interface ip show config'
['netsh', 'interface', 'ip', 'show', 'config'],
python_shell=False
).splitlines()
if 'Default Gateway:' in x
))

View File

@ -41,8 +41,8 @@ def ping(host):
salt '*' network.ping archlinux.org
'''
cmd = 'ping -n 4 {0}'.format(salt.utils.network.sanitize_host(host))
return __salt__['cmd.run'](cmd)
cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)]
return __salt__['cmd.run'](cmd, python_shell=False)
def netstat():
@ -56,8 +56,8 @@ def netstat():
salt '*' network.netstat
'''
ret = []
cmd = 'netstat -nao'
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['netstat', '-nao']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if line.startswith(' TCP'):
@ -88,8 +88,8 @@ def traceroute(host):
salt '*' network.traceroute archlinux.org
'''
ret = []
cmd = 'tracert {0}'.format(salt.utils.network.sanitize_host(host))
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['tracert', salt.utils.network.sanitize_host(host)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if ' ' not in line:
continue
@ -143,8 +143,8 @@ def nslookup(host):
'''
ret = []
addresses = []
cmd = 'nslookup {0}'.format(salt.utils.network.sanitize_host(host))
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['nslookup', salt.utils.network.sanitize_host(host)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if addresses:
# We're in the last block listing addresses
@ -176,8 +176,8 @@ def dig(host):
salt '*' network.dig archlinux.org
'''
cmd = 'dig {0}'.format(salt.utils.network.sanitize_host(host))
return __salt__['cmd.run'](cmd)
cmd = ['dig', salt.utils.network.sanitize_host(host)]
return __salt__['cmd.run'](cmd, python_shell=False)
def interfaces_names():

View File

@ -40,13 +40,19 @@ def set_servers(*servers):
if not __salt__['service.status'](service_name):
if not __salt__['service.start'](service_name):
return False
ret = __salt__['cmd.run'](
'W32tm /config /syncfromflags:manual /manualpeerlist:"{0}" &&'
'W32tm /config /reliable:yes && W32tm /config /update'
.format(' '.join(servers))
)
server_cmd = ['W32tm', '/config', '/syncfromflags:manual',
'/manualpeerlist:{0}'.format(' '.join(servers))]
reliable_cmd = ['W32tm', '/config', '/reliable:yes']
update_cmd = ['W32tm', '/config', '/update']
for cmd in server_cmd, reliable_cmd, update_cmd:
ret = __salt__['cmd.run'](cmd, python_shell=False)
if 'command completed successfully' not in ret:
return False
__salt__['service.restart'](service_name)
return 'command completed successfully' in ret
return True
def get_servers():
@ -59,8 +65,8 @@ def get_servers():
salt '*' ntp.get_servers
'''
cmd = 'w32tm /query /configuration'
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['w32tm', '/query', '/configuration']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if 'NtpServer' in line:
_, ntpsvrs = line.rstrip(' (Local)').split(':', 1)

View File

@ -314,7 +314,7 @@ $msi.GetType().InvokeMember('ProductsEx', 'GetProperty', $null, $msi, ('', 's-1-
| Write-host
'''.replace('\n', ' ') # make this a one-liner
ret = __salt__['cmd.run_all'](ps, shell='powershell')
ret = __salt__['cmd.run_all'](ps, shell='powershell', python_shell=True)
# sometimes the powershell reflection fails on a single product,
# giving us a non-zero return code AND useful output. Ignore RC
# and just try to process stdout, which should empty if the cmd
@ -565,12 +565,14 @@ def install(name=None, refresh=False, pkgs=None, saltenv='base', **kwargs):
cached_pkg = cached_pkg.replace('/', '\\')
msiexec = pkginfo[version_num].get('msiexec')
install_flags = '{0} {1}'.format(pkginfo[version_num]['install_flags'], options and options.get('extra_install_flags') or "")
cmd = '{msiexec}"{cached_pkg}" {install_flags}'.format(
msiexec='msiexec /i ' if msiexec else '',
cached_pkg=cached_pkg,
install_flags=install_flags
)
__salt__['cmd.run'](cmd, output_loglevel='trace')
cmd = []
if msiexec:
cmd.extend('msiexec', '/i')
cmd.append(cached_pkg)
cmd.extend(install_flags.split())
__salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
@ -662,11 +664,19 @@ def remove(name=None, pkgs=None, version=None, extra_uninstall_flags=None, **kwa
if not os.path.exists(os.path.expandvars(cached_pkg)) \
and '(x86)' in cached_pkg:
cached_pkg = cached_pkg.replace('(x86)', '')
cmd = '"' + str(os.path.expandvars(
cached_pkg)) + '"' + str(pkginfo[version].get('uninstall_flags', '') + " " + (extra_uninstall_flags or ''))
expanded_cached_pkg = str(os.path.expandvars(cached_pkg))
uninstall_flags = str(pkginfo[version].get('uninstall_flags', ''))
cmd = []
if pkginfo[version].get('msiexec'):
cmd = 'msiexec /x ' + cmd
__salt__['cmd.run'](cmd, output_loglevel='trace')
cmd.extend(['msiexec', '/x'])
cmd.append(expanded_cached_pkg)
cmd.extend(uninstall_flags.split())
if extra_uninstall_flags:
cmd.extend(str(extra_uninstall_flags).split())
__salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()

View File

@ -5,9 +5,12 @@ Windows Service module.
# Import python libs
import salt.utils
from subprocess import list2cmdline
import time
import logging
try:
from shlex import quote as _cmd_quote # pylint: disable=E0611
except ImportError:
from pipes import quote as _cmd_quote
log = logging.getLogger(__name__)
@ -38,7 +41,9 @@ def has_powershell():
salt '*' service.has_powershell
'''
return 'powershell' in __salt__['cmd.run']('where powershell')
return 'powershell' in __salt__['cmd.run'](
['where', 'powershell'], python_shell=False
)
def get_enabled():
@ -54,13 +59,13 @@ def get_enabled():
if has_powershell():
cmd = 'Get-WmiObject win32_service | where {$_.startmode -eq "Auto"} | select-object name'
lines = __salt__['cmd.run'](cmd, shell='POWERSHELL').splitlines()
lines = __salt__['cmd.run'](cmd, shell='POWERSHELL', python_shell=True).splitlines()
return sorted([line.strip() for line in lines[3:]])
else:
ret = set()
services = []
cmd = list2cmdline(['sc', 'query', 'type=', 'service', 'state=', 'all', 'bufsize=', str(BUFFSIZE)])
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['sc', 'query', 'type=', 'service', 'state=', 'all', 'bufsize=', str(BUFFSIZE)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if 'SERVICE_NAME:' in line:
comps = line.split(':', 1)
@ -68,8 +73,8 @@ def get_enabled():
continue
services.append(comps[1].strip())
for service in services:
cmd2 = list2cmdline(['sc', 'qc', service, str(BUFFSIZE)])
lines = __salt__['cmd.run'](cmd2).splitlines()
cmd2 = ['sc', 'qc', service, str(BUFFSIZE)]
lines = __salt__['cmd.run'](cmd2, python_shell=False).splitlines()
for line in lines:
if 'AUTO_START' in line:
ret.add(service)
@ -88,13 +93,13 @@ def get_disabled():
'''
if has_powershell():
cmd = 'Get-WmiObject win32_service | where {$_.startmode -ne "Auto"} | select-object name'
lines = __salt__['cmd.run'](cmd, shell='POWERSHELL').splitlines()
lines = __salt__['cmd.run'](cmd, shell='POWERSHELL', python_shell=True).splitlines()
return sorted([line.strip() for line in lines[3:]])
else:
ret = set()
services = []
cmd = list2cmdline(['sc', 'query', 'type=', 'service', 'state=', 'all', 'bufsize=', str(BUFFSIZE)])
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['sc', 'query', 'type=', 'service', 'state=', 'all', 'bufsize=', str(BUFFSIZE)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if 'SERVICE_NAME:' in line:
comps = line.split(':', 1)
@ -102,8 +107,8 @@ def get_disabled():
continue
services.append(comps[1].strip())
for service in services:
cmd2 = list2cmdline(['sc', 'qc', service, BUFFSIZE])
lines = __salt__['cmd.run'](cmd2).splitlines()
cmd2 = ['sc', 'qc', service, BUFFSIZE]
lines = __salt__['cmd.run'](cmd2, python_shell=False).splitlines()
for line in lines:
if 'DEMAND_START' in line:
ret.add(service)
@ -177,8 +182,8 @@ def get_service_name(*args):
ret = {}
services = []
display_names = []
cmd = list2cmdline(['sc', 'query', 'type=', 'service', 'state=', 'all', 'bufsize=', str(BUFFSIZE)])
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['sc', 'query', 'type=', 'service', 'state=', 'all', 'bufsize=', str(BUFFSIZE)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if 'SERVICE_NAME:' in line:
comps = line.split(':', 1)
@ -212,8 +217,8 @@ def start(name):
salt '*' service.start <service name>
'''
cmd = list2cmdline(['net', 'start', name])
return not __salt__['cmd.retcode'](cmd)
cmd = ['net', 'start', name]
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def stop(name):
@ -230,8 +235,8 @@ def stop(name):
# up if the service takes too long to stop with a misleading
# "service could not be stopped" message and RC 0.
cmd = list2cmdline(['net', 'stop', name])
res = __salt__['cmd.run'](cmd)
cmd = ['net', 'stop', name]
res = __salt__['cmd.run'](cmd, python_shell=False)
if 'service was stopped' in res:
return True
@ -258,8 +263,8 @@ def restart(name):
salt '*' service.restart <service name>
'''
if has_powershell():
cmd = 'Restart-Service {0}'.format(name)
return not __salt__['cmd.retcode'](cmd, shell='powershell')
cmd = 'Restart-Service {0}'.format(_cmd_quote(name))
return not __salt__['cmd.retcode'](cmd, shell='powershell', python_shell=True)
return stop(name) and start(name)
@ -275,8 +280,8 @@ def status(name, sig=None):
salt '*' service.status <service name> [service signature]
'''
cmd = list2cmdline(['sc', 'query', name])
statuses = __salt__['cmd.run'](cmd).splitlines()
cmd = ['sc', 'query', name]
statuses = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in statuses:
if 'RUNNING' in line:
return True
@ -295,8 +300,8 @@ def getsid(name):
salt '*' service.getsid <service name>
'''
cmd = list2cmdline(['sc', 'showsid', name])
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['sc', 'showsid', name]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if 'SERVICE SID:' in line:
comps = line.split(':', 1)
@ -316,8 +321,8 @@ def enable(name, **kwargs):
salt '*' service.enable <service name>
'''
cmd = list2cmdline(['sc', 'config', name, 'start=', 'auto'])
return not __salt__['cmd.retcode'](cmd)
cmd = ['sc', 'config', name, 'start=', 'auto']
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def disable(name, **kwargs):
@ -330,8 +335,8 @@ def disable(name, **kwargs):
salt '*' service.disable <service name>
'''
cmd = list2cmdline(['sc', 'config', name, 'start=', 'demand'])
return not __salt__['cmd.retcode'](cmd)
cmd = ['sc', 'config', name, 'start=', 'demand']
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def enabled(name):

View File

@ -51,7 +51,7 @@ def set_password(name, password):
salt '*' shadow.set_password root mysecretpassword
'''
cmd = 'net user {0} {1}'.format(name, password)
ret = __salt__['cmd.run_all'](cmd)
cmd = ['net', 'user', name, password]
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
return not ret['retcode']

View File

@ -6,6 +6,11 @@ Support for reboot, shutdown, etc
# Import python libs
import logging
import re
import datetime
try:
from shlex import quote as _cmd_quote # pylint: disable=E0611
except ImportError:
from pipes import quote as _cmd_quote
# Import salt libs
import salt.utils
@ -49,8 +54,8 @@ def init(runlevel):
salt '*' system.init 3
'''
#cmd = 'init {0}'.format(runlevel)
#ret = __salt__['cmd.run'](cmd)
#cmd = ['init', runlevel]
#ret = __salt__['cmd.run'](cmd, python_shell=False)
#return ret
# TODO: Create a mapping of runlevels to
@ -82,8 +87,8 @@ def reboot(timeout=5):
salt '*' system.reboot
'''
cmd = 'shutdown /r /t {0}'.format(timeout)
ret = __salt__['cmd.run'](cmd)
cmd = ['shutdown', '/r', '/t', '{0}'.format(timeout)]
ret = __salt__['cmd.run'](cmd, python_shell=False)
return ret
@ -97,8 +102,8 @@ def shutdown(timeout=5):
salt '*' system.shutdown
'''
cmd = 'shutdown /s /t {0}'.format(timeout)
ret = __salt__['cmd.run'](cmd)
cmd = ['shutdown', '/s', '/t', '{0}'.format(timeout)]
ret = __salt__['cmd.run'](cmd, python_shell=False)
return ret
@ -112,8 +117,8 @@ def shutdown_hard():
salt '*' system.shutdown_hard
'''
cmd = 'shutdown /p /f'
ret = __salt__['cmd.run'](cmd)
cmd = ['shutdown', '/p', '/f']
ret = __salt__['cmd.run'](cmd, python_shell=False)
return ret
@ -128,9 +133,8 @@ def set_computer_name(name):
salt 'minion-id' system.set_computer_name 'DavesComputer'
'''
cmd = ('wmic computersystem where name="%COMPUTERNAME%"'
' call rename name="{0}"')
log.debug('Attempting to change computer name. Cmd is: '.format(cmd))
ret = __salt__['cmd.run'](cmd.format(name))
' call rename name="{0}"'.format(name))
ret = __salt__['cmd.run'](cmd, python_shell=True)
if 'ReturnValue = 0;' in ret:
ret = {'Computer Name': {'Current': get_computer_name()}}
pending = get_pending_computer_name()
@ -155,9 +159,10 @@ def get_pending_computer_name():
salt 'minion-id' system.get_pending_computer_name
'''
current = get_computer_name()
cmd = ('reg query HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control'
'\\ComputerName\\ComputerName /v ComputerName')
output = __salt__['cmd.run'](cmd)
cmd = ['reg', 'query',
'HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName',
'/v', 'ComputerName']
output = __salt__['cmd.run'](cmd, python_shell=False)
pending = None
for line in output.splitlines():
try:
@ -187,8 +192,8 @@ def get_computer_name():
salt 'minion-id' system.get_computer_name
'''
cmd = 'net config server'
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['net', 'config', 'server']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if 'Server Name' in line:
_, srv_name = line.split('Server Name', 1)
@ -206,8 +211,8 @@ def set_computer_desc(desc):
salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!'
'''
cmd = u'net config server /srvcomment:"{0}"'.format(salt.utils.sdecode(desc))
__salt__['cmd.run'](cmd)
cmd = ['net', 'config', 'server', u'/srvcomment:{0}'.format(salt.utils.sdecode(desc))]
__salt__['cmd.run'](cmd, python_shell=False)
return {'Computer Description': get_computer_desc()}
set_computer_description = set_computer_desc
@ -223,8 +228,8 @@ def get_computer_desc():
salt 'minion-id' system.get_computer_desc
'''
cmd = 'net config server'
lines = __salt__['cmd.run'](cmd).splitlines()
cmd = ['net', 'config', 'server']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if 'Server Comment' in line:
_, desc = line.split('Server Comment', 1)
@ -287,8 +292,12 @@ def join_domain(
join_options = 1
cmd = ('wmic /interactive:off ComputerSystem Where '
'name="%computername%" call JoinDomainOrWorkgroup FJoinOptions={0} '
'Name="{1}" UserName="{2}" Password="{3}"'
).format(join_options, domain, username, password)
'Name={1} UserName={2} Password={3}'
).format(
join_options,
_cmd_quote(domain),
_cmd_quote(username),
_cmd_quote(password))
if account_ou:
# contrary to RFC#2253, 2.1, 'wmic' requires a ; as a RDN separator
# for the DN
@ -296,7 +305,7 @@ def join_domain(
add_ou = ' AccountOU="{0}"'.format(account_ou)
cmd = cmd + add_ou
ret = __salt__['cmd.run'](cmd)
ret = __salt__['cmd.run'](cmd, python_shell=True)
if 'ReturnValue = 0;' in ret:
return {'Domain': domain}
return_values = {
@ -316,6 +325,45 @@ def join_domain(
return False
def _validate_datetime(newdatetime, valid_formats):
'''
Validate `newdatetime` against list of date/time formats understood by
windows.
'''
for dt_format in valid_formats:
try:
datetime.datetime.strptime(newdatetime, dt_format)
return True
except ValueError:
continue
return False
def _validate_time(newtime):
'''
Validate `newtime` against list of time formats understood by windows.
'''
valid_time_formats = [
'%I:%M:%S %p',
'%I:%M %p',
'%H:%M:%S',
'%H:%M'
]
return _validate_datetime(newtime, valid_time_formats)
def _validate_date(newdate):
'''
Validate `newdate` against list of date formats understood by windows.
'''
valid_date_formats = [
'%Y-%m-%d',
'%m/%d/%y',
'%y/%m/%d'
]
return _validate_datetime(newdate, valid_date_formats)
def get_system_time():
'''
Get the Windows system time
@ -327,7 +375,7 @@ def get_system_time():
salt '*' system.get_system_time
'''
cmd = 'time /T'
return __salt__['cmd.run'](cmd)
return __salt__['cmd.run'](cmd, python_shell=True)
def set_system_time(newtime):
@ -340,8 +388,10 @@ def set_system_time(newtime):
salt '*' system.set_system_time '11:31:15 AM'
'''
if not _validate_time(newtime):
return False
cmd = 'time {0}'.format(newtime)
return not __salt__['cmd.retcode'](cmd)
return not __salt__['cmd.retcode'](cmd, python_shell=True)
def get_system_date():
@ -355,7 +405,7 @@ def get_system_date():
salt '*' system.get_system_date
'''
cmd = 'date /T'
return __salt__['cmd.run'](cmd)
return __salt__['cmd.run'](cmd, python_shell=True)
def set_system_date(newdate):
@ -368,8 +418,10 @@ def set_system_date(newdate):
salt '*' system.set_system_date '03-28-13'
'''
if not _validate_date(newdate):
return False
cmd = 'date {0}'.format(newdate)
return not __salt__['cmd.retcode'](cmd)
return not __salt__['cmd.retcode'](cmd, python_shell=True)
def start_time_service():

View File

@ -471,7 +471,7 @@ def get_zone():
salt '*' timezone.get_zone
'''
winzone = __salt__['cmd.run']('tzutil /g')
winzone = __salt__['cmd.run'](['tzutil', '/g'], python_shell=False)
for key in LINTOWIN:
if LINTOWIN[key] == winzone:
return key
@ -490,9 +490,9 @@ def get_offset():
salt '*' timezone.get_offset
'''
string = False
zone = __salt__['cmd.run']('tzutil /g')
zone = __salt__['cmd.run'](['tzutil', '/g'], python_shell=False)
prev = ''
for line in __salt__['cmd.run']('tzutil /l').splitlines():
for line in __salt__['cmd.run'](['tzutil', '/l'], python_shell=False).splitlines():
if zone == line:
string = prev
break
@ -539,7 +539,8 @@ def set_zone(timezone):
salt '*' timezone.set_zone 'America/Denver'
'''
return __salt__['cmd.retcode']('tzutil /s "{0}"'.format(LINTOWIN[timezone])) == 0
cmd = ['tzutil', '/s', LINTOWIN[timezone]]
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def zone_compare(timezone):
@ -554,7 +555,8 @@ def zone_compare(timezone):
salt '*' timezone.zone_compare 'America/Denver'
'''
return __salt__['cmd.run']('tzutil /g') == LINTOWIN[timezone]
cmd = ['tzutil', '/g']
return __salt__['cmd.run'](cmd, python_shell=False) == LINTOWIN[timezone]
def get_hwclock():

View File

@ -62,9 +62,11 @@ def add(name,
salt '*' user.add name password
'''
if password:
ret = __salt__['cmd.run_all']('net user {0} {1} /add /y'.format(name, password))
cmd = ['net', 'user', name, password, '/add', '/y']
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
else:
ret = __salt__['cmd.run_all']('net user {0} /add'.format(name))
cmd = ['net', 'user', name, '/add']
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if groups:
chgroups(name, groups)
if fullname:
@ -90,7 +92,8 @@ def delete(name,
salt '*' user.delete name
'''
ret = __salt__['cmd.run_all']('net user {0} /delete'.format(name))
cmd = ['net', 'user', name, '/delete']
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
return ret['retcode'] == 0
@ -105,7 +108,9 @@ def setpassword(name, password):
salt '*' user.setpassword name password
'''
ret = __salt__['cmd.run_all'](
'net user {0} {1}'.format(name, password), output_loglevel='quiet'
['net', 'user', name, password],
output_loglevel='quiet',
python_shell=False
)
return ret['retcode'] == 0
@ -126,7 +131,8 @@ def addgroup(name, group):
if group in user['groups']:
return True
ret = __salt__['cmd.run_all'](
'net localgroup {0} {1} /add'.format(group, name)
['net', 'localgroup', group, name, '/add'],
python_shell=False
)
return ret['retcode'] == 0
@ -150,7 +156,8 @@ def removegroup(name, group):
return True
ret = __salt__['cmd.run_all'](
'net localgroup {0} {1} /delete'.format(group, name)
['net', 'localgroup', group, name, '/delete'],
python_shell=False
)
return ret['retcode'] == 0
@ -173,8 +180,8 @@ def chhome(name, home):
if home == pre_info['home']:
return True
if __salt__['cmd.retcode']('net user {0} /homedir:{1}'.format(
name, home)) != 0:
cmd = ['net', 'user', name, '/homedir:{0}'.format(home)]
if __salt__['cmd.retcode'](cmd, python_shell=False) != 0:
return False
post_info = info(name)
@ -201,8 +208,8 @@ def chprofile(name, profile):
if profile == pre_info['profile']:
return True
if __salt__['cmd.retcode']('net user {0} /profilepath:{1}'.format(
name, profile)) != 0:
cmd = ['net', 'user', name, '/profilepath:{0}'.format(profile)]
if __salt__['cmd.retcode'](cmd, python_shell=False) != 0:
return False
post_info = info(name)
@ -229,8 +236,8 @@ def chfullname(name, fullname):
if fullname == pre_info['fullname']:
return True
if __salt__['cmd.retcode']('net user {0} /fullname:"{1}"'.format(
name, fullname)) != 0:
cmd = ['net', 'user', name, '/fullname:{0}'.format(fullname)]
if __salt__['cmd.retcode'](cmd, python_shell=False) != 0:
return False
post_info = info(name)
@ -262,14 +269,14 @@ def chgroups(name, groups, append=False):
if not append:
for group in ugrps:
if group not in groups:
__salt__['cmd.retcode'](
'net localgroup {0} {1} /delete'.format(group, name))
cmd = ['net', 'localgroup', group, name, '/delete']
__salt__['cmd.retcode'](cmd, python_shell=False)
for group in groups:
if group in ugrps:
continue
__salt__['cmd.retcode'](
'net localgroup {0} {1} /add'.format(group, name))
cmd = ['net', 'localgroup', group, name, '/add']
__salt__['cmd.retcode'](cmd, python_shell=False)
agrps = set(list_groups(name))
return len(ugrps - agrps) == 0