加入收藏 | 设为首页 | 会员中心 | 我要投稿 惠州站长网 (https://www.0752zz.com.cn/)- 办公协同、云通信、物联设备、操作系统、高性能计算!
当前位置: 首页 > 建站 > 正文

详解Python远程控制模块:Paramiko概念、方法及七大案例

发布时间:2019-10-23 21:15:09 所属栏目:建站 来源:波波说运维
导读:副标题#e# 概述 ssh是一个协议,OpenSSH是其中一个开源实现,paramiko是Python的一个库,实现了SSHv2协议(底层使用cryptography)。 有了Paramiko以后,我们就可以在Python代码中直接使用SSH协议对远程服务器执行操作,而不是通过ssh命令对远程服务器进行操

5. paramiko基于公钥密钥连接

  1. import paramiko 
  2. from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException 
  3. def connect(cmd, hostname, port=22, user='root'): 
  4.  client = paramiko.SSHClient()  
  5.  private_key = paramiko.RSAKey.from_private_key_file('id_rsa') 
  6.  ###id_rsa为本地局域网密钥文件 
  7.  client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
  8.  try: 
  9.  client.connect(hostnamehostname=hostname, 
  10.  portport=port, 
  11.  userusername=user, 
  12.  pkey=private_key 
  13.  ) 
  14.  stdin, stdout, stderr = client.exec_command(cmd) 
  15.  except NoValidConnectionsError as e: 
  16.  print("连接失败") 
  17.  except AuthenticationException as e: 
  18.  print("密码错误") 
  19.  else: 
  20.  result = stdout.read().decode('utf-8') 
  21.  print(result) 
  22.  finally: 
  23.  client.close() 
  24. for count in range(254): 
  25.  host = '172.25.254.%s' %(count+1) 
  26.  print(host.center(50, '*')) 
  27.  connect('uname', host) 

(编辑:惠州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读