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

后端 未结 11 2090
青春惊慌失措
青春惊慌失措 2020-11-29 20:20

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 cod

相关标签:
11条回答
  • 2020-11-29 21:17

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

    0 讨论(0)
  • 2020-11-29 21:17

    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.

    0 讨论(0)
  • 2020-11-29 21:21

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

    0 讨论(0)
  • 2020-11-29 21:22

    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)
    
    0 讨论(0)
  • 2020-11-29 21:24

    Many answers already, but one more option

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

    It's a python clone of the famous psexec. Works without any installation on the remote windows machine.

    0 讨论(0)
提交回复
热议问题