本文整理汇总了Python中winrm.protocol.Protocol.run_command方法的典型用法代码示例。如果您正苦于以下问题:Python Protocol.run_command方法的具体用法?Python Protocol.run_command怎么用?Python Protocol.run_command使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类winrm.protocol.Protocol
的用法示例。
在下文中一共展示了Protocol.run_command方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
class Session(object):
#TODO implement context manager methods
def __init__(self, target, auth, transport='plaintext'):
username, password = auth
self.url = self._build_url(target, transport)
self.protocol = Protocol(self.url, transport=transport, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
@staticmethod
def _build_url(target, transport):
match = re.match(
'(?i)^((?P<scheme>http[s]?)://)?(?P<host>[0-9a-z-_]+)(:(?P<port>\d+))?(?P<path>(/)?(wsman)?)?', target)
scheme = match.group('scheme')
if not scheme:
scheme = 'https' if transport == 'ssl' else 'http' # TODO do we have anything other than HTTP/HTTPS
host = match.group('host')
port = match.group('port')
if not port:
port = 5986 if transport == 'ssl' else 5985
path = match.group('path')
if not path:
path = 'wsman'
return '{0}://{1}:{2}/{3}'.format(scheme, host, port, path.lstrip('/'))
示例2: _try_winrm
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
def _try_winrm(self, node):
ip = node.private_ips[0]
p = Protocol(
endpoint='http://%s:5985/wsman' % ip, # RFC 2732
transport='ntlm',
username=self.username,
password=self.secret,
server_cert_validation='ignore')
shell_id = p.open_shell()
command_id = p.run_command(shell_id, 'ipconfig', ['/all'])
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
return std_out
示例3: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth, transport = "plaintext"):
#TODO convert short urls into well-formed endpoint
self.protocol = Protocol(url, auth, transport)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
示例4: run
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
def run(self, host, password, username='Administrator',
port=5732, secure=True):
proto = 'https' if secure else 'http'
p = Protocol(
endpoint='%s://%s:%i/wsman' % (proto, host, port), # RFC 2732?
transport='ntlm',
username=username,
password=password,
server_cert_validation='ignore')
shell_id = p.open_shell()
command_id = p.run_command(shell_id, 'ipconfig', ['/all'])
std_out, std_err, status_code = p.get_command_output(shell_id,
command_id)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
return {'stdout': std_out, 'stderr': std_err}
示例5: _winrm_commands
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
def _winrm_commands(self, node, commands):
ip = node.private_ips[0]
p = Protocol(
endpoint='http://%s:5985/wsman' % ip, # RFC 2732
transport='ntlm',
username=self.username,
password=self.secret,
server_cert_validation='ignore')
shell_id = p.open_shell()
std_out_logs = []
std_err_logs = []
# run the commands in sequence.
for command, params in commands:
command_id = p.run_command(shell_id, command, params)
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
std_out_logs.append(std_out)
std_err_logs.append(std_err)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
return std_out_logs, std_err_logs
示例6: BaseWinRMClient
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
class BaseWinRMClient(BaseClient):
def __init__(self, host=None):
"""
Initialization
@param host: IP address or host name to connect to
@type host: string
"""
self.host = host
self.connection = None
self.shell_id = None
def connect(self, username=None, password=None):
"""
Attempts to connect to a remote server via WinRM.
@param username: Username to be used for the WinRM connection
@type username: string
@param password: Password to be used for the WinRM connection
@type password: string
"""
endpoint = "http://{host}:5985/wsman".format(host=self.host)
try:
self.connection = Protocol(endpoint=endpoint, username=username, password=password)
# Doing a wide catch as the exception handling in WinRM is not
# very thorough or specific
except Exception as exception:
self._log(exception.message)
else:
self.shell_id = self.connection.open_shell()
def is_connected(self):
"""
Checks to see if a WinRM connection exists.
@rtype: bool
"""
return self.connection is not None and self.shell_id is not None
def _format_response(self, std_out=None, std_err=None, status_code=None):
"""
Converts the executed command responses into an object.
@param std_out: The stdout result
@type std_out: string
@param std_err: The stderr result
@type std_err: string
@param status_code: The status code of the executed command
@type status_code: int
@rtype: WinRMResponse
"""
response = WinRMResponse(std_out=std_out, std_err=std_err, status_code=status_code)
return response
def execute_command(self, command=None, args=None):
"""
Executes a command via remote shell.
@param command: The command to execute
@type command: string
@param args: A list of arguments to pass to the command
@type args: list of strings
@return: Result of command execution
@rtype: WinRMResponse
"""
if not self.is_connected():
message = "Not currently connected to {host}.".format(host=self.host)
self._log.error(message)
raise Exception(message)
if args is None:
args = []
self._log.debug("Executing command: {command} {args}".format(command=command, args=" ".join(args)))
command_id = self.connection.run_command(self.shell_id, command, args)
std_out, std_err, status_code = self.connection.get_command_output(self.shell_id, command_id)
response = self._format_response(std_out=std_out, std_err=std_err, status_code=status_code)
self._log.debug("Stdout: {std_out}".format(std_out=response.std_out))
self._log.debug("Stderr: {std_err}".format(std_err=response.std_err))
self._log.debug("Status code: {status_code}".format(status_code=response.status_code))
return response
示例7: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
class Session(object):
# TODO implement context manager methods
def __init__(self, target, auth, transport='plaintext',
timeout=None):
username, password = auth
self.url = self._build_url(target, transport)
self.protocol = Protocol(self.url, transport=transport,
username=username, password=password,
timeout=timeout)
def run_cmd(self, command, args=()):
# TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
def run_ps(self, script):
"""base64 encodes a Powershell script and executes the powershell
encoded script command
"""
# must use utf16 little endian on windows
encoded_ps = b64encode(script.encode('utf_16_le')).decode('ascii')
rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
if len(rs.std_err):
# if there was an error message, clean it it up and make it human
# readable
rs.std_err = self._clean_error_msg(rs.std_err)
return rs
def _clean_error_msg(self, msg):
"""converts a Powershell CLIXML message to a more human readable string
"""
# TODO prepare unit test, beautify code
# if the msg does not start with this, return it as is
if msg.startswith("#< CLIXML\r\n"):
# for proper xml, we need to remove the CLIXML part
# (the first line)
msg_xml = msg[11:]
try:
# remove the namespaces from the xml for easier processing
msg_xml = self._strip_namespace(msg_xml)
root = ET.fromstring(msg_xml)
# the S node is the error message, find all S nodes
nodes = root.findall("./S")
new_msg = ""
for s in nodes:
# append error msg string to result, also
# the hex chars represent CRLF so we replace with newline
new_msg += s.text.replace("_x000D__x000A_", "\n")
except Exception as e:
# if any of the above fails, the msg was not true xml
# print a warning and return the orignal string
# TODO do not print, raise user defined error instead
print("Warning: there was a problem converting the Powershell"
" error message: %s" % (e))
else:
# if new_msg was populated, that's our error message
# otherwise the original error message will be used
if len(new_msg):
# remove leading and trailing whitespace while we are here
msg = new_msg.strip()
return msg
def _strip_namespace(self, xml):
"""strips any namespaces from an xml string"""
try:
p = re.compile("xmlns=*[\"\"][^\"\"]*[\"\"]")
allmatches = p.finditer(xml)
for match in allmatches:
xml = xml.replace(match.group(), "")
return xml
except Exception as e:
raise Exception(e)
@staticmethod
def _build_url(target, transport):
match = re.match(
'(?i)^((?P<scheme>http[s]?)://)?(?P<host>[0-9a-z-_.]+)(:(?P<port>\d+))?(?P<path>(/)?(wsman)?)?', target) # NOQA
scheme = match.group('scheme')
if not scheme:
# TODO do we have anything other than HTTP/HTTPS
scheme = 'https' if transport == 'ssl' else 'http'
host = match.group('host')
port = match.group('port')
if not port:
port = 5986 if transport == 'ssl' else 5985
path = match.group('path')
if not path:
path = 'wsman'
return '{0}://{1}:{2}/{3}'.format(scheme, host, port, path.lstrip('/'))
示例8: Protocol
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
# Run a process on a remote host
s = winrm.Session('windows-host.example.com', auth=('john.smith', 'secret'))
r = s.run_cmd('ipconfig', ['/all'])
print r.status_code, r.std_out,
# Run Powershell script on remote host
ps_script = """$strComputer = $Host
Clear
$RAM = WmiObject Win32_ComputerSystem
$MB = 1048576
"Installed Memory: " + [int]($RAM.TotalPhysicalMemory /$MB) + " MB" """
r = s.run_ps(ps_script)
print r.status_code, r.std_out,
# Run process with low-level API with domain user, disabling HTTPS cert validation
from winrm.protocol import Protocol
p = Protocol(
endpoint='https://windows-host:5986/wsman',
transport='ntlm',
username=r'somedomain\someuser',
password='secret',
server_cert_validation='ignore')
shell_id = p.open_shell()
command_id = p.run_command(shell_id, 'ipconfig', ['/all'])
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
示例9: Session
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
class Session(object):
# TODO implement context manager methods
def __init__(self, target, auth, transport='plaintext'):
username, password = auth
self.url = self._build_url(target, transport)
self.protocol = Protocol(self.url, transport=transport,
username=username, password=password)
def run_cmd(self, command, args=()):
# TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
def run_ps_long(self, script):
"""base64 encodes a Powershell script and executes the powershell
encoded script command
"""
shell_id = self.protocol.open_shell()
def run_command(command):
command_id = self.protocol.run_command(shell_id, command)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
# Powershell errors are returned in XML, clean them up
if len(rs.std_err):
rs.std_err = self.clean_error_msg(rs.std_err)
return rs
def make_ps_command(ps_script):
return ("powershell -encodedcommand %s"
% base64.b64encode(ps_script.encode("utf_16_le")))
def run_and_check_ps(command, stage_message):
rs = run_command(command)
if len(rs.std_err) or rs.status_code != 0:
self.protocol.close_shell(shell_id)
raise Exception("%s\n%s" % (stage_message, rs.std_err))
return rs.std_out
# Get the name of a temp file
cmd = ("$script_file = [IO.Path]::GetTempFileName() | "
" Rename-Item -NewName { $_ -replace 'tmp$', 'tmp.ps1' } -PassThru\n"
'"$script_file"')
script_file = run_and_check_ps(make_ps_command(cmd), "Creating temp script file")
script_file = script_file.strip()
# Append the data to the file
base64_script = base64.b64encode(script)
chunk_size = 2000
for chunk_index in range(0, len(base64_script), chunk_size):
chunk = base64_script[chunk_index:chunk_index + chunk_size]
cmd ='ECHO %s %s "%s" ' % (chunk,
('>>' if chunk_index else '>'),
script_file)
run_and_check_ps(cmd, "writing chunk %s to temp script file" % chunk_index)
# Execute the powershell script
cmd = '''
# Convert it from b64 encoded
$b64 = get-content "%(script_file)s"
[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($b64)) |
out-file -Encoding Default "%(script_file)s"
''' % {'script_file':script_file}
run_and_check_ps(make_ps_command(cmd),
"Converting temp script file back from b64 encoding")
cmd = ("""PowerShell.exe -ExecutionPolicy Bypass -Command "& '%s' " """
% script_file)
rs = run_command(cmd)
# Finally, cleanup the temp file
cmd = "remove-item '%s' " % script_file
run_and_check_ps(make_ps_command(cmd), "Deleting temp script file")
self.protocol.close_shell(shell_id)
return rs
def run_ps(self, script):
# Get a temp powershell file name
# TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
base64_script = base64.b64encode(script.encode("utf_16_le"))
# There is an issue with powershell scripts over 2k or 8k (platform dependent)
# You can not have a command line + argument longer than this
if len(base64_script) > 2000:
return self.run_ps_long(script)
# must use utf16 little endian on windows
rs = self.run_cmd("powershell -encodedcommand %s" % (base64_script))
#.........这里部分代码省略.........
示例10: Protocol
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
script = script.replace("$$"+itemlist[0], itemlist[1])
else:
script = script.replace("$$"+key, value)
script = script.replace("\n", ";")
if "\\" in data["serverusername"]:
#script = base64.b64encode(script.encode("utf-16"))
cmd = "powershell -ExecutionPolicy Bypass -command %s" % (script)
p = Protocol(
endpoint='https://'+data["servername"]+':5986/wsman',
transport='credssp',
username=data["serverusername"],
password=data["password"],
server_cert_validation='ignore')
shell_id = p.open_shell()
command_id = p.run_command(shell_id, cmd)
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
else:
script = "\n"+script
s = winrm.Session(data["servername"], auth=(data["serverusername"], data["password"]))
try:
r = s.run_ps(script)
# except winrm.exceptions.UnauthorizedError:
# print "Could not authenticate on the remote server:", sys.exc_info()[1]
# sys.exit(100)
except:
print "Unexpected error"
raise
示例11: b64encode
# 需要导入模块: from winrm.protocol import Protocol [as 别名]
# 或者: from winrm.protocol.Protocol import run_command [as 别名]
encoded_ps = b64encode(command.encode('utf_16_le')).decode('ascii')
powershell_command = 'powershell {0} -encodedcommand {1}'.format(arguments, encoded_ps)
results = {}
exit_code = 0
for ip in ips:
p = Protocol(
endpoint='https://{0}:{1}/wsman'.format(ip, winrm_ssl_port),
transport='ntlm', # the only authentication we support at the moment
username=r'{0}\{1}'.format(ips, username),
password=password,
server_cert_validation='ignore') # there will be self-signed certificates only, so let's ignore validation
shell_id = p.open_shell()
command_id = p.run_command(shell_id, powershell_command)
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
results[ip] = {"result": std_out.decode('ascii'), "error": std_err.decode('ascii')}
# some command returned an error and this is first error
# save it as exit code to let user know that there is some problem
if status_code > 0 and exit_code == 0:
exit_code = status_code
yaml.safe_dump({"results": results}, sys.stdout)
sys.exit(exit_code)