When i ssh to a machine, sometime i get this error warning and it prompts to say \"yes\" or \"no\". This cause some trouble when running from scripts that automatically ssh
Old question that deserves a better answer.
You can prevent interactive prompt without disabling StrictHostKeyChecking
(which is insecure).
Incorporate the following logic into your script:
if [ -z "$(ssh-keygen -F $IP)" ]; then
ssh-keyscan -H $IP >> ~/.ssh/known_hosts
fi
It checks if public key of the server is in known_hosts
. If not, it requests public key from the server and adds it to known_hosts
.
In this way you are exposed to Man-In-The-Middle attack only once, which may be mitigated by:
With reference to Cori's answer, I modified it and used below command, which is working. Without exit
, remaining command was actually logging to remote machine, which I didn't want in script
ssh -o StrictHostKeyChecking=no user@ip_of_remote_machine "exit"
Do this -> chmod +w ~/.ssh/known_hosts
. This adds write permission to the file at ~/.ssh/known_hosts
. After that the remote host will be added to the known_hosts
file when you connect to it the next time.
Ideally, you should create a self-managed certificate authority. Start with generating a key pair:
ssh-keygen -f cert_signer
Then sign each server's public host key:
ssh-keygen -s cert_signer -I cert_signer -h -n www.example.com -V +52w /etc/ssh/ssh_host_rsa_key.pub
This generates a signed public host key:
/etc/ssh/ssh_host_rsa_key-cert.pub
In /etc/ssh/sshd_config
, point the HostCertificate
to this file:
HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub
Restart the sshd service:
service sshd restart
Then on the SSH client, add the following to ~/.ssh/known_hosts
:
@cert-authority *.example.com ssh-rsa AAAAB3Nz...cYwy+1Y2u/
The above contains:
@cert-authority
*.example.com
cert_signer.pub
The cert_signer
public key will trust any server whose public host key is signed by the cert_signer
private key.
Although this requires a one-time configuration on the client side, you can trust multiple servers, including those that haven't been provisioned yet (as long as you sign each server, that is).
For more details, see this wiki page.