![]() |
Внимание, важное сообщение: Дорогие Друзья!
В ноябре далекого 2001 года мы решили создать сайт и форум, которые смогут помочь как начинающим, так и продвинутым пользователям разобраться в операционных системах. В 2004-2006г наш проект был одним из самых крупных ИТ ресурсов в рунете, на пике нас посещало более 300 000 человек в день! Наша документация по службам Windows и автоматической установке помогла огромному количеству пользователей и сисадминов. Мы с уверенностью можем сказать, что внесли большой вклад в развитие ИТ сообщества рунета. Но... время меняются, приоритеты тоже. И, к сожалению, пришло время сказать До встречи! После долгих дискуссий было принято решение закрыть наш проект. 1 августа форум переводится в режим Только чтение, а в начале сентября мы переведем рубильник в положение Выключен Огромное спасибо за эти 24 года, это было незабываемое приключение. Сказать спасибо и поделиться своей историей можно в данной теме. С уважением, ваш призрачный админ, BigMac... |
|
Компьютерный форум OSzone.net » Программирование, базы данных и автоматизация действий » Скриптовые языки администрирования Windows » PowerShell - [решено] Backup Switch conf(Вызов powershell ), не работает скрипт. |
|
PowerShell - [решено] Backup Switch conf(Вызов powershell ), не работает скрипт.
|
Новый участник Сообщения: 2 |
Добрый день!
Ситуация следующая: Есть скрипт Get-Telnet.ps1 Скрытый текст
<#
.SYNOPSIS Simple script to connect to a server using Telnet, issue commands and capture all of the output. .DESCRIPTION I wrote this script to connect to my Extreme Network switches and download their configuration. I've also gotten it to work on Dell switches, though I had to adjust the WaitTime up a little bit to get all of the output. Because it is expected that you will be wanting to attach to several different devices to get their configurations I wrote this as a Function. The intention is that at the bottom of the script you will have a list of devices you want to capture, and they may have different command and WaitTime requirements (as well as different output files). I put several examples the script below, with full explanations in the Help Section. .PARAMETER Commands An array with a single command in each element. Can be input from a file-- using Get-Content--can come from the pipeline or be specified directly from the parameter. Note about Commands: If you have a dollar sign in your password you MUST escape it in order for it to work: Example: -Commands "admin","$ecurePa$$word" This will not work! Example: -Commands "admin","`$ecurePa`$`$word" This WILL work .PARAMETER RemoteHost Name or IP address of the host you wish to connect to. .PARAMETER Port Port number you need to attach to. .PARAMETER WaitTime The amount of time the script waits in between issuing commands, in Milliseconds. When you run this script you must take a look at the output file to make sure you got all of the output you want. If things are cut off then the script is running too quickly and you have to slow it down by using a higher number. 1000 milliseconds is 1 second. .PARAMETER OutputPath Full path and file name of where you want the script to save the output. .INPUTS String input from Pipeline. .OUTPUTS Text file at specified location. .EXAMPLE Get-Telnet -RemoteHost "192.168.1.2" -OutputPath "\\server\share\hqswitches.txt" Will Telnet to 192.168.1.2 and execute the default commands, saving the output on the server as hqswitches.txt .EXAMPLE Get-Telnet -RemoteHost "10.10.10.2" -Commands "admin","password","terminal datadump","show run" -OutputPath "\\server\share\DellHQswitches.txt" -WaitTime 2000 Will Telnet to a Dell switch at 10.10.10.2, login using admin/password. Issues the command terminal datadump (which tells Dell to not pause output) and than so the full running configuration and save the output to the server as DellHQSwitches.txt. The WaitTime had to be adjusted to up because the script was running too fast for the switch. .EXAMPLE Get-Telnet -RemoteHost "192.168.10.1" -Commands "admin","password","terminal pager 0","show run" -OutputPath "\\server\share\CiscoFirewall.txt" An example of how to connect to a Cisco ASA firewall and save the running config to a file. .EXAMPLE Get-Content "c:\scripts\commands.txt" | Get-Telnet -RemoteHost "192.168.10.1" -OutputPath "\\server\share\ciscoswitch.txt" -WaitTime 1500 Get-Telnet -Commands (Get-Content "c:\scripts\commands.txt") -RemoteHost "192.168.10.1" -OutputPath "\\server\share\ciscoswitch.txt" -WaitTime 1500 Two examples of how to use Get-Content to pull a series of commands from a text file and execute them. .NOTES Author: Martin Pugh Twitter: @thesurlyadm1n Spiceworks: Martin9700 Blog: www.thesurlyadmin.com Changelog: 1.0 Initial Release .LINK http://community.spiceworks.com/scri...issue-commands #> Function Get-Telnet { Param ( [Parameter(ValueFromPipeline=$true)] [String[]]$Commands = @("username","password","disable clipaging","sh config"), [string]$RemoteHost = "HostnameOrIPAddress", [string]$Port = "23", [int]$WaitTime = 1000, [string]$OutputPath = "\\server\share\switchbackup.txt" ) #Attach to the remote device, setup streaming requirements $Socket = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port) If ($Socket) { $Stream = $Socket.GetStream() $Writer = New-Object System.IO.StreamWriter($Stream) $Buffer = New-Object System.Byte[] 1024 $Encoding = New-Object System.Text.AsciiEncoding #Now start issuing the commands ForEach ($Command in $Commands) { $Writer.WriteLine($Command) $Writer.Flush() Start-Sleep -Milliseconds $WaitTime } #All commands issued, but since the last command is usually going to be #the longest let's wait a little longer for it to finish Start-Sleep -Milliseconds ($WaitTime * 4) $Result = "" #Save all the results While($Stream.DataAvailable) { $Read = $Stream.Read($Buffer, 0, 1024) $Result += ($Encoding.GetString($Buffer, 0, $Read)) } } Else { $Result = "Unable to connect to host: $($RemoteHost):$Port" } #Done, now save the results to a file $Result | Out-File $OutputPath } #Edit the seconds below to fit your needs #Extreme Network Switch #Get-Telnet -RemoteHost "192.168.1.2" -Commands "username","password","disable clipaging","sh config" -OutputPath "\\server\share\hqswitches.txt" #Dell Switch #Get-Telnet -RemoteHost "10.10.10.2" -Commands "admin","password","terminal datadump","show run" -OutputPath "\\server\share\DellHQswitches.txt" -WaitTime 2000 #Cisco ASA #Get-Telnet -RemoteHost "192.168.10.1" -Commands "admin","password","terminal pager 0","show run" -OutputPath "\\server\share\CiscoFirewall.txt" #Use a command file #Get-Telnet -Commands (Get-Content "c:\scripts\commands.txt") -RemoteHost "192.168.10.1" -OutputPath "\\server\share\ciscoswitch.txt" -WaitTime 1500 Function Get-Telnet я подцепил к модулю ISE при выполнении входа в powershell и затем выполнении команды Скрытый текст
Get-Telnet -RemoteHost "192.168.0.1" -Commands "user", "pasword", "copy running-config tftp:", "tftpname", "filename.txt" -OutputPath D:\backup\sw.txt -WaitTime 1500
все работает, однако если запуск через cmd Скрытый текст
powershell -NoExit -Command "& {Get-Telnet -RemoteHost "192.168.0.1" -Commands "user", "password", "copy running-config tftp:","tftpname", "filename.txt" -OutputPath D:\backup\sw.txt -WaitTime 1500}"
выскакивает ошибка Скрытый текст
Get-Telnet : Не удается найти позиционный параметр, принимающий аргумент "Syste
m.Object[]". строка:1 знак:4 + & {Get-Telnet -RemoteHost 192.168.0.1 -Commands user, password, copy running- con ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ + CategoryInfo : InvalidArgument: ( ![]() ingException + FullyQualifiedErrorId : PositionalParameterNotFound,Get-Telnet Можно ли как-то решить проблему, параметры ввода команд интересны именно в таком формате(т.е. в теле команды), т.к. скрипт выполняется через по THE DUDE и туда подставляются значения -RemoteHost и "filename.txt". При этом, если команды находятся в файле Скрытый текст
powershell -command "& {Get-Telnet -Commands (Get-Content "D:\1\commands.txt") -RemoteHost "192.168.0.1" -OutputPath D:\backup\sw.txt -WaitTime 1500}" все опять же работает. |
|
Отправлено: 16:24, 13-11-2015 |
Ветеран Сообщения: 1259
|
Профиль | Отправить PM | Цитировать |
Отправлено: 16:32, 13-11-2015 | #2 |
Для отключения данного рекламного блока вам необходимо зарегистрироваться или войти с учетной записью социальной сети. Если же вы забыли свой пароль на форуме, то воспользуйтесь данной ссылкой для восстановления пароля. |
Новый участник Сообщения: 2
|
Профиль | Отправить PM | Цитировать Спасибо, все заработало!
|
Отправлено: 08:45, 16-11-2015 | #3 |
![]() |
Участник сейчас на форуме |
![]() |
Участник вне форума |
![]() |
Автор темы |
![]() |
Сообщение прикреплено |
| |||||
Название темы | Автор | Информация о форуме | Ответов | Последнее сообщение | |
CMD/BAT - [решено] Powershell вызов из cmd | c4uran | Скриптовые языки администрирования Windows | 7 | 15-09-2015 10:53 | |
Интерфейс - не работает быстрый вызов Win + X | fraskini | Microsoft Windows 8 и 8.1 | 2 | 04-03-2014 03:32 | |
FreeBSD - Не работает squid.conf. | Ruslan19891989 | Общий по FreeBSD | 3 | 26-03-2012 00:22 | |
CMD/BAT - [решено] Вызов функции из скрипта powershell | ferget | Программирование и базы данных | 0 | 03-06-2011 03:33 | |
Switch/802.3 - Не работает инет Switch ProCurve 1700-24 (J9080A) | rednax | Сетевое оборудование | 1 | 15-03-2011 12:29 |
|