How to connect to a remote Windows machine to execute commands using python?

后端 未结 11 2108
青春惊慌失措
青春惊慌失措 2020-11-29 20:20

I am new to Python and I am trying to make a script that connects to a remote windows machine and execute commands there and test ports connectivity.

Here is the cod

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 21:07

    You can use pywinrm library instead which is cross-platform compatible.

    Here is a simple code example:

    #!/usr/bin/env python
    import winrm
    
    # Create winrm connection.
    sess = winrm.Session('https://10.0.0.1', auth=('username', 'password'), transport='kerberos')
    result = sess.run_cmd('ipconfig', ['/all'])
    

    Install library via: pip install pywinrm requests_kerberos.


    Here is another example from this page to run Powershell script on a remote host:

    import winrm
    
    ps_script = """$strComputer = $Host
    Clear
    $RAM = WmiObject Win32_ComputerSystem
    $MB = 1048576
    
    "Installed Memory: " + [int]($RAM.TotalPhysicalMemory /$MB) + " MB" """
    
    s = winrm.Session('windows-host.example.com', auth=('john.smith', 'secret'))
    r = s.run_ps(ps_script)
    >>> r.status_code
    0
    >>> r.std_out
    Installed Memory: 3840 MB
    
    >>> r.std_err
    

提交回复
热议问题