很好,这是我正在使用的代码:
function escribe_log($dispositivo, $log, $comando){
$Fichero_Log = "C:\Modificacion_routers.log"
$texto = $dispositivo
$texto >> $Fichero_Log
$texto = $log
$texto >> $Fichero_Log
$texto = $comando
$texto >> $Fichero_Log
}
##PROGRAMA PRINCIPAL##
Import-Module SSH-Sessions
$ficheroIPS = "C:\ipsdispositivos.txt"
$ficheroComandos = "c:\comandos.txt"
$dispositivos = Get-Content $ficheroIPS
$comandos = Get-Content $ficheroComandos
foreach ($dispositivo in $dispositivos) {
New-SshSession -ComputerName $dispositivo -Username USUARIO -password PASSWORD
foreach ($comando in $comandos) {
$SshResults = Invoke-SshCommand -ComputerName $dispositivo -Command $comando
escribe_log $dispositivo $SshResults $comando
Start-Sleep -s 1
}
$comandos = Get-Content $ficheroComandos
}
Remove-sshSession -RemoveAll
完美地启动“sh”显示命令,我的问题是当我启动命令时会自动断开会话,然后命令无法启动“conf t”进入配置模式然后启动配置命令。
你知道这个库是否可以配置路由器吗?如果那不可能,他们会知道我使用脚本配置路由器的任何替代方法吗?
解决了:
使用 POWERSHELL 更改 SSH 路由器/交换机的功能
Function set-SSH($devices, $ssh){
function ReadStream($reader)
{
$line = $reader.ReadLine();
while ($line -ne $null)
{
$line
$line = $reader.ReadLine()
}
}
function WriteStream($cmd, $writer, $stream)
{
$writer.WriteLine($cmd)
while ($stream.Length -eq 0)
{
start-sleep -milliseconds 1000
}
}
$stream = $ssh.CreateShellStream("dumb", 80, 24, 800, 600, 1024)
$reader = new-object System.IO.StreamReader($stream)
$writer = new-object System.IO.StreamWriter($stream)
$writer.AutoFlush = $true
while ($stream.Length -eq 0)
{
start-sleep -milliseconds 500
}
ReadStream $reader
foreach ($command in $commands) {
WriteStream $command $writer $stream
ReadStream $reader
Write-Host $reader
start-sleep -milliseconds 500
}
$stream.Dispose()
$ssh.Disconnect()
$ssh.Dispose()
}
初始化 $commands、$ssh、$devices 三个变量
#Example of file commands.txt...
#sh conf
#conf t
#int f0/1
#description Modify via powershell
#exit
#exit
#wr
#...
$fileCommands= ".\commands.txt"
$commands= Get-Content $fileCommands
#Example of file devices.csv...
#10.10.10.10;SWITCH01
#10.10.10.11;SWITCH02
#10.10.10.12;SWITCH03
#...
$devices = Import-Csv -path ".\devices.csv" -header 'ip','hostname' -delimiter ';'
$port = 22
$ssh = new-object Renci.SshNet.SshClient($devices[0].ip, $port, $user, $password)
Try{
$ssh.Connect()
Start-Sleep -s 1
set-SSH $commands $ssh
}catch{
}