Linux.com

Feature

CLI Magic: OpenSSH + Bash

By Mark McGrew on January 23, 2006 (8:00:00 AM)

Share    Print    Comments   

User level: Advanced

Other system administrators have fantastic toolboxes for their work. My tools consist of two everyday programs: OpenSSH and the GNU Bourne-Again Shell (bash). No other tool, whether console-based or GUI, has been so consistently useful to me as these two programs.

As a system administrator, I have used OpenSSH's piping abilities more times than I can remember. The typical ssh call gets me access to systems for administration with a proven identity, but ssh is capable of so much more. In combination with bash's subshell invocation, OpenSSH can distribute the heavy work, reduce trace interference on a system under test, and make other "impossible" tasks possible. I've even used it to make Microsoft Windows remote administration easier.

In the examples below, I have tried to avoid GNU-specific idioms for tools which have non-GNU counterparts. This practice improves portability of shell scripts in heterogeneous environments.

OpenSSH as a pipe

A pipe normally feeds the output of one program to the input of another. OpenSSH allows these two programs to run on different computers. For example:

$ ls -lR | ssh remotehost grep lost-file.txt

This (contrived) example shows the simplicity of connecting programs on a network, whether trusted or untrusted. OpenSSH even passes the exit code of the remote command back to the local shell.

Note two things here. First, the local shell interprets the command line before calling ssh. This means the usual quoting rules apply. In particular, any environment variables to be evaluated remotely must have their dollar signs escaped. If you forget to do this, the local shell will evaluate the variables, before invoking OpenSSH. This example shows the difference:

$ ssh localhost echo \$PATH #escaped--evaluated remotely
Password:
/usr/bin:/bin:/usr/sbin:/sbin
$ ssh localhost echo $PATH #unescaped--evaluated locally
Password:
/usr/local/bin:/usr/bin:/bin:/opt/bin:/usr/i686-pc-linux-gnu/gcc-bin/3.4.4:/opt/
blackdown-jdk-1.4.2.02/bin:/opt/blackdown-jdk-1.4.2.02/jre/bin:/usr/qt/3/bin:/us
r/kde/3.4/bin:/usr/kde/3.3/bin:/usr/games/bin:/opt/insight/bin

This shows the other important point to remember. OpenSSH may not apply your login shell profile (such as ~/.bash_profile) or even the non-interactive shell profile (~/.bashrc), so your paths, aliases, and functions might not be available. The sshd manual page has more information under the LOGIN PROCESS heading.

Backup to remote storage

Here's a problem my office faces regularly. Part of our quality testing involves backups and restores of large files, but the nature of the files hinders good compression, and many of our systems do not have sufficient space for uncompressed local archive storage. OpenSSH lets us use another system for temporary storage:

TMPFILE=${HOSTNAME}-${PID}
tar cf - dirname | ssh remotehost "cat > ${TMPFILE}.tar" # quoted for remote redirection

This creates the tar locally, then feeds the stream through OpenSSH into $TMPFILE on the remote host. The restoration is simply the reverse sequence:

ssh remotehost "cat ${TMPFILE}.tar" | tar xv

Backup with remote compression and storage

When compression is necessary (and feasible), workload distribution becomes more effective with OpenSSH. Just as distcc allows multiple machines to compile simultaneously, OpenSSH lets one system create the archive, while another system compresses it:

tar cf - dirname | ssh remotehost "gzip -c > ${TMPFILE}.tar.gz"

In this case, OpenSSH carries the uncompressed archive over the network. If you're on a LAN slower than 100Mbps, you probably will not see a benefit from this. The workload on the local system does involve the OpenSSH encryption, but the compression workload is moved to the remote system.

OpenSSH may have compression enabled by the remote server, causing redundant compression workloads. To expedite the data flow through OpenSSH, try setting Compression to no in the remote system's sshd_config.

To restore the archive, again, simply reverse the data flow:

ssh remotehost "zcat < ${TMPFILE}.tar.gz" | tar xv

Backup with local compression and remote storage

One of our systems has four CPUs, making it more efficient when creating compressed archives:

tar cf - dirname | gzip -c | ssh remotehost "cat > ${TMPFILE}.tar.gz"

This speeds up the network transfer even more, by compressing the data first. Restoration is equally simple; just run:

ssh remotehost cat ${TMPFILE}.tar.gz | gunzip -c | tar xv

Parenthesized subshells, too

A pipe sequence using OpenSSH can also use parenthesized subshells, which is to say, commands enclosed in parentheses are run in a subshell. Used judiciously, they can reduce complexity:

ssh remotehost zcat ${TMPFILE}.tar.gz | ( cd /other/path ; tar xv ) | wc -l

This restores the archive to /other/path, and the wc -l command shows us the number of files restored. While tar -C /other/path would work for Linux, other Unix systems may not use GNU tar. Using bash's parentheses makes this command much more portable.

Reducing filesystem interference

One of our project leaders asked me to run a kernel call trace on a system with nearly full disks. I decided to record the trace on my desktop system instead of on the test system. According to the strace man page, the -o option allows a pipe to process the trace output, but ssh in this case required stdin/stdout for password entry. Using a named pipe on the filesystem left stdin, stdout, and stderr unchanged for the test program. I ran the following commands on the test system:

mkfifo /home/me/pipe
strace -f -o /home/me/pipe test-program & cat /home/me/pipe | ssh desktop "cat > trace-record"

The strace command went into the background, but waited until another program was ready to read from the FIFO. The tested program ran more slowly, but exceeding local disk space was not a concern.

Remote Windows administration

Finally, a trick that doesn't rely on bash, except as my login shell. Using multiple SSH connections, with X forwarding, I can use Xvnc to translate the Windows desktop to something that works in my Linux-only home environment. This sequence connects to my desktop system from outside, then forwards the Windows desktop to an X window at home:

$ ssh -X -C termsrv #from home
Password:
$ ssh -X my-desktop #from termsrv
Password:
$ vncviewer windows #from office desktop

The -C compresses the forwarded X protocol, making Xvnc much more bearable through a DSL connection. The VNC server on the Windows system is configured to run as a service, so that I can connect first, then log in as the Administrator for whatever purpose I need at the moment.

I have used many tools in both CLI and GUI to install, use, and administer both operating systems and programs. Nothing has matched the usefulness and flexibility of OpenSSH and bash together. With them, I can do much more than log in to a remote system securely. The examples shown here are a small sample of the possibilities.

Mark McGrew is a small-office system administrator in Silicon Valley.

Share    Print    Comments   

Comments

on CLI Magic: OpenSSH + Bash

Note: Comments are owned by the poster. We are not responsible for their content.

Great article!

Posted by: Anonymous Coward on January 23, 2006 07:55 PM
I found this article really useful and cool! Thanks!

#

Pass-whaa?

Posted by: Anonymous Coward on January 23, 2006 10:13 PM
I agree, ssh is a great time-saver. Of course, I prefer tcsh to bash.<nobr> <wbr></nobr>;-)

Also, why use password authentication? You can have better security and more convenience using public/private keys (passphrase-protected, of course) and ssh-agent (only have to type the passphrase once). Even better, use Gentoo's great <a href="http://www.gentoo.org/proj/en/keychain/" title="gentoo.org">keychain</a gentoo.org>, which is a pretty straight-forward script that runs on most distros.

#

Passwords - It's a good thing (TM)

Posted by: Anonymous Coward on January 23, 2006 11:13 PM
While PKI keys are more secure, they are not always more convenient. People use password authentication because it is far more convenient when portability comes into play. While PKI works great for you and your Gentoo machine, there are lots more people that use multiple machines, and multiple OSes and multiple locations. There are times when you cannot plug in or mount a USB drive with your keys and there are times when you simply don't have your USB drive with you. However, with password authentication, you can always log in, provided that you can get a SSH client.

In the past week I have logged into various machines via SSH from Netware, OSX, Linux, Windows, Solaris and AIX machines. None of the client machines were mine and it would not have been possible to mount a USB dongle on most of the clients. Without password authentication, I would not be able to get my work done.

#

Ok, just for you then.

Posted by: Administrator on January 23, 2006 11:21 PM
I think you are in a special case regarding your heavy use of many other machines. However, that does not make your point of using passwords is better valid.

Most people who I have helped support over the years as a sysadmin only use two or three machines at most. Usually its just a laptop. Convience should not be an excuse. People are intelligent and you need to give them that oppurtunity to be more secure, otherwise we just keep giving them outs.

If anything, PKI can be easier for the user because they wouldn't be constricted by some server-side password change rotation. And could cut down on the number of passwords they have to know.

Sorry Anonymous Reader, but I think you're an isolated case.

#

tar portability

Posted by: Anonymous Coward on January 24, 2006 04:18 AM
In the examples below, I have tried to avoid GNU-specific idioms for tools which have non-GNU counterparts. This practice improves portability of shell scripts in heterogeneous environments.

Good:
<tt>tar cf - dirname |<nobr> <wbr></nobr>...</tt>
Not good:
<nobr> <wbr></nobr>
<tt>... | tar xv</tt>
On some platforms, you need to explicitly specify stdin. For example, NetBSD tar tries to read from<nobr> <wbr></nobr>/dev/nrst0. A better form would be:
<nobr> <wbr></nobr>
<tt>... | tar xfv -</tt>
Also, be aware that not all implementations of tar have the -z and -j options for gzip and bzip2 compression.

#

Re:tar portability

Posted by: Anonymous Coward on January 27, 2006 11:53 AM
Solaris is the same, and it catches me out every time. I much prefer the GNU tar which fits more neatly into the behaviour of the other GNUNIX tools, and doesn't by default attempt to (for example) write to the production machine's DLT drive (oops, sorry).

#

YMMV etc.

Posted by: Administrator on January 24, 2006 12:45 PM
I am the author of the article, and yes, your advice is good. (I did say, "I tried to avoid GNU-specific idioms...") All command syntax should be verified on the applicable platform(s) for maximum flexibility.

#

my ssh script to dig remote server info

Posted by: Anonymous Coward on January 26, 2006 01:06 AM
I have created complete script using ssh to dig remote server information such as uptime, disk usage, cpu usage, RAM usage,system load,etc. from multiple servers. It is here <a href="http://bash.cyberciti.biz/monitoring/dig_remote_linux_server_information.bash.php" title="cyberciti.biz">http://bash.cyberciti.biz/monitoring/dig_remote_l<nobr>i<wbr></nobr> nux_server_information.bash.php</a cyberciti.biz>

#

Re:Sorry, mkrenz, but you are wrong ..

Posted by: Anonymous Coward on January 27, 2006 11:43 AM
.. wrong about one thing. Anonymous Reader is NOT an isolated case.

In fact, I would bet that anyone who does remote command line work at all is probably connecting to more than two or three machines in any given week.

I know that you CAN set up PKI, and that after that, its a little bit more convenient. But as you admit, this is only convenient if you only ever work with the same 2 or 3 machines, and those machines don't get rebuilt too often.

My experience is quite different to that, so the overhead of setting up and using PKI can easily outweigh the difficulty of using passwords that I'm already familiar with. Usernames and passwords have to be set up anyway. Once you have a login, you also automatically have password-based ssh connection. To me that is the easiest thing. You also mention security but again, I think you are not covering all possible scenarios. There are certainly scenarios (think isolated LAN) where security is a completely different problem from say, connecting across the internet. And yet ssh is useful on either.

As a result of this article, I will be looking more deeply into ssh - both in pipes, and in scripts - but there are a number of options I will explore before I look at PKI.

Are you sure, mkrenz, that it is not you that is the special case?

#

Re:Sorry, mkrenz, but you are wrong ..

Posted by: Administrator on January 27, 2006 12:15 PM
Are you sure, mkrenz, that it is not you that is the special case?

Possibly. It might depend on the part of the world you live in or the type of business that you work for. The other guy who replied said he is in a university environment. That is almost a completely different environment than when you work for a company.

I've been a sysadmin for almost 9 years now, have been one at 4 different companies and have friends who are sysadmins and have met even more at conferences. From what I've heard and seen, usually sysadmins only have 2 or 3 computers that they use ssh from. Maybe even just 1.

But in all this time there is definately one thing that I have seen a lot of. People who do things differently than the norm.

#

only with Cygwin+X

Posted by: Administrator on January 31, 2006 04:57 AM
Using the X protocol through SSH assumes that the desktop, or some program running on the remote, uses X for its GUI. This excludes all of the programs from M$, including the administration and Office.

The VNC protocol is a neutral system for duplicating one desktop onto another, independently of the OS layer. Besides being cross-platform, it is also smaller than a basic Cygwin installation.

As for public access, you make a bad assumption. The commands are typed in sequence, into the same X-based shell window (xterm, etc.). Notice the comments attached to each command, showing where that command is executed.

#

X forwarding...

Posted by: Administrator on January 28, 2006 12:25 AM
Your X forwarding example with vnc:


Assuming you have ssh client installed on widoze box, you can do this:

$ ssh -X -C termsrv #from home
Password:



Assuming you have sshd on windozed client running.


$ ssh -X my-desktop #from termsrv
Password:



if you are ssh into box at both point, I assume both box is publicly accessible. Most company do not allow public access to company desktop.

#

Re:Ok, just for you then.

Posted by: Administrator on January 24, 2006 06:18 AM
hate to say this, but I agree with parent. I use ssh from sometimes as many as 10 machines in one day, and even though I have keys setup for a few of them, when I grab a random machine on campus, I don't have my keys, and without pw auth, I wouldn't be able to get in. Now my passwords are pretty secure (10+ chars random caps/numbers/symbols) so, I'm not too worried about getting brute forced.

#

Another tutorial on SSH

Posted by: Administrator on January 23, 2006 08:53 PM

Just two weeks ago I gave a presentation on SSH at the Bloomington Linux Users Group, you can find the document I wrote from the presentation at the following URLs:

<a href="http://www.suso.org/docs/shell/ssh.sdf" title="suso.org">http://www.suso.org/docs/shell/ssh.sdf</a suso.org>

<a href="http://www.bloomingtonlinux.org/wiki/15th_meeting" title="bloomingtonlinux.org">http://www.bloomingtonlinux.org/wiki/15th_meeting</a bloomingtonlinux.org>

The second link has the extra stuff that was in the presentation, but not in the user document on suso.org. It also includes some basic information on how encryption works (very basic)

#

This story has been archived. Comments can no longer be posted.



 
Tableless layout Validate XHTML 1.0 Strict Validate CSS Powered by Xaraya