zew*_*OlF 16 python sockets windows wmi remote-server
我是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()
Run Code Online (Sandbox Code Playgroud)
您可以使用以下两种方法将一台计算机连接到网络中的另一台计算机:
以下是使用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.")
Run Code Online (Sandbox Code Playgroud)
第二种方法是使用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)
Run Code Online (Sandbox Code Playgroud)
断开连接:
import win32api
import win32net
win32net.NetUseDel('\\\\192.168.1.18',username,win32net.USE_FORCE)
Run Code Online (Sandbox Code Playgroud)在本地系统中安装远程计算机驱动器
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')
Run Code Online (Sandbox Code Playgroud)
要在本地系统中卸载远程计算机驱动器:
import win32api
import win32net
import win32netcon,win32wnet
win32wnet.WNetCancelConnection2('\\\\192.168.1.4\\D$',1,1)
Run Code Online (Sandbox Code Playgroud)在使用netuse之前,你应该在你的系统中安装pywin32并使用python.
来源:连接远程系统.
连接用
c=wmi.WMI('machine name',user='username',password='password')
#this connects to remote system. c is wmi object
Run Code Online (Sandbox Code Playgroud)
命令
process_id, return_value = c.Win32_Process.Create(CommandLine="cmd.exe /c <your command>")
#this will execute commands
Run Code Online (Sandbox Code Playgroud)
您可以使用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'])
Run Code Online (Sandbox Code Playgroud)
通过安装库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
Run Code Online (Sandbox Code Playgroud)
也许您可以使用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)
Run Code Online (Sandbox Code Playgroud)
执行命令并获得反馈:
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)
Run Code Online (Sandbox Code Playgroud)
我不知道 WMI,但如果您想要一个简单的服务器/客户端,您可以使用教程点中的这个简单代码
服务器:
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
Run Code Online (Sandbox Code Playgroud)
客户
#!/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
Run Code Online (Sandbox Code Playgroud)
它还具有简单客户端/服务器应用程序所需的所有信息。
只需转换服务器并使用一些简单的协议从 python 调用函数即可。
PS:我确信有很多更好的选择,如果你愿意的话,这只是一个简单的选择......
| 归档时间: |
|
| 查看次数: |
99916 次 |
| 最近记录: |