如何使用Python连接到远程Windows计算机并执行命令?

31

我是Python的新手,正在尝试编写一个脚本,连接到远程Windows机器并在那里执行命令以测试端口连通性。

这是我正在编写的代码,但它不起作用。基本上,我想要的是连接到远程机器并返回该机器的数据,而不是本地机器的数据。

import wmi
import os
import subprocess
import re
import socket, sys

def main():

     host="remotemachine"
     username="adminaam"
     password="passpass!"
     server =connects(host, username, password)
     s = socket.socket()
     s.settimeout(5)
     print server.run_remote('hostname')

class connects:

    def __init__(self, host, username, password, s = socket.socket()):
        self.host=host
        self.username=username
        self.password=password
        self.s=s

        try:
            self.connection= wmi.WMI(self.host, user=self.username, password=self.password)
            self.s.connect(('10.10.10.3', 25))
            print "Connection established"
        except:
            print "Could not connect to machine"


   def run_remote(self, cmd, async=False, minimized=True):
       call=subprocess.check_output(cmd, shell=True,stderr=subprocess.STDOUT )
       print call

main() 

有什么建议吗?请帮帮忙。 - zewOlF
重要的是在用户名前面加上域名前缀。例如 username = r"EUR\adminaam" - MathKid
11个回答

0

pypsrp - Python PowerShell 远程协议客户端库

At a basic level, you can use this library to;

Execute a cmd command
Run another executable
Execute PowerShell scripts
Copy a file from the localhost to the remote Windows host
Fetch a file from the remote Windows host to the localhost
Create a Runspace Pool that contains one or multiple PowerShell pipelines and execute them asynchronously
Support for a reference host base implementation of PSRP for interactive scripts

参考: https://github.com/jborean93/pypsrp


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接