如何连接到远程 Windows 机器以使用 python 执行命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18961213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:24:55  来源:igfitidea点击:

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

pythonwindowssocketswmiremote-server

提问by zewOlF

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.

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

Here is the code that I am writing but it is not working. Basically, I want to and it returns with the local machine data, not the remote one.

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

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() 

回答by Kobi K

I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint

我不知道 WMI 但如果你想要一个简单的服务器/客户端,你可以使用tutorialspoint 中的这个简单代码

Server:

服务器:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection 

Client

客户

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

it also have all the needed information for simple client/server applications.

它还具有简单客户端/服务器应用程序所需的所有信息。

Just convert the server and use some simple protocol to call a function from python.

只需转换服务器并使用一些简单的协议从 python 调用函数。

P.S: i'm sure there are a lot of better options, it's just a simple one if you want...

PS:我相信有很多更好的选择,如果你愿意,这只是一个简单的选择......

回答by Ashish Jain

You can connect one computer to another computer in a network by using these two methods:

您可以使用以下两种方法将一台计算机连接到网络中的另一台计算机:

  • Use WMI library.
  • Netuse method.
  • 使用 WMI 库。
  • 网络使用方法。


WMI

WMI

Here is the example to connect using wmi module:

以下是使用 wmi 模块进行连接的示例:

ip = '192.168.1.13'
username = 'username'
password = 'password'
from socket import *
try:
    print("Establishing connection to %s" %ip)
    connection = wmi.WMI(ip, user=username, password=password)
    print("Connection established")
except wmi.x_wmi:
    print("Your Username and Password of "+getfqdn(ip)+" are wrong.")


netuse

网易

The second method is to use netuse module.

第二种方法是使用netuse模块。

By Netuse, you can connect to remote computer. And you can access all data of the remote computer. It is possible in the following two ways:

通过 Netuse,您可以连接到远程计算机。您可以访问远程计算机的所有数据。可以通过以下两种方式:

  1. Connect by virtual connection.

    import win32api
    import win32net
    ip = '192.168.1.18'
    username = 'ram'
    password = 'ram@123'
    
    use_dict={}
    use_dict['remote']=unicode('\\192.168.1.18\C$')
    use_dict['password']=unicode(password)
    use_dict['username']=unicode(username)
    win32net.NetUseAdd(None, 2, use_dict)
    

    To disconnect:

    import win32api
    import win32net
    win32net.NetUseDel('\\192.168.1.18',username,win32net.USE_FORCE)
    
  2. Mount remote computer drive in local system.

    import win32api
    import win32net
    import win32netcon,win32wnet
    
    username='user'
    password='psw'
    
    try:
        win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, 'Z:','\\192.168.1.18\D$', None, username, password, 0)
        print('connection established successfully')
    except:
        print('connection not established')
    

    To unmount remote computer drive in local system:

    import win32api
    import win32net
    import win32netcon,win32wnet
    
    win32wnet.WNetCancelConnection2('\\192.168.1.4\D$',1,1)
    
  1. 通过虚拟连接进行连接。

    import win32api
    import win32net
    ip = '192.168.1.18'
    username = 'ram'
    password = 'ram@123'
    
    use_dict={}
    use_dict['remote']=unicode('\\192.168.1.18\C$')
    use_dict['password']=unicode(password)
    use_dict['username']=unicode(username)
    win32net.NetUseAdd(None, 2, use_dict)
    

    断开连接:

    import win32api
    import win32net
    win32net.NetUseDel('\\192.168.1.18',username,win32net.USE_FORCE)
    
  2. 在本地系统中安装远程计算机驱动器。

    import win32api
    import win32net
    import win32netcon,win32wnet
    
    username='user'
    password='psw'
    
    try:
        win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, 'Z:','\\192.168.1.18\D$', None, username, password, 0)
        print('connection established successfully')
    except:
        print('connection not established')
    

    在本地系统中卸载远程计算机驱动器:

    import win32api
    import win32net
    import win32netcon,win32wnet
    
    win32wnet.WNetCancelConnection2('\\192.168.1.4\D$',1,1)
    

Before using netuse you should have pywin32 install in your system with python also.

在使用 netuse 之前,您还应该使用 python 在系统中安装 pywin32。



Source: Connect remote system.

来源:连接远程系统

回答by Chet Meinzer

do the client machines have python loaded? if so, I'm doing this with psexec

客户端机器是否加载了python?如果是这样,我正在使用psexec执行此操作

On my local machine, I use subprocess in my .py file to call a command line.

在我的本地机器上,我在 .py 文件中使用 subprocess 来调用命令行。

import subprocess
subprocess.call("psexec {server} -c {}") 

the -c copies the file to the server so i can run any executable file (which in your case could be a .bat full of connection tests or your .py file from above).

-c 将文件复制到服务器,以便我可以运行任何可执行文件(在您的情况下,它可能是一个充满连接测试的 .bat 文件或上面的 .py 文件)。

回答by fhulprogrammer

For connection

连接用

c=wmi.WMI('machine name',user='username',password='password')

#this connects to remote system. c is wmi object

for commands

命令

process_id, return_value = c.Win32_Process.Create(CommandLine="cmd.exe /c  <your command>")

#this will execute commands

回答by Rusty Weber

I have personally found pywinrmlibraryto be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.

我个人发现pywinrm图书馆非常有效。但是,它确实需要在机器上运行一些命令和一些其他设置才能工作。

回答by kenorb

You can use pywinrmlibraryinstead which is cross-platform compatible.

您可以使用pywinrm,而不是它是跨平台兼容。

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.

通过以下方式安装库:pip install pywinrm requests_kerberos.



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

这是此页面上的另一个示例,用于在远程主机上运行 Powershell 脚本:

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

回答by Beatrice Lin

Maybe you can use SSH to connect to a remote server.

也许您可以使用 SSH 连接到远程服务器。

Install freeSSHd on your windows server.

在您的 Windows 服务器上安装 freeSSHd。

SSH Client connection Code:

SSH客户端连接代码:

import paramiko

hostname = "your-hostname"
username = "your-username"
password = "your-password"
cmd = 'your-command'

try:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname,username=username,password=password)
    print("Connected to %s" % hostname)
except paramiko.AuthenticationException:
    print("Failed to connect to %s due to wrong username/password" %hostname)
    exit(1)
except Exception as e:
    print(e.message)    
    exit(2)

Execution Command and get feedback:

执行命令并获得反馈:

try:
    stdin, stdout, stderr = ssh.exec_command(cmd)
except Exception as e:
    print(e.message)

err = ''.join(stderr.readlines())
out = ''.join(stdout.readlines())
final_output = str(out)+str(err)
print(final_output)

回答by David Castro

is it too late?

是不是太晚了?

I personally agree with Beatrice Len, I used paramiko maybe is an extra step for windows, but I have an example project git hub, feel free to clone or ask me.

我个人同意 Beatrice Len,我使用 paramiko 可能是 windows 的一个额外步骤,但我有一个示例项目 git hub,请随意克隆或问我。

https://github.com/davcastroruiz/django-ssh-monitor

https://github.com/davcastroruiz/django-ssh-monitor