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 <
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.
Hi,
I need help in automation of ssh. I am trying to send commands automatically so that it will fire commands and give me the output of it. As we all know that, ssh is for getting into the node and fire some commands and give output for that command.
I am using ssh factory jar file and i am trying to send commands automatically.
kindly check for the below code which i have tried:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.jscape.inet.ssh.Ssh;
import com.jscape.inet.ssh.SshAdapter;
import com.jscape.inet.ssh.SshConnectedEvent;
import com.jscape.inet.ssh.SshDataReceivedEvent;
import com.jscape.inet.ssh.SshDisconnectedEvent;
import com.jscape.inet.ssh.SshException;
import com.jscape.inet.ssh.SshScript;
import com.jscape.inet.ssh.SshTask;
import com.jscape.inet.ssh.SshTaskEndEvent;
import com.jscape.inet.ssh.SshTaskStartEvent;
import com.jscape.inet.ssh.SshTaskTimeoutException;
import com.jscape.inet.ssh.connection.channels.SessionCli ent;
import com.jscape.inet.ssh.util.SshParameters;
public class SshScriptTutorial extends SshAdapter {
public SshScriptTutorial() {}
public void executeSshScript(String hostname, String username, String password)
throws SshException, IOException, InterruptedException
{
// assumes that SSH shell prompt is “$” .. this MUST match exactly
String shellPrompt = “>”;
// initialize and create new Ssh instance
SshParameters sshParams = new SshParameters(hostname,username,password);
Ssh ssh = new Ssh(sshParams);
// register this class to receive Ssh events
ssh.addSshListener(this);
// create new script object and bind to the given ssh object
SshScript script = new SshScript(ssh);
// add tasks to script object
script.addTask(new SshTask(shellPrompt, “show host”, shellPrompt));
script.addTask(new SshTask(shellPrompt, “ssh ssgpun”, shellPrompt));
// while sending password, it is not able to fire this.
script.addTask(new SshTask(shellPrompt, “password”, “:”)); // trying to send password to the server.
// connect to SSH server and execute script
ssh.connect();
// wait until last task is complete
while(!script.isComplete()) {
try {
Thread.sleep(500);
} catch(Exception e) {}
}
// disconnect from server
// ssh.disconnect();
}
public void connected(SshConnectedEvent event) {
System.out.println(“Connected to host: ” + event.getHost());
}
public void disconnected(SshDisconnectedEvent event) {
System.out.println(“Disconnected from host: ” + event.getHost());
}
public void dataReceived(SshDataReceivedEvent event) {
System.out.print(event.getData());
}
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// System.out.print(“Enter SSH hostname: “);
// String hostname = reader.readLine();
// System.out.print(“Enter SSH username: “);
// String username = reader.readLine();
String hostname = “hostname”; // ip of server
String username = “username”;
System.out.print(“Enter SSH password: “);
String password = reader.readLine();
SshScriptTutorial tutorial = new SshScriptTutorial();
tutorial.executeSshScript(hostname, username, password);
// System.out.print(“Hi”);
String cus_pass = reader.readLine();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Output log appears as,
Enter SSH password: 4732885288
Connected to host: 150.236.14.11
egw-pnq > show host
Node IP number Reverse SSH tunnel
__________________________________________________ _____________________
ssgpun 192.168.181.2 yes
egw-pnq > ssh ssgpun
Connecting to ssgpun as user
Password:
Till this i am able to send commands automatically. when i am trying to send password, it is not able to fire it.
I feel that this might be due to setting shell prompt or delay problem. I am not sure. I dont know how to solve it.
If any1 knows, kindly help me out in this step.
The 2006 comment about AIX and RSA keys I think has moved. I found this link
https://www-304.ibm.com/support/docview.wss?uid=isg3T1000523
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
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.
Thanks a lot for the information posted it helped us great deal
just use your keys and auth files.
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.
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
expect command is not found error is coming…plz help
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
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.
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.
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
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.
You have to use ssh-agent to get password-less logins using pre-exchanged keys: http://www.hackinglinuxexposed.com/articles/20021226.html
Owen