gpt4 book ai didi

python - 如何使用Python3从Centos连接到windows 2012机器

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:33 25 4
gpt4 key购买 nike

我的要求是能够在 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("\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")

关于python - 如何使用Python3从Centos连接到windows 2012机器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52853285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com