Python的Pexpect的ssh_key作为字符串而不是文件路径

问题描述 投票:0回答:1

是否有可能通过ssh_key为字符串,而不是文件,而使用ssh连接的凭据?

我的代码:(此工作正常ssh_key的文件路径)

self.status = self.ssh.login(self.config['hostname'], 
self.config['username'],
ssh_key='/home/martha/lab/martha.pem')
self.disconnect()
return  {"status":self.status}

而下面不工作

 self.status = self.ssh.login(self.config['hostname'], 
    self.config['username'],
    ssh_key='-----ssh key content-----')
    self.disconnect()
    return  {"status":self.status}

是否有可能,任何形式的帮助表示赞赏?

python ubuntu ssh ssh-keys pexpect
1个回答
0
投票

不幸的是,我不认为有与pexpect这样的选择。解决方法是容易做的:

import os
ssh_temp_file = '/tmp/ssh-key.tmp' #Maybe use a dynamic filename using the process number
with open(ssh_temp_file,'w') as fd: 
    fd.write('ssh-key content')

self.status = self.ssh.login(...)
os.remove(ssh_temp_file)

我将它包装在一个函数。

def ssh_with_string(self,ssh_key,*ssh_args,**ssh_kwargs):
    ssh_kwargs['ssh_key'] = '/tmp/ssh-key.'+str(os.getpid())+'.tmp'
    with open(ssh_kwargs['ssh_key'],'w') as fd: 
        fd.write(ssh_key)

    self.status = self.ssh.login(*ssh_args,**ssh_kwargs)
    os.remove(ssh_kwargs['ssh_key'])
    return self.status
© www.soinside.com 2019 - 2024. All rights reserved.