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()
Maybe you can use SSH to connect to a remote server.
Install freeSSHd on your windows server.
SSH Client connection Code:
Execution Command and get feedback:
For connection
for commands
I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint
Server:
Client
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...
You can use
pywinrm
library instead which is cross-platform compatible.Here is a simple code example:
Install library via:
pip install pywinrm requests_kerberos
.Here is another example from this page to run Powershell script on a remote host:
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.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.
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).