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



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

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

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

  1. 要执行的PowerShell脚本已经放置在Windows服务器(2012(中。
  2. 运行在Linux(CentOS(上的Python3程序使用netmiko模块通过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是否支持通过终端服务器进行连接?

有一个"terminal_server"device_type在SSH连接后基本上什么都不做。这意味着您必须手动处理与终端服务器的交互才能连接到终端设备。完全连接到终端网络设备后,您可以"重新调度",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("rn")
time.sleep(1)
net_connect.write_channel("rn")
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 1rn")
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 + 'rn')
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 + 'rn')
time.sleep(.5)
output = net_connect.read_channel()
# Did we successfully login
if '>' in output or '#' in output:
break
net_connect.write_channel('rn')
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")

最新更新