[TriLUG] Single line scripts

Jon.Carnes@peoplefluent.com via TriLUG trilug at trilug.org
Tue Sep 6 09:56:30 EDT 2016


I use pexpect scripts (basically a python version of expect - but a nicer easy to use version)
Here is a script that logs me into a sever and then gives me control...
Note: I've removed a bunch of code (to handle each exception), to make the example simpler.

#! /usr/bin/python
#
# imput the name or ip address of a server to inspect.
#  - handles first time logins
#  - uses either default or alternate password login
#  - resets alternate login to default
#  
#  st - login and then give control to the user...
#  Jon Carnes - Aug 2016 version 1.0
#
import pexpect
import sys
import time
#
# Input from the command line the server to log into (myserver.local.ip.net)
CHKcla = len(sys.argv)
if ( CHKcla <= 1 ):
   print "  ... Include the name or ip of the server you want to attach to on the command line"
   exit
# end of check for command line argument
Server = str(sys.argv[1])
ScreenOn = 0
# Look for command line switches passed in with ip
if ( CHKcla == 3 ):
   Server = str(sys.argv[2])
   Switch = str(sys.argv[1])
   CHKsw = Switch.find("s")
   if CHKsw >= 0:
      ScreenOn = 1
   # end of Screen switch check
# end of parsing command line arguements
Action = "ssh socialtext@" + Server
mypassword = "Password.1234"   # the safest password I know
child = pexpect.spawn(Action)
#child.logfile = sys.stdout
index = child.expect(['assword:', '(yes/no)', pexpect.EOF, pexpect.TIMEOUT])
#child.expect('password:')
if index == 0:
   child.sendline(mypassword)
else:
   child.sendline('yes')
   child.expect('assword:')
   child.sendline(mypassword)
# end of nasty check for first connection
#
#child.expect(':~$')   the "$" is interpreted as a meta character
index = child.expect(['\$','assword:','Changing password',pexpect.EOF,pexpect.TIMEOUT])
#child.expect(':~')
if index ==0:
   child.sendline('sudo su -')
   jndex = child.expect(['user:',':~#'])
   if jndex == 0:
      child.sendline(mypassword)
   if jndex == 1:
      child.sendline("echo sudo should not act this way")
   # end check for recent sudo attachment
elif index == 1:
   print "  ... stored password is incorrect"
   child.close()
   sys.exit()   
elif index == 2:
   # password has expired...
   print "  ... Password expired "
   child.close()
   sys.exit()
elif index == 3:
   print "  ... Lost connection"
   child.close()
   sys.exit()
elif index == 4:
   print "  ... I'm having a problem logging in to " + Server + "... sorry... stopping"
   child.close()
   sys.exit()
# end of attempted login 
### to run in screen or not to run in screen - that is the question ###
child.expect(':~#')
if ( ScreenOn == 1 ):
   child.sendline('screen -ls')
   child.expect(':~#')
   a = child.before
   CHK = a.find('.stx')
   if CHK > 0:
      child.sendline('screen -x stx')
      child.expect('')
   else:
      child.sendline('screen -S stx')
      child.expect(':~#')
   # end enter into screen session
# end of ScreenOn processing
print child.before 
child.setwinsize(40,160) 
child.interact()
#child.sendline('exit')
#child.sendline('exit')
sys.exit()
time.sleep(0.5)
CHK = child.isalive()
if CHK:
   child.close()
# end of closed check... and we are outta here

Hope someone finds it useful.
Note - I use variants of this to inspect servers and inject updates in an environment where I'm not allowed to setup keyed ssh access.

Jon Carnes 

On 9/6/16, 12:47 AM, "TriLUG on behalf of Lee Fickenscher via TriLUG" <trilug-bounces+jonc=nc.rr.com at trilug.org on behalf of trilug at trilug.org> wrote:

    I'll third aliases/functions and also add that you should check out "man
    ssh_config" for those oft-used unwieldy ssh connections.
    
    -Lee
    
    On Mon, Sep 5, 2016 at 9:07 PM, Brian Gerard via TriLUG <trilug at trilug.org>
    wrote:
    
    > On 09/05/2016 03:34 PM, Grawburg via TriLUG wrote:
    > >
    > > I have long commands I enter in a terminal, such as starting
    > > connecting to a Raspberry Pi located several floors away with ssh, or
    > > setting up a connection to my NAS (rather than having a line in
    > > /etc/fstab).
    > > I can simply have a text file saved and do a copy and paste into
    > > terminal each time I need it, but I'd like to turn it into a what I
    > > would have called a .bat file decades ago.
    > > Is this something I should learn to to do in bash? I don't need
    > > multiple lines, there is no extra coding, just a single line.
    > >
    > > Thanks,
    > > Brian Grawburg
    >
    > Going by your description, I would second the recommendation for aliases
    > or functions.  The decision between them will more or less come down to
    > whether or not you need to pass arguments to the commands.
    >
    > For example...
    >
    > #
    > # Use an alias if the command is exactly the same every time.
    > #
    > bash$ alias dfhome='ssh -q my-home-machine "df -h"'
    > bash$ dfhome
    > Filesystem      Size  Used Avail Use% Mounted on
    > /dev/sda1       312G  112G  185G  38% /
    > tmpfs           385M  896K  384M   1% /run
    > /dev/sda2        30G  179M   28G   1% /tmp
    > /dev/sda3       184G   65G  110G  38% /home
    >
    > #
    > # Or a function if you want to be able to change behavior.
    > #
    > bash$ function dfon() { ssh -q $1 "df -h"'; }
    > bash$ dfon my-home-machine
    > Filesystem      Size  Used Avail Use% Mounted on
    > /dev/sda1       312G  112G  185G  38% /
    > tmpfs           385M  896K  384M   1% /run
    > /dev/sda2        30G  179M   28G   1% /tmp
    > /dev/sda3       184G   65G  110G  38% /home
    > bash$ dfon some-other-machine
    > # ...etc...
    >
    > Try it, tweak it, repeat.   Once you've got it where you want it, add it
    > to your .bashrc and you'll have it whenever you log in.
    >
    > A shell script in your own ~/bin directory or the like is absolutely
    > fine as well, but sounds a trifle heavy for what you've described.
    > However, I would say the opposite if these are things you'll need to ssh
    > in and run without starting up a login shell (like 'ssh my-host
    > "one-of-these-commands"').  In that case you will want a separate shell
    > script rather than aliases or functions in your .bashrc.
    >
    > I covered some of this in the "bash tips n tricks" talk I gave a couple
    > of years back.  You can find the materials for that at:
    > https://github.com/briangerard/bash_class
    > (the section on aliases begins on slide 32, and functions begin on
    > slide 38)
    >
    > ...and the recording is viewable here:
    > https://www.youtube.com/watch?v=J4_tFm4iRpc
    >
    > HTH-
    > Brian
    >
    >
    > --
    > This message was sent to: elfick at gmail.com <elfick at gmail.com>
    > To unsubscribe, send a blank message to trilug-leave at trilug.org from that
    > address.
    > TriLUG mailing list : http://www.trilug.org/mailman/listinfo/trilug
    > Unsubscribe or edit options on the web  : http://www.trilug.org/mailman/
    > options/trilug/elfick%40gmail.com
    > Welcome to TriLUG: http://trilug.org/welcome
    >
    -- 
    This message was sent to: Jon Carnes - cybertooth <jonc at nc.rr.com>
    To unsubscribe, send a blank message to trilug-leave at trilug.org from that address.
    TriLUG mailing list : http://www.trilug.org/mailman/listinfo/trilug
    Unsubscribe or edit options on the web	: http://www.trilug.org/mailman/options/trilug/jonc%40nc.rr.com
    Welcome to TriLUG: http://trilug.org/welcome




More information about the TriLUG mailing list