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)
原文地址:https://www.cnblogs.com/windyrainy/p/15306267.html