• paramiko学习


    1.基于用户名和密码的 sshclient 方式登录

    def connect_server(hostname, port, username, password):
        try:
            # 创建SSH对象
            ssh_client = paramiko.SSHClient()
            # 允许连接不在know_hosts文件中的主机
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # 连接服务器
            ssh_client.connect(hostname, port, username, password)
            # 执行命令
            std_in, std_out, std_err = ssh_client.exec_command('ls')
            # 获取命令结果
            #for line in std_out:
                #print(line.strip("
    "))
            ssh_client.close()
        except Exception as e:
            print(e)

    2.基于公钥密钥的 SSHClient 方式登录

    def connect_server(hostname, port, username):
        # 指定本地的RSA私钥文件,如果建立密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
        pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')
        # 建立连接
        ssh = paramiko.SSHClient()
        ssh.connect(hostname, port, username, pkey=pkey)
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command('df -hl')
        # 结果放到stdout中,如果有错误将放到stderr中
        print(stdout.read())
        # 关闭连接
        ssh.close()

    3.paramiko上传文件

    def upload_file(hostname, port, username, password, local_path, server_path):
        try:
            t = paramiko.Transport((hostname, port))
            t.connect(username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp.put(local_path, server_path)
            t.close()
        except Exception as e:
            print(e)

    4.paramiko下载文件

    def download_file(hostname, port, username, password, local_path, server_path):
        try:
            t = paramiko.Transport((hostname, port))
            t.connect(username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp.get(local_path, server_path)
            t.close()
        except Exception as e:
            print(e)
  • 相关阅读:
    Python基础学习笔记(10)形参 命名空间
    10 练习题:形参 命名空间
    09 练习题:函数、参数
    4.题库
    第三章:构造NFA DFA
    第二章
    第一章
    83.jquery的筛选与过滤
    82.认识jQuery以及选择器
    81.案例 初始化、拖拽、缓冲
  • 原文地址:https://www.cnblogs.com/windyrainy/p/15306267.html
Copyright © 2020-2023  润新知