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

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


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

Here is a simple code example:

#!/usr/bin/env pythonimport 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 winrmps_script = """$strComputer = $HostClear$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_code0>>> r.std_outInstalled Memory: 3840 MB>>> r.std_err


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:

  1. Connect by virtual connection.

    import win32apiimport win32netip = '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 win32apiimport win32netwin32net.NetUseDel('\\\\192.168.1.18',username,win32net.USE_FORCE)
  2. Mount remote computer drive in local system.

    import win32apiimport win32netimport win32netcon,win32wnetusername='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 win32apiimport win32netimport win32netcon,win32wnetwin32wnet.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.


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

Install freeSSHd on your windows server.

SSH Client connection Code:

import paramikohostname = "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)