Python uses winrm to remotely connect to another PC and control

First, you need to configure winrm on Windows to ensure that you can connect and control:
Refer to the link
Take my own computer as an example: use 192.168.64.84 (win10) to connect to 192.168.64.80 (win7) and control.
Here is an example of deleting a picture of win7:


import winrm
import time
s=winrm.Session('http://192.168.64.80:5985/wsman',auth=('admin','000000'))
time.sleep(5)
s.keep_alive = False

comm="del/f/s/q "+r"C:\Users\liuyan\Desktop\1.jpg"
t=s.run_cmd(comm)

print(t.std_out)
print("******")
print(t.std_err)
print("******")

The results of the operation are:

b'Deleted file - C:\\Users\\admin\\Desktop\\1.jpg\r\n'
******
b''
******

And on a win7 PC, the picture will also be deleted.

If you want to run multiple commands, use & to separate:

t=s.run_cmd('dir & cd / & dir')

Two lists will be output, and the running results are not easy to release.

Mention run_cmd() and run_ps(): the
former executes commands and the latter executes scripts.

 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

But I also encountered a problem, that is, it fails when I want to open a webpage or application, but this command can be executed on the command line of win7, which burns my brain.

#comm='start '+r'https://blog.csdn.net/liulanba?spm=1001.2101.3001.5343'
#print(comm)
# s.run_cmd(comm)

# comm="start C:\GTJA\RichEZ\newVer\Loading.exe"
# t=s.run_cmd(comm)

This problem has not been solved yet, the big guys passing by can poke me, thank you very much!
It is said that there is another method, I haven't tried it yet, please record it first

import winrm
conn = winrm.Protocol(endpoint='http://10.10.60.14:5985/wsman', transport='plaintext', username='administrator', password='password')

shell_id=conn.open_shell()

com=conn.run_command(shell_id,"dir") 

stdout, stderr, return_code = conn.get_command_output(shell_id, com) 

print "STDOUT: %s" % (stdout)
print "STDERR: %s" % (stderr)

Guess you like

Origin blog.csdn.net/liulanba/article/details/115125271