How to automate password entry?

2020-02-09 18:25发布

问题:

I want to install a software library (SWIG) on a list of computers (Jenkins nodes). I'm using the following script to automate this somewhat:

NODES="10.8.255.70 10.8.255.85 10.8.255.88 10.8.255.86 10.8.255.65 10.8.255.64 10.8.255.97 10.8.255.69"
for node in $NODES; do 
  scp InstallSWIG.sh root@$node:/root/InstallSWIG.sh
  ssh root@$node sh InstallSWIG.sh
done

This way it's automated, except for the password request that occur for both the scp and ssh commands.

Is there a way to enter the passwords programmatically?

Security is not an issue. I’m looking for solutions that don’t involve SSH keys.

回答1:

With SSH the right way to do it is to use keys instead.

# ssh-keygen

and then copy the *~/.ssh/id_rsa.pub* file to the remote machine (root@$node) into the remote user's .ssh/authorized_keys file.



回答2:

Here’s an expect example that sshs in to Stripe’s Capture The Flag server and enters the password automatically.

expect <<< 'spawn ssh level01@ctf.stri.pe; expect "password:"; send "e9gx26YEb2\r";'


回答3:

You can perform the task using empty, a small utility from sourceforge. It's similar to expect but probably more convenient in this case. Once you have installed it, your first scp will be accomplished by following two commands:

./empty -f scp InstallSWIG.sh root@$node:/root/InstallSWIG.sh
echo YOUR_SECRET_PASSWORD | ./empty -s -c

The first one starts your command in the background, tricking it into thinking it's running in interactive mode on a terminal. The other one sends it data from stdin. Of course, putting your password anywhere on command line is risky due to shell history being preserved, users being able to see it in ps results etc. Not secure either, but a bit better thing would be to store the password in a file and redirect the second command's input from that file instead of using echo and a pipe.

After copying to the server, you can run the script in a similar manner:

./empty -f ssh root@$node sh InstallSWIG.sh
echo YOUR_SECRET_PASSWORD | ./empty -s -c


回答4:

You could look into setting up passwordless ssh keys for that. Establishing Batch Mode Connections between OpenSSH and SSH2 is a starting point, you'll find lots of information on this topic on the web.



回答5:

Wes' answer is the correct one but if you're keen on something dirty and slow, you can use expect to automate this.