精华内容
下载资源
问答
  • python sftp上传下载

    2017-02-09 14:51:26
    python sftp上传下载
  • python sftp

    2012-06-07 20:43:57
    windows调用linux系统中的sftp功能。语言还是c++ 可以选择libcurl + OpenSSL + Zlib + Libssh2, 结合QT编译,可能是自己太笨,搞了2天也没编译好环境,后来选择了python的paramiko实现上传下载功能,tarfile用来...

    windows调用linux系统中的sftp功能。语言还是c++ 可以选择libcurl + OpenSSL + Zlib + Libssh2

    结合QT编译,可能是自己太笨,搞了2天也没编译好环境,后来选择了pythonparamiko实现上传下载功能,tarfile用来解压,用中午的午休时间搞定。

     

    选择这条路,最后证明是噩梦的开始,如c++调用python,c++中的多线程在python中的支持,python环境打包,win7下编译好的程序在winXP中由于python27.dll的依赖不能用...

    成也python,败也python,后续博客中会陆续更新。

     

    环境:

     

    Python 2.7 pythonxy2.7集成

    Paramiko: paramiko-1.7.7.1.zip

     

     

    pythonsftp.pyc 文件如下:

     

    # -*- coding: utf-8 -*- 
     
    import sys
    import os
    import getpass
    import socket
    import paramiko
    from datetime import date, timedelta
    import tarfile
    #解压
    def pythonTgz(stcPath,tagPath):
    	#已"r:gz"格式打开
        tarobj = tarfile.open(stcPath, "r:gz")
        for tarinfo in tarobj:
            tarobj.extract(tarinfo.name, tagPath)
        tarobj.close()
    
    #上传下载
    def pythonSftp(isget,hostname,port,sftpUsername,sftpPassword,remotepath,localpath,fileList):
    #创建一个连接实例
            t = paramiko.Transport((hostname,port)) 
     		#连接服务器
            t.connect(username = sftpUsername, password = sftpPassword)
    		#创建一个sftp客户端实例
            pSftp = paramiko.SFTPClient.from_transport(t)
    		#循环每个文件上传/下载
    for f in fileList:
                    pSftp.put(os.path.join(localpath,f),remotpathtemp)
    
            …
    

     

     代码实现很挫,很挫...

     

    boost对python的引用

    添加vc++对python、boost库的应用

     

     

    拷贝相关文件

     

    拷贝上一步生成的动态编译库到程序目录

    boost_pyhton-vc100-mt-1_49.dll

    boost_pyhton-vc100-mt-1_49.lib

     

    boost_pyhton-vc100-mt-gd_49.dll

    boost_pyhton-vc100-mt-gd_49.lib

     

    拷贝python上传下载实现代码

    pythonsftp.pyc

     

    程序实现

     

    #include <boost/python.hpp>
    #include <Python.h>
    
    #ifdef _DEBUG
    #pragma comment(lib, "boost_python-vc100-mt-gd-1_49.lib")
    #pragma  message("boost_python --> debug~lab")
    #else
    #pragma comment(lib, "boost_python-vc100-mt-1_49.lib")
    #pragma  message("boost_python --> reless~lib")
    #endif
    …
    int psdsftp::unCompres( const std::string &resPath, const std::string &tagPath )
    {
    	//检查功能有效性
    	if(!Py_IsInitialized())   
    	{   
    		cout <<"初始化失败!"<< endl;
    		return -1;   
    	}
    	// 调用Python中的sftp函数并获得返回值
    	try
    	{
    		call_method<char *>(module.get(), m_funUnCom.c_str(), 
    			resPath.c_str(),
    			tagPath.c_str() );
    	}
    	catch (...)
    	{
    		cout <<"出错了!~"<< endl;
    	}
    	return 0;
    }
    
     

     

    python 打包选择的是 py2exe(pythonxy中已经安装)

     

     

    创建配置文件mysetup.py

    from distutils.core import setup
    import py2exe  
    import sys
    import os
    import getpass
    import socket
    import paramiko
    import tarfile
    setup(console = ["pythonsftp.py"])
    ...
     

    pythonsftp.py为要打包的python文件

     

    <!--[if !supportLists]-->Ø  <!--[endif]-->提取python文件

    复制mysetup.py到程序发布文件夹,在cmd窗口指向程序文件夹

    cd D:\work\SFTP\SFTPPython\test_boost_python_cmd

    python mysetup.py py2exe

    参考:

    http://blog.csdn.net/andoring/article/details/6616430

    http://wiki.woodpecker.org.cn/moin/LeoJay/PyPackage

     

    复制相关的文件

    复制pythonsftp.pyc文件到发布根目录

    <!--[if !supportLists]-->Ø  <!--[endif]-->如果是用vs2010编译,要复制对应的文件

    ~/redist/x86/Microsoft.VC100.CRT 目录下的两个文件:

    msvcp100.dll

    msvcr100.dll

    <!--[if !supportLists]-->Ø  <!--[endif]-->Boost.python库引用

    boost_python-vc100-mt-1_49.dll

    boost_python-vc100-mt-1_49.lib

    <!--[if !supportLists]-->Ø  <!--[endif]-->py2exe c++嵌入python打包的bug

    如果是C++嵌入python生成的library.zip中缺少一些文件,生成的程序会报丢失文件的错误 ImportError: No module named site

    需要把python中的lab文件从新打包(C:\Python27\Lib

    在c++文件中设置python的运行目录

    #include <Windows.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    psdsftp::psdsftp(void)
    	:m_pythonSftp("pythonsftp")
    	,m_funSFTP   ("pythonSftp")
    	,m_funUnCom  ("pythonTgz")
    {
    	// 得到当前可执行文件所在的目录
    	char szPath[10240];
    	GetModuleFileName(NULL, szPath, sizeof(szPath));
    
    	char* p = strrchr(szPath, '\\');
    	if (p == NULL)
    	{
    		printf("不能获得文件路径!\n");
    		return ;
    	}
    	*p = 0;
    	cout << szPath << endl;
    
    	// 设定运行时的PATH
    	std::string PATHS = szPath;
    	std::string pathdlls = "sys.path.append(r'" + PATHS + "\\stdlib.zip')";
    	std::string pathlib  = "sys.path.append(r'" + PATHS + "\\dlls')";
    	cout << pathdlls << endl;
    	cout << pathlib << endl;
    
    	Py_Initialize();
    
    	PyRun_SimpleString("import sys");
    	PyRun_SimpleString(pathdlls.c_str());
    	PyRun_SimpleString(pathlib.c_str());
    
     

     

     

     

    展开全文
  • python sftp_python -SFTP

    2020-11-24 04:50:19
    #coding=utf-8 ''' Created on Jun 6, 2017 @author: wb ''' import wx import os import shutil import sys import os.path import paramiko from paramiko import sftp import time import WtgGetCfg from ...

    #coding=utf-8

    '''

    Created on Jun 6, 2017

    @author: wb

    '''

    import wx

    import os

    import shutil

    import sys

    import os.path

    import paramiko

    from paramiko import sftp

    import time

    import WtgGetCfg

    from WtgGetCfg import getCfg

    from WtgGetCfg import saveCfg

    def main():

    global path

    global rootdir  # 指明被遍历的文件夹

    global ToPath

    global host

    global user

    global passwd

    global mtime

    #      time.strftime('%Y_%m',time.localtime(time.time()))

    txtName = time.strftime('%Y_%m',time.localtime(time.time()))

    f = file(txtName, "a+")

    #    history = f.read()

    f.close()

    print txtName

    host,rootdir,user,passwd,lastTime,ToPath = getCfg()

    if not os.path.isdir(ToPath):

    os.makedirs(ToPath)

    print 'New Floder Successful'

    mtime = lastTime

    historyTime = time.strptime(lastTime,"%a %b %d %H:%M:%S %Y")

    print time.mktime(historyTime)

    print host,rootdir,user,passwd,lastTime,ToPath

    try:

    t = paramiko.Transport((host,22))

    t.connect(username=user, password=passwd)

    sftp = paramiko.SFTPClient.from_transport(t)

    except:

    print "connection failed "

    f2 = open(txtName, "a")

    name = "connection failed"+"\t"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"\n"

    f2.write(name)

    f2.close()

    #        app = wx.PySimpleApp()

    app = wx.App()

    dlg = wx.MessageDialog(None, 'connection failed'+"\n"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),

    'Warning !',

    wx.OK | wx.ICON_INFORMATION

    #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION

    )

    dlg.ShowModal()

    dlg.Destroy()

    return -1

    for parent,dirnames,filenames in os.walk(u''+rootdir.encode('gbk')):    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字

    f1 = open(txtName, "a")

    for filename in filenames:                        #输出文件信息

    #        print "parent is:" + parent

    #        print "filename is:" + filename

    #        print "the full name of the file is:" + os.path.join(parent,filename) #输出文件路径信息

    mtime = time.ctime(os.path.getmtime(os.path.join(parent,filename)))

    print mtime

    nowTime = time.strptime(mtime,"%a %b %d %H:%M:%S %Y")

    print time.mktime(nowTime)

    if nowTime > historyTime :

    print filename

    if sftp.put(os.path.join(parent,filename),filename):

    shutil.copy (os.path.join(parent,filename), ToPath)

    os.remove (os.path.join(parent,filename))

    print 'success'

    name = filename +"\t"+"ok"+"\t"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"\n"

    f1.write(name)

    else:

    app = wx.App()

    dlg = wx.MessageDialog(None, filename+'upload failed',

    'Warning !',

    wx.OK | wx.ICON_INFORMATION

    #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION

    )

    dlg.ShowModal()

    dlg.Destroy()

    print 'be defeated'

    print filename

    name = filename +"\t"+"fail"+"\t"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"\n"

    f1.write(name)

    #        if filename in history:

    else:

    print '已经上传过'

    #

    saveCfg(mtime)

    f1.close()

    if __name__ == '__main__':

    main()

    展开全文
  • ln.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_ln.py] 2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck.py],本地文件:[/home/...

    主类

    importosimportreimportthreadingimportparamikofrom stat importS_ISDIRimportlogging2#定义一个类,表示一台远端linux主机

    classLinux(threading.Thread):#通过IP, 用户名,密码,超时时间初始化一个远程Linux主机

    def __init__(self, thread_id, thread_name, ip, username, password, remote_dir, local_dir, pattern, isRmRemoteFile = 0, timeout=30):

    threading.Thread.__init__(self)

    self.thread_id=thread_id

    self.thread_name=thread_name

    self.ip=ip

    self.username=username

    self.password=password

    self.timeout=timeout

    self.remote_dir=remote_dir

    self.local_dir=local_dir

    self.pattern=pattern#是否sftp成功后删除远程文件,1-删除,0-不删除

    self.isRmRemoteFile =isRmRemoteFile#transport和chanel

    self.t = ''self.chan= ''

    #链接失败的重试次数

    self.try_times = 3

    #调用该方法连接远程主机

    defconnect(self):pass

    #断开连接

    defclose(self):pass

    #发送要执行的命令

    defsend(self, cmd):pass

    #get单个文件

    defsftp_get(self, remotefile, localfile):

    t= paramiko.Transport(sock=(self.ip, 22))

    t.connect(username=self.username, password=self.password)

    sftp=paramiko.SFTPClient.from_transport(t)

    sftp.get(remotefile, localfile)

    t.close()#put单个文件

    defsftp_put(self, localfile, remotefile):

    t= paramiko.Transport(sock=(self.ip, 22))

    t.connect(username=self.username, password=self.password)

    sftp=paramiko.SFTPClient.from_transport(t)

    sftp.put(localfile, remotefile)

    t.close()#----获取远端linux主机上指定目录及其子目录下的所有文件------

    def __get_all_files_in_remote_dir(self, sftp, remote_dir, pattern = '.*'):#保存所有文件的列表

    all_files =list()#去掉路径字符串最后的字符'/',如果有的话

    if remote_dir[-1] == '/':

    remote_dir= remote_dir[0:-1]#获取当前指定目录下的所有目录及文件,包含属性值

    files =sftp.listdir_attr(remote_dir)for x infiles:#remote_dir目录中每一个文件或目录的完整路径

    filename = remote_dir + '/' +x.filename#如果是目录,则递归处理该目录,这里用到了stat库中的S_ISDIR方法,与linux中的宏的名字完全一致

    ifS_ISDIR(x.st_mode):

    all_files.extend(self.__get_all_files_in_remote_dir(sftp, filename))else:#matchObj = re.match('.*\.py$', filename, re.M|re.I)

    matchObj = re.match(pattern, filename, re.M|re.I)ifmatchObj:

    all_files.append(filename)returnall_filesdefsftp_get_dir(self):

    t= paramiko.Transport(sock=(self.ip, 22))

    t.connect(username=self.username, password=self.password)

    sftp=paramiko.SFTPClient.from_transport(t)#获取远端linux主机上指定目录及其子目录下的所有文件

    all_files = self.__get_all_files_in_remote_dir(sftp, self.remote_dir, self.pattern)#依次get每一个文件

    for x inall_files:

    filename= x.split('/')[-1]

    local_filename=os.path.join(self.local_dir, filename)

    logging2.debug('正在下载远程文件:[%s],本地文件:[%s]', x, local_filename)

    sftp.get(x, local_filename)if self.isRmRemoteFile == 1 and os.path.exists(local_filename) ==True:

    logging2.debug('已下载本地[%s],删除远程文件[%s]', local_filename, x)

    sftp.remove(x)

    t.close()defrun(self):#将远端remote_path目录中的所有文件get到本地local_path目录

    Linux.sftp_get_dir(self)if __name__ == '__main__':

    logging2.init("collect", "DEBUG")

    remote_path1= r'/public/jxbill/shell/python/data'local_path1= r'/home/zxl/public/code/python/sftp/data'pattern1= r'.*'host1= Linux(1, 'thread_27', '192.168.161.27', 'user', 'password', remote_path1, local_path1, pattern1)

    remote_path2= r'/public/ahbill/shell/python/data'local_path2= r'/home/zxl/public/code/python/sftp/data'pattern2= r'.*\.py$'host2= Linux(1, 'thread_26', '192.168.161.26', 'user', 'password', remote_path2, local_path2, pattern2, 1)

    host1.start()

    host2.start()

    host1.join()

    host2.join()

    日志类logging2.py

    importosimportthreadingimportqueueimporttimeimportdatetimeimportloggingfrom logging.handlers importRotatingFileHandlerclasslogging2(threading.Thread):

    AQueue= queue.Queue(100000)

    nPID=os.getpid()

    Adt= datetime.datetime.now().strftime('%Y%m%d')

    nCount= 1

    def __init__(self, threadID, name, module, logLevel):

    threading.Thread.__init__(self)

    self.threadID=threadID

    self.name=name

    self.module=moduleprint("set loglevel: [%s]" %(logLevel) )

    formatter= logging.Formatter('%(asctime)s|%(name)s|%(process)d|%(levelname)s|%(message)s')

    logfile= "log_" + self.module + "_" + str(logging2.nPID) + "_" + str(logging2.Adt) + ".log"self.logger= logging.getLogger(__name__)

    self.rHandler= RotatingFileHandler(logfile, maxBytes = 10*1024*1024, backupCount = 10)

    self.rHandler.setFormatter(formatter)

    self.console=logging.StreamHandler()

    self.console.setFormatter(formatter)if logLevel == 'DEBUG':

    self.logger.setLevel(level=logging.DEBUG)

    self.rHandler.setLevel(logging.DEBUG)

    self.console.setLevel(logging.DEBUG)elif logLevel == 'INFO':

    self.logger.setLevel(level=logging.INFO)

    self.rHandler.setLevel(logging.INFO)

    self.console.setLevel(logging.INFO)elif logLevel == 'WARNING':

    self.logger.setLevel(level=logging.WARN)

    self.rHandler.setLevel(logging.WARN)

    self.console.setLevel(logging.WARN)elif logLevel == 'ERROR':

    self.logger.setLevel(level=logging.ERROR)

    self.rHandler.setLevel(logging.ERROR)

    self.console.setLevel(logging.ERROR)

    self.logger.addHandler(self.rHandler)

    self.logger.addHandler(self.console)#如果跨天了,则重新生成新的文件名

    defreSetLog(self):

    AdtTemp= datetime.datetime.now().strftime('%Y%m%d')#比较新的时间

    if AdtTemp ==logging2.Adt:return(True)

    logging2.Adt=AdtTemp

    logfile= "log_" + self.module + "_" + str(logging2.nPID) + "_" + str(AdtTemp) + ".log"self.rHandler= RotatingFileHandler(logfile, maxBytes = 1*1024, backupCount = 10)

    self.logger.addHandler(self.rHandler)

    self.logger.addHandler(self.console)

    logging2.nCount+= 1

    defrun(self):print ("开启日志线程:" +self.name)

    i=0whileTrue:#data = "queue test data"

    #debug(data)

    #print("Queuesize: %s" % (logging2.AQueue.qsize()))

    self.reSetLog()if logging2.AQueue.empty() ==False:#从队列获取日志消息

    data =logging2.AQueue.get()#解析日志消息,格式:日志级别,内容

    level =list(data.keys())[0]

    content=data.get(level)#把内容按分隔符|解析成list传入参数

    lstContent = list(content.split('|'))if level == 'DEBUG':

    self.logger.debug(*lstContent)elif level == 'INFO':

    self.logger.info(*lstContent)elif level == 'WARNING':

    self.logger.warn(*lstContent)elif level == 'ERROR':

    self.logger.error(*lstContent)else:

    time.sleep(0.5)print ("退出线程:" +self.name)def debug(*content):

    logMsg= ""

    #传入多个参数用竖线分隔符分开

    for i inrange(len(content)):if i == len(content)-1:

    logMsg+=content[i]else:

    logMsg+= content[i]+"|"logging2.AQueue.put({'DEBUG':logMsg})def info(*content):

    logMsg= ""

    for i inrange(len(content)):if i == len(content)-1:

    logMsg+=content[i]else:

    logMsg+= content[i]+"|"logging2.AQueue.put({'INFO':logMsg})def warn(*content):

    logMsg= ""

    for i inrange(len(content)):if i == len(content)-1:

    logMsg+=content[i]else:

    logMsg+= content[i]+"|"logging2.AQueue.put({'WARNING':logMsg})def error(*content):

    logMsg= ""

    for i inrange(len(content)):if i == len(content)-1:

    logMsg+=content[i]else:

    logMsg+= content[i]+"|"logging2.AQueue.put({'ERROR':logMsg})definit(module, level):#创建新线程

    thread1 = logging2(1, "Thread-log", module, level)#开启新线程

    thread1.start()#thread1.join()

    结果显示:

    日志文件:

    -rw-rw-r--. 1 zxl zxl 2684 6月 28 15:20 log_collect_17744_20200628.log

    日志内容:

    2020-06-28 15:32:44,740|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_ah_5G.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_ah_5G.py]

    2020-06-28 15:32:44,740|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_ah.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_ah.py]

    2020-06-28 15:32:44,740|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_jx_5G.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_jx_5G.py]

    2020-06-28 15:32:44,740|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_jx.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_jx.py]

    2020-06-28 15:32:44,740|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_ln_5G.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_ln_5G.py]

    2020-06-28 15:32:44,740|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_ln.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_ln.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_xz_5G.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_xz_5G.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/cppcheck_xz.py],本地文件:[/home/zxl/public/code/python/sftp/data/cppcheck_xz.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/logserv.py],本地文件:[/home/zxl/public/code/python/sftp/data/logserv.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/monitorSys.py],本地文件:[/home/zxl/public/code/python/sftp/data/monitorSys.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/MvSvnLibToNew.py],本地文件:[/home/zxl/public/code/python/sftp/data/MvSvnLibToNew.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/teleCMD.py],本地文件:[/home/zxl/public/code/python/sftp/data/teleCMD.py]

    2020-06-28 15:32:44,741|logging2|18058|DEBUG|正在下载远程文件:[/public/jxbill/shell/python/data/1.a],本地文件:[/home/zxl/public/code/python/sftp/data/1.a]

    2020-06-28 15:32:44,742|logging2|18058|DEBUG|正在下载远程文件:[/public/ahbill/shell/python/data/2.py],本地文件:[/home/zxl/public/code/python/sftp/data/2.py]

    2020-06-28 15:32:44,742|logging2|18058|DEBUG|已下载本地[/home/zxl/public/code/python/sftp/data/2.py],删除远程文件[/public/ahbill/shell/python/data/2.py]

    2020-06-28 15:32:44,742|logging2|18058|DEBUG|正在下载远程文件:[/public/ahbill/shell/python/data/1.py],本地文件:[/home/zxl/public/code/python/sftp/data/1.py]

    2020-06-28 15:32:44,742|logging2|18058|DEBUG|已下载本地[/home/zxl/public/code/python/sftp/data/1.py],删除远程文件[/public/ahbill/shell/python/data/1.py]

    2020-06-28 15:32:44,742|logging2|18058|DEBUG|正在下载远程文件:[/public/ahbill/shell/python/data/3.py],本地文件:[/home/zxl/public/code/python/sftp/data/3.py]

    2020-06-28 15:32:44,742|logging2|18058|DEBUG|已下载本地[/home/zxl/public/code/python/sftp/data/3.py],删除远程文件[/public/ahbill/shell/python/data/3.py]

    展开全文
  • python中想要实现sftp的话可以使用paramiko模块paramiko很强大,通过python实现SSH协议。可以做到ssh远程登录,sftp上传下载文件。sftp的实现1.通过密码口令认证#!/usr/bin/python# -*- coding:utf-8 -*-import ...

    python中想要实现sftp的话可以使用paramiko模块

    paramiko很强大,通过python实现SSH协议。可以做到ssh远程登录,sftp上传下载文件。

    sftp的实现

    1.通过密码口令认证#!/usr/bin/python

    # -*- coding:utf-8 -*-

    import paramiko

    remotedir = "/app/ftpuser/"

    hostname = "192.168.1.100"

    port = 22

    user = "ftpuser"

    password = "123456"

    if __name__=="__main__":

    t = paramiko.Transport((hostname,port))

    t.connect(username=user,password=password)

    sftp = paramiko.SFTPClient.from_transport(t)

    print sftp.listdir(remotedir)

    t.close

    2.通过密钥认证#!/usr/bin/python

    # -*- coding:utf-8 -*-

    import paramiko

    remotedir = "/app/ftpuser/"

    hostname = "192.168.1.100"

    port = 22

    user = "ftpuser"

    pkey_file = "/home/aa/.ssh/id_rsa"

    if __name__=="__main__":

    key = paramiko.RSAKey.from_private_key_file(pkey_file)

    t = paramiko.Transport((hostname,port))

    t.connect(username=user,pkey=key)

    sftp = paramiko.SFTPClient.from_transport(t)

    print sftp.listdir(remotedir)

    t.close

    看,用python实现sftp客户端访问的实现很简单。相比较shell脚本而言,在一些业务逻辑处理方面用python实现更加方便

    原文地址:http://10452483.blog.51cto.com/10442483/1735593

    展开全文
  • 前言在Python中,paramiko是实现ssh2协议的一个模块。在服务器上基本都是使用ssh远程,如果我们需要传输文件,也可以直接使用基于ssh服务的sftp传输,不需要另外开启文件传输的服务。安装paramikopip install ...
  • We are trying to transfer text files from a Linux server to a Windows server using a python script (which resides on the SFTP server).It is necessary for us to ensure the files are transferred using t...
  • We are trying to transfer text files from a Linux server to a Windows server using a python script (which resides on the SFTP server).It is necessary for us to ensure the files are transferred using t...
  • 总览在上一篇文章中,我们介绍了Python中的ftplib模块,您可以阅读有关的更多信息,见:《pysftp是什么?pysftp是一个易于使用的sftp模块,它利用了paramiko和pycrypto。它提供了一个简单的sftp接口。pysftp的一些...
  • Python(其实任何语言都是)中操控ssh执行远程命令是一个很麻烦的事情……首先要突破ssh密码的非交互模式,我之前一直用sshpass拼接各种复杂的字符串。然后是之后的执行命令只能执行一行,或者是很长的字符串,拼接...
  • 使用pysftp.Connection.listdir_attr...然后,迭代列表并仅选择所需的文件.import timedef get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):for entry in sftp.listdir_attr(remotedir):remotepat...
  • ls") for i in stdout: list.append(i) sftp = ssh.open_sftp() for i in list: tempremote = ("*path*" + i).replace('\n', '') templocal = ("*path*" + i).replace('\n', '') try: #Get the file from the ...
  • 使用SFTP上传与下载文件方式一:import paramikotransport = paramiko.Transport(("106.15.88.182", 22)) # 获取Transport实例transport.connect(username="root", password="123456") # 建立连接# 创建sftp对象,...
  • I need to connect to a SFTP, download the most recent file, then change the file name and load again to the same SFTP folder and delete the 'original name' file. I have done this with FTP with user an...
  • 嗨我正在使用python并尝试连接到sftp并想从那里检索xml文件并需要放在我的本地系统中,下面是代码import paramikosftpURL = 'sftp.somewebsite....automatically add keys ...
  • 通过配置文件链接sftp服务器,下载指定文件,上传指定文件,常常用于更新服务器指定资源。
  • python sftp&ftp&ssh2

    2019-04-02 01:14:46
    NULL 博文链接:https://desert3.iteye.com/blog/1441445
  • I was able to successfully upload the file from S3 to SFTP location using the below syntax as given by @Martin Prikryl ...
  • 使用paramiko库实现sftp的操作 paramiko的安装可以使用“pip install paramiko”直接实现安装。 sftp上传下载的示例代码如下: import paramiko def upload_action(IP, User, Password, local_file, server_file): ...
  • remote_filename = remote_dir + '/' + filename sftp = paramiko.SFTPClient.from_transport(self.t) is_existence = True if filename in sftp.listdir(f'{remote_dir}/') else False if not is_existence: sftp....
  • /usr/bin/python # -*- coding:utf-8 -*- import paramiko remotedir = "/root" remotefile = "/root/log_history.txt" hostname = "10.142.152.xxx" port = 22 username = "...
  • username=’usrname’, password=’mypassword’) sftp_client = client.open_sftp() ncfile = sftp_client.open('mynetCDFfile') b_ncfile = ncfile.read() # **** nc = Dataset('test.nc', memory=b_ncfile) But ...
  • 使用SFTP上传与下载文件 方法一 import paramiko transport = paramiko.Transport(("106.15.88.182", 22)) # 获取Transport实例 transport.connect(username="root", password="123456") # 建立连接 # 创建sftp...
  • python sftp 的使用

    2013-06-28 16:23:59
    1、paramiko支持 官网:http://www.lag.net/paramiko/ 下载地址:https://github.com/paramiko/paramiko/archive/master.zip # 安装方法:解压到某个文件夹,进入... python setup.py install2、pycrypto支持...
  • .sftp.get(remote, os.path.join(local, filename))   else :   parent, child  =   os.path.split(remote)     for   dirpath, dirnames, filenames  in   self ._walk_remote...
  •  self._sftp.get(remote, os.path.join(local, filename))  else:  parent, child = os.path.split(remote)  for dirpath, dirnames, filenames in self._walk_remote(remote):  dirpath = ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 9,618
精华内容 3,847
关键字:

pythonsftp

python 订阅