Python使用winrm远程连接另一台PC并控制

首先需要在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)
  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值