zoukankan      html  css  js  c++  java
  • Python 3.x--paramiko模块详解

    一、使用paramiko模块实现SSH功能

    下列代码在Windows上运行,连接虚拟机中centos系统。

    import paramiko
    
    # 创建SSH对象
    ssh = paramiko.SSHClient()
    # 允许连接不在known_hosts文件上的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器
    ssh.connect(hostname="192.168.0.99", port=22, username="root", password="rootroot")
    # 执行命令
    stdin, stdout, stderr = ssh.exec_command('df')
    # 获取结果
    result = stdout.read().decode()
    # 获取错误提示(stdout、stderr只会输出其中一个)
    err = stderr.read()
    # 关闭连接
    ssh.close()
    print(stdin, result, err)

    注:如果注释“ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())”这句,会报错。

    类似问题可以为linux系统中~/.ssh/known_hosts文件中的内容。

     二、实现SFTP功能

    import paramiko
    # 连接虚拟机centos上的ip及端口
    transport = paramiko.Transport(("192.168.0.99", 22))
    transport.connect(username="root", password="rootroot")
    # 将实例化的Transport作为参数传入SFTPClient中
    sftp = paramiko.SFTPClient.from_transport(transport)
    # 将“calculator.py”上传到filelist文件夹中
    sftp.put('D:python库Python_shellday05calculator.py', '/filelist/calculator.py')
    # 将centos中的aaa.txt文件下载到桌面
    sftp.get('/filedir/aaa.txt', r'C:Usersduany_000Desktop	est_aaa.txt')
    transport.close()

    注:如果遇到Windows中路径问题,链接如下网址http://blog.csdn.net/elang6962/article/details/68068126

    三、使用秘钥实现SSH功能

    import paramiko
    private_key = paramiko.RSAKey.from_private_key_file('id_rsa31')
    # 创建SSH对象
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器
    ssh.connect(hostname='192.168.79.9', port=22, username='root', pkey=private_key)
    stdin, stdout, stderr = ssh.exec_command('ifconfig')
    res_out = stdout.read()
    print(res_out.decode())
    ssh.close()

    四、使用秘钥实现SFTP功能

    import paramiko
    private_key = paramiko.RSAKey.from_private_key_file('id_rsa31')
    # 连接虚拟机centos上的ip及端口
    transport = paramiko.Transport(("192.168.79.9", 22))
    transport.connect(username="root", pkey=private_key)
    # 将实例化的Transport作为参数传入SFTPClient中
    sftp = paramiko.SFTPClient.from_transport(transport)
    # 将“calculator.py”上传到filelist文件夹中
    sftp.put('D:python库Python_shellday05calculator.py', '/filedir/calculator.py')
    # 将centos中的aaa.txt文件下载到桌面
    sftp.get('/filedir/oldtext.txt', r'C:Usersduany_000Desktopoldtext.txt')
    transport.close()
  • 相关阅读:
    jvisualvm工具使用
    Java四种引用包括强引用,软引用,弱引用,虚引用。
    <实战> 通过分析Heap Dump 来了解 Memory Leak ,Retained Heap,Shallow Heap
    什么是GC Roots
    Memory Analyzer tool(MAT)分析内存泄漏---理解Retained Heap、Shallow Heap、GC Root
    JDK自带工具之问题排查场景示例
    websocket协议握手详解
    ssh 登陆服务器原理
    新版本macos无法安装mysql-python包
    如何将多个小值存储进一个值中
  • 原文地址:https://www.cnblogs.com/rainowl-ymj/p/7247287.html
Copyright © 2011-2022 走看看