I have a some device which can communicate over Serial ports. So to make things easy we have switch which can send Serial data over IP. Now to connect to this switch we need to use SSH and then we can fire a set of commands to perform some operations.
Now I am looking a way to automate these task as I have a around 8 such devices on which I need to send some common commands and some specific command (may be present in a file).
Also I am looking a way through which I can dump what is being output over the terminal in a file so that if later we want to take a look we can do so.
So how can we write a simple chat client which can send commands over SSH (you can think of hyper terminal command send to reset the device etc) and get the results and other output back. Any thoughts will be a great help.
Below is the code which I am able to do till now
#!/usr/bin/perl if( ! defined $ARGV[0] ) { print "Usage: ssh.pl <host> <port> [ <username> [ <password> ] + ]\n"; exit; } my ($host, $port, $username, $password) = @ARGV; $username = $ENV{USER} if $username eq ""; use Expect; use IO::Pty; my $spawn = new Expect; $spawn->raw_pty(1); # This gets the size of your terminal window $spawn->slave->clone_winsize_from(\*STDIN); my $PROMPT; # This function traps WINCH signals and passes them on sub winch { my $signame = shift; my $pid = $spawn->pid; $shucks++; print "count $shucks,pid $pid, SIG$signame\n"; $spawn->slave->clone_winsize_from(\*STDIN); kill WINCH => $spawn->pid if $spawn->pid; } $SIG{WINCH} = \&winch; # best strategy #$Expect::Exp_Internal = 1; #$Expect::Log_Stdout = 0; $spawn=Expect->spawn("ssh $username\@$host -p $port"); # log everything if you want $spawn->log_file("/tmp/autossh.log.$$"); my $PROMPT = '[\]\$\>\#]\s$'; my $ret = $spawn->expect(10, [ qr/\(yes\/no\)\?\s*$/ => sub { $spawn->send("yes\n"); exp_co +ntinue; } ], [ qr/assword:\s*$/ => sub { $spawn->send("$password\n") i +f defined $password; } ], [ qr/ogin:\s*$/ => sub { $spawn->send("$username\n"); +exp_continue; } ], [ qr/REMOTE HOST IDEN/ => sub { print "FIX: .ssh/known_hosts\n"; +exp_continue; } ], [ qr/$PROMPT/ => sub { $spawn->send("echo Now try window + resizing\n"); } ], [ qr/You are now master for the port\s*$/ => sub { $spawn->send("$ +cmd\n"); exp_continue; } ], ); $spawn->send("$cmd\r"); # Hand over control # Destroy the expect object $spawn->soft_close();
Sample session is given below
# perl ssh.pl <host name> <port> <username> <password> Password: Authentication successful. Starting DPA for port 1 Authentication successful. Escape Sequence is: Control-] You are now master for the port.
Now once I have You are now master for the port. I need to send some commands but I am not able to do so. So any thoughts how to fix this script.
In reply to Simple SSH based chat client by techman2006
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |