SSH Login Script

Bash(expect) script to login remote machines via ssh.
Append -L:”local port”:”Remote host”:Remote port” to do port fowarding.
Associate sh files with /bin/mintty.exe if you are using cygwin.

To one host
#!/bin/bash

host=host
name=hostname
user=user
pass=pass
log=/cygdrive/c/Users/Public/logs/"$name"_`date +%d_%h_%Y_%H%M%S`
noansi=/cygdrive/c/Users/Public/script/no_ansi.pl

expect -c "
spawn ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null-l $user $host
expect password:
send $pass\n
interact
" | tee -a "$log"_raw.txt
perl $noansi "$log"_raw.txt > "$log".txt

Send commands to more than one host(telnet)
#!/bin/bash

hosts="host host1 host2"
user=user
pass=pass

for host in $hosts; do
expect -c "
spawn telnet \"$host\"
expect login:
send \"$user\n\"
expect Password:
send \"$pass\n\"
expect $
send \"ping 10.0.0.1\n\"
expect $
send \"exit\n\"
interact
"
done

Perl script to remove all control characters from recorded files by tee.
Taken from http://unix.stackexchange.com/questions/14684/removing-control-chars-including-console-codes-colours-from-script-output

mp_ansi.pl
#!/usr/bin/perl
use encoding 'shiftjis', STDIN=>'shiftjis', STDOUT=>'shiftjis';
while () {
s/ \e[ #%()*+\-.\/]. |
\r | # Remove extra carriage returns also
(?:\e\[|\x9b) [ -?]* [@-~] | # CSI ... Cmd
(?:\e\]|\x9d) .*? (?:\e\\|[\a\x9c]) | # OSC ... (ST|BEL)
(?:\e[P^_]|[\x90\x9e\x9f]) .*? (?:\e\\|\x9c) | # (DCS|PM|APC) ... ST
\e.|[\x80-\x9f] //xg;
1 while s/[^\b][\b]//g; # remove all non-backspace followed by backspace
print;
}

Advertisements
Leave a comment

2 Comments

  1. Ubu01

     /  November 2, 2015

    mp_ansi.pl is a typo for no_ansi?
    I had a similar script in the past to log in to different hosts.

    Reply
    • Yes, it’s a typo. I’ll fix it.
      Thank you for telling me.

      These days I don’t use the no ANSI perl script. I just cat the raw log file in my terminal when I want to see it without control characters.

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: