This should do the job. This solution use the pexpect library which is a great way to automate commands. You basically call add_known_hosts with the host, user, password that you want added. it will try to ssh to that host and either enters the password or responds to the add to known hosts connection with a yes and then enters the password. Finally it cleanly exits the connection by sending the exit command. You can modify this and not require a username and password and just answer yes to the continue connecting question and then end the ssh process instead of continuing with the password prompt.
import pexpect, time
def add_known_hosts(host, user, password):
child = pexpect.spawn('ssh %s@%s' % (user, host))
i = child.expect(['.* password:', '.* continue connecting (yes/no)?'])
if i == 1:
child.sendline('yes')
child.expect('.* password:')
child.sendline(password)
child.expect('%s@%s' % (user, host))
time.sleep(1)
child.sendline('exit')
add_known_hosts('myhost', 'myusername', 'mypassword')
debugging
from the comments below it seems you are facing issues using pexpect on your system. A good way to just to do a simple test to confirm pexpect is working correctly with ssh is to run the code below. Fill in host, user with your appropriate settings and then run the code, you should be able to interact with the ssh session. At this point you can build up from here and see exactly what text you are expecting to get from ssh and what text you want to send in response.
import pexpect
host, user = 'myhost', 'myusername'
child = pexpect.spawn('ssh %s@%s' % (user, host))
child.interact()