복붙노트

[PYTHON] 파이썬을 사용하여 명령을 실행하기 위해 원격 Windows 컴퓨터에 연결하는 방법은 무엇입니까?

PYTHON

파이썬을 사용하여 명령을 실행하기 위해 원격 Windows 컴퓨터에 연결하는 방법은 무엇입니까?

필자는 Python을 처음 사용하고 있으며 원격 Windows 컴퓨터에 연결하여 명령을 실행하고 포트 연결을 테스트하는 스크립트를 작성하려고합니다.

여기에 제가 쓰고있는 코드가 있지만 작동하지 않습니다. 기본적으로, 나는 원한다. 그리고 그것은 원격 머신이 아닌 로컬 머신 데이터를 반환한다.

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

해결법

  1. ==============================

    1.다음 두 가지 방법을 사용하여 한 컴퓨터를 네트워크의 다른 컴퓨터에 연결할 수 있습니다.

    다음 두 가지 방법을 사용하여 한 컴퓨터를 네트워크의 다른 컴퓨터에 연결할 수 있습니다.

    다음은 wmi 모듈을 사용하여 연결하는 예입니다.

    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 모듈을 사용하는 것입니다.

    Netuse를 사용하면 원격 컴퓨터에 연결할 수 있습니다. 그리고 원격 컴퓨터의 모든 데이터에 액세스 할 수 있습니다. 다음 두 가지 방법으로 가능합니다.

    출처 : 원격 시스템에 연결하십시오.

  2. ==============================

    2.SSH를 사용하여 원격 서버에 연결할 수 있습니다.

    SSH를 사용하여 원격 서버에 연결할 수 있습니다.

    Windows 서버에 freeSSHd를 설치하십시오.

    SSH 클라이언트 연결 코드 :

    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)
    

    실행 명령 및 피드백 받기 :

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

    3.pywinrm 라이브러리 대신 플랫폼 간 호환이 가능합니다.

    pywinrm 라이브러리 대신 플랫폼 간 호환이 가능합니다.

    다음은 간단한 코드 예제입니다.

    #!/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'])
    

    다음을 통해 라이브러리 설치 : pip install pywinrm requests_kerberos.

    다음은이 페이지에서 원격 호스트에 Powershell 스크립트를 실행하는 또 다른 예제입니다.

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

    4.연결 용

    연결 용

    c=wmi.WMI('machine name',user='username',password='password')
    
    #this connects to remote system. c is wmi object
    

    명령 용

    process_id, return_value = c.Win32_Process.Create(CommandLine="cmd.exe /c  <your command>")
    
    #this will execute commands
    
  5. ==============================

    5.나는 WMI를 모른다. 그러나 당신이 간단한 서버 / 클라이언트를 원한다면, tutorialspoint에서이 간단한 코드를 사용할 수 있습니다.

    나는 WMI를 모른다. 그러나 당신이 간단한 서버 / 클라이언트를 원한다면, tutorialspoint에서이 간단한 코드를 사용할 수 있습니다.

    섬기는 사람:

    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 
    

    고객

    #!/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
    

    그것은 또한 간단한 클라이언트 / 서버 응용 프로그램에 필요한 모든 정보를 가지고 있습니다.

    그냥 서버를 변환하고 파이썬에서 함수를 호출하는 간단한 프로토콜을 사용하십시오.

    추신 : 나는 더 나은 옵션이 많이있을 것이라고 확신합니다. 원하는 경우 간단합니다.

  6. ==============================

    6.나는 개인적으로 pywinrm 라이브러리가 매우 효과적이라는 것을 발견했다. 그러나 작동하기 전에 일부 명령을 기계에서 실행하고 다른 설정을해야합니다.

    나는 개인적으로 pywinrm 라이브러리가 매우 효과적이라는 것을 발견했다. 그러나 작동하기 전에 일부 명령을 기계에서 실행하고 다른 설정을해야합니다.

  7. ==============================

    7.클라이언트 컴퓨터에 파이썬이로드되어 있습니까? 그렇다면 psexec을 사용하여이 작업을 수행합니다.

    클라이언트 컴퓨터에 파이썬이로드되어 있습니까? 그렇다면 psexec을 사용하여이 작업을 수행합니다.

    로컬 컴퓨터에서 .py 파일의 subprocess를 사용하여 명령 줄을 호출합니다.

    import subprocess
    subprocess.call("psexec {server} -c {}") 
    

    -c는 실행 파일을 실행할 수 있도록 파일을 서버에 복사합니다 (이 경우에는 .bat가 연결 테스트 또는 .py 파일로 가득 찰 수 있습니다).

  8. ==============================

    8.너무 늦었 니?

    너무 늦었 니?

    나는 개인적으로 베아트리체 렌 (Becatrice Len)에 동의한다. 나는 paramiko를 윈도우 용 추가 단계로 사용했지만, 예제 프로젝트 git hub를 가지고있다.

    https://github.com/davcastroruiz/django-ssh-monitor

  9. from https://stackoverflow.com/questions/18961213/how-to-connect-to-a-remote-windows-machine-to-execute-commands-using-python by cc-by-sa and MIT license