2

我正在使用此代码将服务器添加到 known_hosts:

subprocess.Popen(['sshpass', '-p', password, 'ssh', '-o', 'StrictHostKeyChecking=no', add_key], stdout=subprocess.PIPE).communicate()[0]

这会将主机名添加到 known_hosts 但服务器在尝试进入主机时挂起。我只想将主机名添加到 known_hosts 并继续我的其他代码。我怎样才能做到这一点?谢谢

4

2 回答 2

1

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()
于 2012-11-28T04:08:10.797 回答
0

没关系,自己解决了。这是我所做的:

test = subprocess.Popen(['sshpass', '-p', password, 'ssh', '-o', 'StrictHostKeyChecking=no', add_key])
            time.sleep(5.0)
            test.kill()

谢谢!

于 2012-11-28T12:26:29.470 回答