通过私钥公钥实现远程机器访问,代码demo如下
def ssh(hostname, cmd):
ida_key = paramiko.RSAKey.from_private_key_file('/Users/apple/Downloads/id_rsa')
try:
ssh_obj = paramiko.SSHClient()
ssh_obj.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_obj.connect(hostname=hostname, port=22, username='work', pkey=ida_key, timeout=3)
except Exception as e:
print(e)
return False, hostname + "登录失败!"
stdin, stdout, stderr = ssh_obj.exec_command(cmd)
error = stderr.read().decode('utf-8').strip()
if error:
return False, '{hostname},{cmd}执行时出现问题'
else:
result = stdout.read()
ssh_obj.close()
return True, result.decode('utf-8').strip()
注意:
1./Users/apple/Downloads/id_rsa 私钥文件,该文件权限需要赋予600? chmod 600 id_rsa
2.如果出现Authentication failed 权限错误提示
? ? ? ? 解决办法1:升级?openssh-server版本?yum update openssh-server -y
? ? ? ? 解决办法2:ssh_obj.connect中添加disabled_algorithms=dict(pubkeys=["rsa-sha2-512", "rsa-sha2-256"])
3.私钥id_rsa文件中
???????? begin要为RSA如下:-----BEGIN RSA PRIVATE KEY-----
? ? ? ? 不能是OPENSSH如下:-----BEGIN OPENSSH PRIVATE KEY-----
4.python3版本,指定运行方式
?/opt/soft/python3.6/bin/python3 SSHClient.py???????? ? ? ??
|