How to connect to a remote Windows machine to exec

2019-01-16 17:31发布

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.

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

8条回答
趁早两清
2楼-- · 2019-01-16 17:41

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

Install freeSSHd on your windows server.

SSH Client connection Code:

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)
查看更多
\"骚年 ilove
3楼-- · 2019-01-16 17:41

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
查看更多
混吃等死
4楼-- · 2019-01-16 17:45

I don't know WMI but if you want a simple Server/Client, You can use this simple code from 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.

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

查看更多
Summer. ? 凉城
5楼-- · 2019-01-16 17:46

You can use pywinrm library instead which is cross-platform compatible.

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.


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

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
查看更多
可以哭但决不认输i
6楼-- · 2019-01-16 17:49

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

查看更多
甜甜的少女心
7楼-- · 2019-01-16 17:50

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

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

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

查看更多
登录 后发表回答