How to connect to a remote Windows machine to execute commands using python?
Solution 1
You can connect one computer to another computer in a network by using these two methods:
- Use WMI library.
- Netuse method.
WMI
Here is the example to connect using wmi module:
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.
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:
-
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)
-
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)
Before using netuse you should have pywin32 install in your system with python also.
Source: Connect remote system.
Solution 2
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
Solution 3
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)
Solution 4
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
Solution 5
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.
Related videos on Youtube
zewOlF
Updated on October 12, 2020Comments
-
zewOlF over 3 years
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()
-
zewOlF over 10 yearsany sugestions Guys.. ? ? please help
-
MathKid over 9 yearsIt is important to prefix the domain in front of the username. For example
username = r"EUR\adminaam"
-
-
zewOlF over 10 yearsThank you Kobi for replying me, but this is gonna be so hard to go to every client and run a script there.... what i am trying to do is accessing multiple machines from 1 machine and execute commands there
-
Rjain about 8 yearsCan u suggest some package that can be used for cross platform remote login
-
Michael Biniashvili almost 7 yearswow, very cool, work very good, can be install using pip [#]pip install wmi
-
alpha_989 over 6 yearsWhat is the relative advantages and disadvantages of WMI over Netuse and vice versa?
-
Rohit almost 4 yearsThis solution helped me a big time. From windows machine I was trying to run a shell script on a remote machine which eventually has python script path to run. If I need to run multiple commands then can I repeat the execution command box ? Please suggest.
-
Beatrice Lin almost 4 yearsWhen you run exec_command multiple times, each command is executed in its own "shell". So the previous commands have no effect on an environment of the following commands.
-
Beatrice Lin almost 4 yearsIf you need the previous commands to affect the following commands, just use an appropriate syntax of your server shell. Most *nix shells use a semicolon or an double-ampersand (with different semantics) to specify a list of commands. In your case, the ampersand is more appropriate, as it executes following commands, only if previous commands succeed: like this: stdin,stdout,stderr=ssh.exec_command("ORACLE_SID=PROD && cd /01/application/dataload && pwd")
-
Rusty Weber over 3 yearsFunny you should ask. I'm personally working on open sourcing a library for just exactly that.
-
Adnan Sheikh almost 3 yearsI was trying this and I am facing an issue when I run a command like 'ipconfig'. It says "HTTPSConnectionPool(host='192.168.1.13', port=5986): Max retries exceeded with url: /wsman (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fcb12024a90>, 'Connection to 192.168.1.13 timed out. (connect timeout=30)'))""