Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
linux_faq:execute_commands_on_windows_host_using_pywinrm [2019/08/26 08:10] adminlinux_faq:execute_commands_on_windows_host_using_pywinrm [2019/08/26 09:16] (current) – [TypeError: startswith first arg must be bytes...] admin
Line 1: Line 1:
 +https://github.com/diyan/pywinrm/ \\
 +https://pypi.org/project/pywinrm/0.2.1/ \\
 +https://devblogs.microsoft.com/scripting/using-winrm-on-linux/\\
 +
 +  sudo apt-get install python-dev libkrb5-dev
 +  pip install Kerberos pywinrm
 +
 +<code>#!/bin/python
 +
 +import winrm
 +
 +win_host = 'http://windows.domain.local:5985/wsman'
 +win_user = 'user@DOMAIN.LOCAL'
 +win_pass = 'secret_password'
 +winrm_transport='ntlm'
 +
 +s = winrm.Session(win_host, auth=(win_user, win_pass), transport=winrm_transport)
 +r = s.run_cmd('ipconfig', ['/all'])
 +print (r.std_out)
 +print (r.status_code)
 +
 +
 +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)
 +print (r.std_out)
 +</code>
 +  
 +<code>
 +#!/bin/python
 +
 +from winrm.protocol import Protocol
 +
 +p = Protocol(
 +    endpoint='https://windows-host:5986/wsman',
 +#   endpoint='http://windows-host:5985/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)
 +print (std_out)
 +print (status_code)
 +</code>
 +
 +====== Ошибки ======
 +===== TypeError: startswith first arg must be bytes... =====
 +При попытке запустить **PowerShell Script** на русскоязычной **Windows** получаем такое:
 +<code>Traceback (most recent call last):
 +  File "./test_winrm.py", line 19, in <module>
 +    r= s.run_ps(ps_script)
 +  File "/usr/local/lib/python3.7/dist-packages/winrm/__init__.py", line 54, in run_ps
 +    rs.std_err = self._clean_error_msg(rs.std_err)
 +  File "/usr/local/lib/python3.7/dist-packages/winrm/__init__.py", line 62, in _clean_error_msg
 +    if msg.startswith("#< CLIXML\r\n"):
 +TypeError: startswith first arg must be bytes or a tuple of bytes, not str
 +</code>
 +Обсуждение тут: https://github.com/diyan/pywinrm/issues/111  \\
 +Судя по всему - причина в каких-то проблемах с кодировкой в функции **_clean_error_msg(self, msg)**. Я просто закомментировал пару строк, которые вызывают эту функцию, которая делает удобочитаемыми сообщения об ошибках. \\
 +В принципе, меня вполне устроит просто проверка того, что скрипт вернул код 0. \\
 +В моей системе в файлике **/usr/local/lib/python3.7/dist-packages/winrm/__init__.py** я закоменнтировал строки:
 +        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)
 +в функции **run_ps(self, script)**. \\
 +Однако, если исполнять этот скрипт в среде **python2**, то все отрабатывает без ошибок! 
 +
 + 
 +
  
  • linux_faq/execute_commands_on_windows_host_using_pywinrm.txt
  • Last modified: 2019/08/26 09:16
  • by admin