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

后端 未结 11 2091
青春惊慌失措
青春惊慌失措 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: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)
    

提交回复
热议问题