Industry guru Dave Taylor offers free tech support on a wide variety of technical and business topics, including HTML, Apple iPhone, online advertising, Cascading Style Sheets, Web design, management, Unix, Linux, search engine optimization, online dating, Mac OS X, shell script programming and Microsoft Windows.

Automating SSH with a shell script

I am trying to write a shell script for automated ssh. vairable user and passwd have initialized correctly, but when I use the following it still prompting me for the password.

ssh -l $user cisdevapp1
$passwd
uptime
exit

I have also tried the following

ssh -l $user cisdevapp1 < $passwd
uptime
exit
EOF

and no luck. Please help?


Dave's Answer:

For all that the SSH program suite is wonderful, one of its weaknesses is that it's not at all easy to specify a password to allow you to include it (or its file transfer cousin sftp) in a shell script.

When I worked with sftp for my book Wicked Cool Shell Scripts I actually ended up deciding that it was easier and more secure to actually prompt for the password rather than save it in a data file or similar.

However, there are a couple of ways that I think you could explore to make SSH completely script-friendly:

1. Config files

if you can add data files on both your system and the remote system you'll be connecting to, you can try adding data to the /etc/hosts.equiv or /etc/shosts.equiv files. As the man page says:

"First, if the machine the user logs in from is listed in /etc/hosts.equiv or /etc/shosts.equiv on the remote machine, and the user names are the same on both sides, the user is immediately permitted to log in. Second, if .rhosts or .shosts exists in the user's home directory on the remote machine and contains a line containing the name of the client machine and the name of the user on that machine, the user is permitted to log in. This form of authentication alone is normally not allowed by the server because it is not secure."

As they say, this isn't a particularly secure method at all, and has lots of holes that leave you open to exploitive hacks. Most smart admins will automatically axe any '.rhosts' or "hosts.equiv" files either in /etc (hugely dangerous) or in an individual user's home directory (still pretty dangerous).

Instead, there's a more complex solution that involves both using "rhosts" combined with RSA authentication. Again, quoting from the man page:

"The second authentication method is the rhosts or hosts.equiv method combined with RSA-based host authentication. It means that if the login would be permitted by $HOME/.rhosts, $HOME/.shosts, /etc/hosts.equiv, or /etc/shosts.equiv, and if additionally the server can verify the client's host key (see /etc/ssh_known_hosts and $HOME/.ssh/known_hosts in the FILES section), only then is login permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing and routing spoofing. [Note to the administrator: /etc/hosts.equiv, $HOME/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.]"

Again, this is a bit more secure than the first method, but still not a great solution unless you have otherwise strong security on both systems and neither is exposed to the public internet.

2. SSH_ASKPASS

The other approach you could try taking with ssh within a script is to experiment with the environment variable SSH_ASKPASS . Here's what the man page explains:

"If ssh needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal. If ssh does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase. This is particularly useful when calling ssh from a .Xsession or related script. (Note that on some machines it may be necessary to redirect the input from /dev/null to make this work.)"

Not very clearly explained, but enough that you could probably start poking around and find something or other to help you on your exploration.

3. sftp -b batch mode

The sftp program also has a "-b" flag for batch mode, with its man page including this intriguing comment: "Since it lacks user interaction it should be used in conjunction with non-interactive authentication." However, there's no further documentation on how to work with non-interactive authentication so I don't know how you'd learn more about it.

I realize this isn't the answer you were seeking, but I hope it's useful and informative nonetheless. If someone knows how to make ssh / sftp more script-friendly, please add it as a comment.



Help others find this article at Del.icio.us, Digg, Netscape, Reddit, and Stumble Upon    

Subscribe!

Never miss another useful Q&A article again! Subscribe to AskDaveTaylor with Google Reader.

Comments

You have to use ssh-agent to get password-less logins using pre-exchanged keys: http://www.hackinglinuxexposed.com/articles/20021226.html

Owen

Posted by: Owen at November 17, 2005 9:52 PM

If you're on a Mac OS X system, use the SSHKeyChain app to help manage your keys. http://www.sshkeychain.org/. That combined with the earlier comment will get you up and running.

Posted by: Michael Clark at November 17, 2005 11:19 PM

To use sftp in a script without user interaction (non-interactive authentication) for AIX, please see this article, which explains how to set up the RSA authentication.

http://www-1.ibm.com/support/docview.wss?uid=isg1pTechnote1279

Posted by: Sunil Ray at February 22, 2006 6:51 AM

Its all about using the right tool for the job.

To script interactive sessions, you need to use Expect.

For example to login to an anonymous ftp server and not have to manually enter the login information each time, use the following expect script:

#!/usr/bin/expect

spawn ftp $argv
expect "Name"
send "anonymous\r"
expect "Password:"
send "user@hostname.com\r"
interact

When you execute the script:

$ expect ./ftp-login.exp upload.sf.net

It will log you in and leave you at the ftp> prompt, where it enters interactive mode. When you are done, simple exit the ftp session normally (quit command) and the expect session will terminate.

Posted by: lowkey at March 4, 2006 11:01 PM

If you are attempting to login to a server without having to enter a pass-phrase, then then we would recommend the use of a SSH agent. Under OS X there is an excellent application called "SSHKeychain" [ http://www.sshkeychain.org ]

Using key pairs for authentication is generally accepted to be more secure than using passwords. However, increased security will cost you simplicity, because you will now require a private key and an SSH agent application to be running in order to access your server without entering a password.

If you decide to use key pairs then you will need to disable the password authentication to the server to gain the benefits of increased security.

Posted by: Lucid Information Systems at April 10, 2006 6:11 PM

To expand on the expect example:

For SFTP, make the script like so:
#!/usr/local/bin/expect

spawn sftp $argv
expect "password:"
send "yourpass\r"
interact

Then call it like this: expect ./script user@host

Hope that helps.
MB

Posted by: MB at December 1, 2006 3:09 PM

expect command is not found error is coming...plz help

Posted by: siva at January 8, 2007 1:48 AM

To make life even easier (for OSX 10.4.9) you can use macFUSE & Expect

MacFUSE --> http://code.google.com/p/macfuse/

download sshfs-0.1.0.dmg --> a mountable SSH file system

install Expect by using FINK ---> http://www.finkproject.org/index.php?phpLang=en

Write a script in expect (I keep my in /usr/local/bin) something like:

set timeout -1
spawn $env(SHELL)
match_max 100000
send -- "mkdir /volumes/req'd volume name\r"
expect -exact "$ "
send -- "sshfs @server:/what you want to mount /volumes/req'd volume name -ocache=no -onolocalcaches
-oreconnect,ping_diskarb,volname=req'd volume name\r"
expect -exact "password: "
send -- "the req'd ssh password\r"
expect -exact "$ "
expect eof
exit

This will make a directory in /volumes, and mount the drive / directory you want in "FINDER" with the name specified (req'd volume name). You can then treat the SSH drive just like any other drive

The expect script, in my case, is run from terminal, and is invoked by just typing its name -- in my case the name of the volume I am mounting

When finished just eject the drive as per normal

Posted by: Dave Scott at April 19, 2007 1:44 AM

Hi I am trying to write shell script that will accept an file as input and execute the sftp process to get file from specified server mentioned in the file ....please help and give the exact code.

Posted by: Himadri Debnath at August 9, 2007 3:14 AM

just use your keys and auth files.

Posted by: booga at November 27, 2007 9:36 PM

Thanks a lot for the information posted it helped us great deal

Posted by: vipink at May 15, 2008 5:32 AM

hi friends,

please help me to write a script to take over a sftp session from a remote machine. providing the password through the same script and fetch files from that machine to my home directory.

will appretiate your help.

Posted by: arnab at May 27, 2008 7:25 AM

you can use 'plink' utility where u can specify password to ssh in plain text in the commandline, this enables you write batch processing/automated ssh execution.

plink available on the openssh website.

plink -ssh -pw password username@hostname df -k

Posted by: Ismail at January 29, 2009 7:09 AM

I have something to say, now that you mention it, but ...
Starbucks coffee cup I do have a lot to say, and questions of my own for that matter, but first I'd like to say thank you for all your efforts on this Web site by buying you a cup of coffee!

I do have a comment, now that you mention it!











Remember personal info?


Please note that I will never send you any unsolicited email. Ever.

While I'm at it, please note that by submitting a question or comment you're agreeing to my terms of service, which are: you relinquish any subsequent rights of ownership to your material by submitting it on this site.








Ask Dave Taylor: The iPhone App: Advertisement



Follow me on Twitter @DaveTaylor

Search
Find just the answers you seek from among our 2300+ free tech support articles by using our Lijit search engine.


Help!





Subscribe to
Ask Dave Taylor!

Add to Google Reader
Add to My Yahoo!
Subscribe in NewsGator Online

RDF   XML

Free Updates!
Sign up and get free weekly updates and special offers on books, seminars, workshops and more.


Recent Entries
Book Links
© 2002 - 2010 by Dave Taylor. All Rights Reserved.

Note: This web site is for the purpose of disseminating information for educational purposes, free of charge, for the benefit of all visitors. We take great care to provide quality information. However, we do not guarantee, and accept no legal liability whatsoever arising from or connected to, the accuracy, reliability, currency or completeness of any material contained on this web site or on any linked site.

[whiteboard marker tray]
"Ask Dave Taylor®" is a registered trademark of Intuitive Systems, LLC.