繁体   English   中英

如何使用Python3从Centos连接到Windows 2012计算机

[英]How to connect to windows 2012 machine from Centos using Python3

我的要求是能够在Windows 2012服务器上远程运行PowerShell脚本的能力,这必须从使用Python脚本的Linux服务器上触发。

需要有关处理此问题的最佳方法的建议,以及示例代码(如果可能)。

以下是我打算实现的步骤,但我发现它没有按预期工作。

  1. Windows Server(2012)中已放置要执行的PowerShell脚本。
  2. 在Linux(CentOS)上运行的Python3程序使用netmiko模块将SSH SSH到Windows服务器(2012)。
  3. 通过SSH连接发送命令(PowerShell命令以在远程Windows服务器中执行脚本)。

我能够使用Python连接到远程Windows服务器。 但是我看不到这种方法能正常工作。

需要一种有效的方法来实现这一目标。

from netmiko import ConnectHandler

device = ConnectHandler(device_type="terminal_server",
                        ip="X.X.X.x",
                        username="username",
                        password="password")
hostname = device.find_prompt()
output = device.send_command("ipconfig")
print (hostname)
print (output)
device.disconnect()

“ terminal_server”设备类型没有做太多事情,您现在必须手动进行传递。

下面摘自COMMON_ISSUES.md

Netmiko是否支持通过终端服务器进行连接?

SSH连接后,有一个“ terminal_server” device_type基本上不执行任何操作。 这意味着您必须手动处理与终端服务器的交互才能连接到终端设备。 完全连接到终端网络设备后,可以“重新调度”,并且Netmiko将正常运行

from __future__ import unicode_literals, print_function
import time
from netmiko import ConnectHandler, redispatch

net_connect = ConnectHandler(
    device_type='terminal_server',        # Notice 'terminal_server' here
    ip='10.10.10.10', 
    username='admin', 
    password='admin123', 
    secret='secret123')

# Manually handle interaction in the Terminal Server 
# (fictional example, but hopefully you see the pattern)
# Send Enter a Couple of Times
net_connect.write_channel("\r\n")
time.sleep(1)
net_connect.write_channel("\r\n")
time.sleep(1)
output = net_connect.read_channel()
print(output)                             # Should hopefully see the terminal server prompt

# Login to end device from terminal server
net_connect.write_channel("connect 1\r\n")
time.sleep(1)

# Manually handle the Username and Password
max_loops = 10
i = 1
while i <= max_loops:
    output = net_connect.read_channel()

    if 'Username' in output:
    net_connect.write_channel(net_connect.username + '\r\n')
    time.sleep(1)
    output = net_connect.read_channel()

    # Search for password pattern / send password
    if 'Password' in output:
    net_connect.write_channel(net_connect.password + '\r\n')
    time.sleep(.5)
    output = net_connect.read_channel()
    # Did we successfully login
    if '>' in output or '#' in output:
        break

    net_connect.write_channel('\r\n')
    time.sleep(.5)
    i += 1

# We are now logged into the end device 
# Dynamically reset the class back to the proper Netmiko class
redispatch(net_connect, device_type='cisco_ios')

# Now just do your normal Netmiko operations
new_output = net_connect.send_command("show ip int brief")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM