如何连接到远程Windows机器以使用python执行命令?

前端之家收集整理的这篇文章主要介绍了如何连接到远程Windows机器以使用python执行命令?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是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,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()
您可以使用以下两种方法将一台计算机连接到网络中的另一台计算机:

>使用WMI库.
> Netuse方法.

WMI

以下是使用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模块.

通过Netuse,您可以连接到远程计算机.您可以访问远程计算机的所有数据.可以通过以下两种方式实现:

>通过虚拟连接进行连接.

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)

断开连接:

import win32api
import win32net
win32net.NetUseDel('\\\\192.168.1.18',win32net.USE_FORCE)

>在本地系统中安装远程计算机驱动器.

import win32api
import win32net
import win32netcon,win32wnet

username=’user’
password=’psw’

try:
    win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK,'Z:','\\\\192.168.1.18\\D$',None,0)
    print “connection established successfully”
except:
    print  “connection not established”

要在本地系统中卸载远程计算机驱动器:

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.

资料来源:Connect remote system.

原文链接:https://www.f2er.com/windows/371894.html

猜你在找的Windows相关文章