python远程访问服务器获取文件

一、sftp

1、使用paramiko模块进行sftp传输,实现在线读取文件,注意paramiko模块存在一些依赖,可能安装的时候会有一些小的障碍。

    client = paramiko.SSHClient()

    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host_ip, port, username, password, timeout=5)
    sftp_client = client.open_sftp()
    logging.info(sftp_client)
    remote_file = sftp_client.open(data_path+ filename +".txt", 'r')

二、ftp

使用python自带的ftplib模块 进行ftp传输,这边是下载到本地在进行读取文件,这边需要注意要问清楚是不是ftp传输,因为一般ftp服务器是关闭的,在连接的时候是连接不上的。

def ftpconnect(host, port, username, password):
    ftp = FTP()
    ftp.connect(host, int(port))
    ftp.login(username, password)
    return ftp

#   下载文件
def downloadfile(ftp, remotepath, localpath, filename):
    print(localpath)
    bufsize = 1024
    ftp.cwd(remotepath)
    ftp.dir()
    fp = open(localpath + filename,'wb')
    ftp.retrbinary('RETR %s' % os.path.basename(filename), fp.write, bufsize)
    fp.close()
    
#   上传文件
def uploalfile(ftp, remotepath, localpath):
    bufsize = 1024
    fp = open(localpath, 'rb')
    ftp.storbinary('STOR ' + remotepath, fp, bufsize)
#   ftp.set_debuglevel(0)
    ftp.close()