Execute multiple commands via SSH and PowerShell - windows

I successfully managed to connect to a Cisco IE-2000-L switch via SSH. I used the Renci SSH.NET library.
Starting guide: http://vwiki.co.uk/SSH_Client_(PowerShell)
My working code is
# Load SSH library (for .NET 4.0 and PowerShell 3)
$DllPath = "D:\temp\Renci.SshNet.dll"
[void][reflection.assembly]::LoadFrom( (Resolve-Path $DllPath) )
# Connect to switch (Cisco IE2000-L) with IP, port, username, password
$SshClient = New-Object Renci.SshNet.SshClient('172.20.91.30', 22, 'admin', 'mypassword')
$SshClient.Connect()
# execute one command on Cisco switch
$SshCommand = $SshClient.RunCommand('show arp')
# show result
$SshCommand.Result
# close SSH connection
$SshCommand.Dispose()
$SshClient.Disconnect()
$SshClient.Dispose()
My problem is
The above code sends just one command. But I want to execute several commands consecutively without closing and reopening a session.
If I add a second command right after the first one
# execute one command on Cisco switch
$SshCommand = $SshClient.RunCommand('show arp')
$SshCommand = $SshClient.RunCommand('show start')
...the script hangs and never finishes. What am I doing wrong?
Minor relevant information
My main goal is to send multiple commands at once to a Cisco switch
I already tried Plink together with batch cmd input. It's not reliable enough. It works sometimes and sometimes not.
I already tried telnet scripting. Too awkward.

Related

Writing Automated scripts to configure device

My requirement is like this:
I need to log in to a remote device (say Router/switch) and execute following commands.
telnet xx.xx.xx.xx
//give password here
sys
interface g x/x/x
shut
desc free-port
exit
There are Hundreds of devices for which I cannot waste time doing above damn thing 100 times. I need to write a automated script which does it. so My questions are as follows:
I use Windows system, so What is the best scripting language to be used : Ruby / shell script / perl ? (I was formerly ROR Developer, so i know Ruby, Linux terminal. Now I am working in networking domain. )
What I thought was : Put all Devices into an array and using for loop, call devices one by one and execute above said commands.
I don't have knowledge of scripting, so please guide me further. I don't know where to start from.
Step 1: decide the file structure of your program.
For example, this is the simplest structure
if_admin/
|--config.yml
|--run.rb
Step 2: write a config file or a bunch of config files that contain the different parts of the commands you need to run on the targets.
For example, you can use a yaml file like this:
xx.xx.xx.xx:
password: s3cret
router-shelf: x
slot: x
port: x
yy.yy.yy.yy:
...
Step 3: implement what you want to do
require 'yaml'
require 'net/telnet'
config = YAML.load_file('./config.yml')
config.each do |host, conf|
telnet = Net::Telnet.new('Host' => host)
telnet.login(conf['password'])
telnet.puts <<-CMD
sys
interface g #{conf['router-shelf']}/#{conf['slot']}/#{conf['port']}
shut
desc free-port
CMD
telnet.close
end
If you can use expect script , you are in luck.
#!/usr/bin/expect
set timeout 60
set cmds [list "ssh host1 ..." "ssh host2 ..." "ssh host3 ..."]
foreach cmd $cmds {
spawn -noecho bash -c $cmd
expect {
-re "password" {
exp_send "$env(PASS_WORD)\"
exp_continue
}
eof { wait } ; # at this time the last spawn'ed process has exited
}
}
Here is the rough idea of above script :-
set cmds [list.... will be used as list to store set of commands.
foreach will iterate though those commands
spawn will spawn process for each of the command. you can write multiple command with single telnet in bash, just break down commands using \ (backslash) so it is easily readable and extendable.
expect block will pass password whenever it encounter certain regex.
eof will wait till all commands in spawn process are finish.
set timeout -1 will keep loop running. i think default time for expect script is 10secs.
You can create one more foreach loop for host-list.
I think this will be enough to get you started for your automation process.
As to the question of "What is the best scripting language to be used", I would say go with one that does what you need and one that you're comfortable with using.
If you want to go with Perl, one module that you could use is Net::Telnet. Of course, you'll need Perl itself. I'd recommend using Strawberry Perl, which should already have Net::Telnet installed.
Another possible route is to use putty, which is a SSH and telnet client. You could combine that with TTY Plus, which provides an interface that uses tabs for different putty sessions. And it lets you issue commands to multiple putty sessions. This is one possibility that wouldn't involve a lot of code writing.

ssh perl script not running

I am trying to write a script that will ssh to a remote machine in perl.
I'm not sure what's wrong but when I run the script, it prompts me for the root password and ends up with blank output after I give the password.
Here's my script:
#!/usr/bin/perl
use strict;
use warnings;
my #id=`ssh expert\#x.x.x.x`;
print"#id";
That is what you have asked your program to do. This line
`ssh expert\#x.x.x.x`
Starts a new subprocess running ssh with the given parameters
Exits that subprocess and returns any text output from ssh
You presumably need to interact with the remote system once you have connected, so you either need the perl process to connect to the remote system, or you need to be able to listen and talk to the subprocess that hash connected before it exits
The first is by far the simplest solution. If you use the Net::OpenSSH module and read its documentation then you will see that you can open a connection by creating an object. You can then send commands and retrieve the output using that object's capture method
I would advice against using system ssh command inside perl code for below reasons:
It makes parsing output difficult
Error handling becomes difficult
Less programming flexibility
Rather, use a CPAN library, e.g. Net::SSH::Perl for firing SSH commands from Perl code.
Its simple to open a shell using this module as described below:
$ssh->shell
Opens up an interactive shell on the remote machine and connects it to your STDIN. This is most effective when used with a pseudo tty; otherwise you won't get a command line prompt, and it won't look much like a shell. For this reason--unless you've specifically declined one--a pty will be requested from the remote machine, even if you haven't set the use_pty argument to new (described above).
This is really only useful in an interactive program.
In addition, you'll probably want to set your terminal to raw input before calling this method. This lets Net::SSH::Perl process each character and send it off to the remote machine, as you type it.
To do so, use Term::ReadKey in your program:
use Term::ReadKey;
ReadMode('raw');
$ssh->shell;
ReadMode('restore');
Below is a quick example that demonstrates how easy it would be to use the same module to fire and parse command output:
use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new($host);
$ssh->login($user, $pass);
my($stdout, $stderr, $exit) = $ssh->cmd($cmd);
Link to Net::SSH::Perl cpan documentation: http://search.cpan.org/~schwigon/Net-SSH-Perl-1.42/lib/Net/SSH/Perl.pm
Another module which I prefer to use is Net::OpenSSH: http://search.cpan.org/~salva/Net-OpenSSH-0.70/lib/Net/OpenSSH.pm
use Net::OpenSSH;
my $ssh = Net::OpenSSH->new($host);
$ssh->error and
die "Couldn't establish SSH connection: ". $ssh->error;
$ssh->system("ls /tmp") or
die "remote command failed: " . $ssh->error;
my #ls = $ssh->capture("ls");
$ssh->error and
die "remote ls command failed: " . $ssh->error;
my ($out, $err) = $ssh->capture2("find /root");
$ssh->error and
die "remote find command failed: " . $ssh->error;
my ($rin, $pid) = $ssh->pipe_in("cat >/tmp/foo") or
die "pipe_in method failed: " . $ssh->error;
print $rin "hello\n";
close $rin;

Netcat to run subsequent command after connecting server via shell script in unix

I am fresh programmer on shell script. i want to do some automation using nc command via shell scripting.
I need to run certain command after connecting server with selected port using nc . server is listening on connected port. we can get prompt to pass content while running from terminal. but i need to pass content many times. So I made a shell file which is containing following code but response is not coming
#!/bin/bash
#test.sh
function nc_input {
echo "ABCD,R,1,5151670,512173140137353,01141456843,0"
}
nc_input | nc 10.200.16.223 7913

How to enter a password into another process prompt from Ruby

I am writing an application that needs to run command on a remote Raspberry PI using a revssh script. revssh is a custom script that implements to some level the Revssh protocol concepts. it uses ssh reverse tunneling to send commands from the server to the clients.
I am using Ruby 2.1, I tried to do this using IO.popen but it does not work, so I tried the following:
# revssh (short for reverse ssh ) enables the execution of remote commands
# from the server on connected clients, like the 'psu_pi_analytics' here. but it requires
# to enter a root password each time you want to run a command using 'revssh -c'
IO.popen('revssh -c psu_pi_analytics uname -a', 'w+') do|io|
io.puts 'password' # enter the password when prompted
puts io.gets
end
this code work if the command to execute run on the local machine, but not in my case.
So any thoughts, or suggestions.
What important here is how to deal with the new connection created by the revssh script using ssh, which is managed in the terminal if the script is run directly from the terminal.
Edit:
By not work I mean it still prompts for the password, even if I puts the password to the io.
You can use an Expect-like library (e.g. RExpect, Expect4r) for interacting with other processes.
Another question related to this: Is there an Expect equivalent gem for Ruby?

Ruby scripting - Telnet Hangs During Login

I am trying to do some basic scripting using ruby to log in to a windows machine via telnet and pull some files over using the dos command line ftp. When I do this manually everything goes swimmingly but when I try it via ruby I'm getting an error in the login call.
Here is my test program in its entirety:
require 'net/telnet'
tn = Net::Telnet::new("Host"=>"xxx.xxx.xxx.xxx", "Timeout"=>25, "Output_log"=>"output_log.log", "Dump_log"=> "dump_log.log", "Prompt"=>"C:.*>")
tn.login("administrator", "xxxxxxx") {}
tn.cmd('dir')
exit
The contents of output_log don't betray anything as being wrong:
Trying 208.10.202.187...
Connected to 208.10.202.187.
Welcome to Microsoft Telnet Service
login: administrator
password:
*===============================================================
Welcome to Microsoft Telnet Server.
*===============================================================
C:\Documents and Settings\Administrator>
Same for the dump_log which has very similar but awkwardly formatted contents. When I run the program it sits around for a while and then outputs the following error:
PS C:\code\tools\deployment> ruby test.rb
C:/Ruby/lib/ruby/1.8/net/telnet.rb:551:in `waitfor': timed out while waiting for more data (Timeout::Error)
from C:/Ruby/lib/ruby/1.8/net/telnet.rb:685:in `cmd'
from C:/Ruby/lib/ruby/1.8/net/telnet.rb:730:in `login'
from test.rb:3
Which leads me to suspect that the telnet class is not recognizing the command prompt. I've tried several different regex strings for the Prompt parameter, including the default and nothing seems to help.
I think the prompt field needs to be a regexp, not a string
Try
tn = Net::Telnet::new("Host"=>"xxx.xxx.xxx.xxx", "Timeout"=>25,
"Output_log"=>"output_log.log", "Dump_log"=> "dump_log.log",
"Prompt"=> /C:.*>/)

Resources