簡體   English   中英

如何連接到遠程 Windows 機器以使用 python 執行命令?

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

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

您可以使用以下兩種方法將一台計算機連接到網絡中的另一台計算機:

  • 使用 WMI 庫。
  • 網絡使用方法。

WMI

以下是使用 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模塊。

通過 Netuse,您可以連接到遠程計算機。 您可以訪問遠程計算機的所有數據。 可以通過以下兩種方式:

  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)

在使用 netuse 之前,您還應該使用 python 在系統中安裝 pywin32。


來源: 連接遠程系統

您可以使用跨平台兼容的pywinrm

下面是一個簡單的代碼示例:

#!/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'])

通過以下方式安裝庫: pip install pywinrm requests_kerberos


這是此頁面上的另一個示例,用於在遠程主機上運行 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

也許您可以使用 SSH 連接到遠程服務器。

在您的 Windows 服務器上安裝 freeSSHd。

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)

執行命令並獲得反饋:

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)

連接用

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

#this connects to remote system. c is wmi object

命令

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

#this will execute commands

客戶端機器是否加載了python? 如果是這樣,我正在使用psexec執行此操作

在我的本地機器上,我在 .py 文件中使用 subprocess 來調用命令行。

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

-c 將文件復制到服務器,以便我可以運行任何可執行文件(在您的情況下,它可能是一個充滿連接測試的 .bat 文件或上面的 .py 文件)。

我個人發現pywinrm非常有效。 但是,它確實需要在機器上運行一些命令和一些其他設置才能工作。

我不知道 WMI 但如果你想要一個簡單的服務器/客戶端,你可以使用tutorialspoint 中的這個簡單代碼

服務器:

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 

客戶

#!/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

它還具有簡單客戶端/服務器應用程序所需的所有信息。

只需轉換服務器並使用一些簡單的協議從 python 調用函數。

PS:我相信有很多更好的選擇,如果你願意,這只是一個簡單的選擇......

連接到遠程服務器並執行命令的最佳方式是使用“ wmiexec.py

只需運行pip install impacket

這將在 python 的腳本文件夾下創建“ wmiexec.py ”文件

在 python > Scripts > wmiexec.py 里面

我們需要以下列方式運行 wmiexec.py

python <wmiexec.py location> TargetUser:TargetPassword@TargetHostname "<OS command>"

請根據您的位置更改 wmiexec.py 位置

就像我使用 python 3.8.5 一樣,我的 wmiexec.py 位置將是C:\\python3.8.5\\Scripts\\wmiexec.py

python C:\python3.8.5\Scripts\wmiexec.py TargetUser:TargetPassword@TargetHostname "<OS command>"

根據您的遠程機器修改 TargetUser、TargetPassword、TargetHostname 和 OS 命令

注意:以上方法用於在遠程服務器上運行命令。

但是如果你需要從遠程服務器捕獲輸出,我們需要創建一個 python 代碼。

import subprocess
command = 'C:\\Python36\\python.exe C:\\Python36\\Scripts\\wmiexec.py TargetUser:TargetPassword@TargetHostname "ipconfig"'
command = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
stdout= command.communicate()[0]
print (stdout)

相應地修改代碼並運行它。

是不是太晚了?

我個人同意 Beatrice Len,我使用 paramiko 可能是 windows 的一個額外步驟,但我有一個示例項目 git hub,請隨意克隆或問我。

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

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

已經有很多答案,但還有一個選擇

PyPSExec https://pypi.org/project/pypsexec/

它是著名的 psexec 的 python 克隆。 無需在遠程 Windows 機器上進行任何安裝即可工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM