首先需要在Windows上配置winrm来保证可以进行连接和控制:
参考链接
以我自己的电脑为例:使用192.168.64.84(win10)连接192.168.64.80(win7)并进行控制。
此处是删除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("******")
运行结果为:
b'Deleted file - C:\\Users\\admin\\Desktop\\1.jpg\r\n'
******
b''
******
并且在win7的PC上,该图片也会被删除。
如果想要运行多条命令,使用&分隔即可:
t=s.run_cmd('dir & cd / & dir')
则会输出两个列表,运行结果不太方便放出。
提一下run_cmd()和run_ps():
前者是执行命令的,后者是执行脚本的。
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
但是我也遇到了一个问题,那就是想打开网页或者应用的时候就失败了,但是这个命令在win7的命令行却是可以执行的,烧脑壳。
#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)
这个问题还没有解决,路过的大佬可以戳我一下,万分感谢!
据说还有另一种方法,我还没有尝试,先记录一下
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)