zoukankan      html  css  js  c++  java
  • paramiko 与 远程服务器操作

    传输文件

    import paramiko
    import os

    def download_from(ip,u,p):
      file_list=['file2',file3','file4']
      file_path="/home/projs/"
      client=paramiko.Transport((ip,22))
      client.connect(username=u,password=p)
      sftp=paramiko.SFTPClient.from_transport(client)

      for file in file_list:
        sftp.get(os.path.join(file_path,file),os.path.join('local_path',file))
      client.close()

    def put_to(ip,u,p):
      file_path="E:\"
      remote_path='/home/ubuntu/'
      client=paramiko.Transport((ip,22))
      client.connect(username=u,password=p)
      sftp=paramiko.SFTPClient.from_transport(client)
      for file in os.listdir(file_path):
        file_s=os.path.join(file_path,file)
        if os.path.isfile(file_s):
          sftp.put(file_s,os.path.join(remote_path,file))

      client.close()

    下载文件使用sftp.get

    sftp.get(远程服务器上文件地址,本地保存地址)

    上传文件使用sftp.put(本地文件路径,需要传到的远程服务器文件路径)

    通过ssh连接服务器

    ssh = paramiko.SSHClient()

    #这里是设置第一次连接的服务器IP时,自动添加可信任host

    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # server的格式为{'hostname':'192.xxx.xxx.xx','port':22,'username':'root','password':'xxxxx'}

    ssh.connect(**server)

    transport_ = ssh.get_transport()

    #这里生成的sftp和上面性质一样,可用于文件传输

    sftp = transport_.open_sftp_client()

    #sftp也可直接读写远程服务器上的文件,sftp.file返回的是一个Python中的类file类的文件对象,大部分对file的操作也可用于stfp.file

    with sftp.file('remote/file/path','r') as f:
        txt = f.read()

    with sftp.file('/some/remote/file/path','w') as f:
        f.write('some contents..')

    #通过ssh.exec_command直接在远程服务器上执行指令

    stdin,stdout,stderr = ssh.exec_command("service iptables restart")

    logger.warning('stdout:%s,stderr:%s'%(stdout.read(),stderr.read())

    ssh.close()

    #切记用完后关闭ssh.close(),不关闭可能造成无法想象的结果

    ssh.connect(**server) 和ssh.close()可以配合使用,打开,关闭;

    一个已创建的ssh = paramiko.SSHClient()可以多次 打开再关闭,用于不同服务器的连接

  • 相关阅读:
    如何进行Django单元测试
    django使用celery实现异步操作
    django 多并发,多线程。
    cookies设置时间
    Mysql实现企业级日志管理、备份与恢复
    Redis与Memcached的区别
    cookie 和session 的区别详解
    python内存泄露查找
    浙大月赛ZOJ Monthly, August 2014
    Vector
  • 原文地址:https://www.cnblogs.com/Ting-light/p/10472301.html
Copyright © 2011-2022 走看看