1. ftp

Python 自带有模块支持ftp. 可以参看一下代码。

 #!/usr/bin/env python
import sys
import os
import time
import getopt
import traceback
from ftplib import FTP class ftp_up_down():
def __init__(self):
pass
def captureException(self,logname='ftp_log.log'):
logs = open(logname, 'a')
print >> logs, time.strftime('%Y-%m-%d %X', time.localtime())
err = ''.join(traceback.format_exception(*sys.exc_info()))
print >> logs, err
logs.close() def logging(self,mystring, filename='ftp_log.log'): try:
print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " " + mystring
fso = open(filename, 'a')
fso.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " " + mystring + '\n' + '\n')
fso.close()
except:
captureException() def ftp_up(self,ServerFolder, LocalLocation, FileName, ServerAddr, user, password):
try:
time1= time.time()
bufsize = 2048#set buffer size
ftp=FTP()
#ftp.set_debuglevel(2)#open debug level, 2 display the detailed info, 0 close the debug info
ftp.connect(ServerAddr)#connect
ftp.login(user,password)#login
print ftp.getwelcome()#display ftp server welcome message
ftp.cwd(ServerFolder) #choose the work directory
filename = LocalLocation + '\\' + FileName
file_handler = open(filename,'rb')#open the file in local as readonly
ftp.storbinary('STOR %s' % os.path.basename(filename),file_handler,bufsize)#upload file
ftp.set_debuglevel(0)
file_handler.close()
ftp.quit()
time2= time.time()
print "ftp up OK"
self.logging('Successfully upload file: "{0}" to FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
print round((time2-time1),3)
except:
self.logging('Fail to upload file: "{0}" to FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
self.captureException() def ftp_down(self,ServerFolder, LocalLocation, FileName, ServerAddr, user, password):
try:
time1= time.time()
bufsize = 2048#set buffer size
ftp=FTP()
#ftp.set_debuglevel(2)
ftp.connect(ServerAddr)#connect
ftp.login(user,password)#login
print ftp.getwelcome()#display ftp server welcome message
ftp.cwd(ServerFolder)#choose the work directory
filename = LocalLocation + '\\' + FileName
file_handler = open(filename,'wb').write #open the file in local as write
ftp.retrbinary('RETR %s' % os.path.basename(filename),file_handler,bufsize)#download file
ftp.set_debuglevel(0)
ftp.quit()
time2= time.time()
print "ftp down OK"
self.logging('Successfully download file: "{0}" from FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
print round((time2-time1),3)
except:
self.logging('Fail to download file: "{0}" from FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
self.captureException()
def usage(self): print '''
Usage:ftp_up_down [-u|-d]|[-S serverfolder| -L localfolder| -F filename| -I unix_ip| -U unix_user| -P unix_password]|[--help]\n
\t-u|-d -u means upload, -p means download\n
\t-S the unix folder to store the upload/download file\n
\t-L the Windows folder to store the upload/download file\n
\t-F the file name to be upload/download\n
\t-I the unix server ip\n
\t-U the unix user\n
\t-P the unix user password\n
Examples:
\tftp_up_down -d -S "/release/scripts/" -L "E:\\Daly\\Investigation\\" -F "a.txt" -I 10.100.99.1xx -U root -P pass\n
\tftp_up_down -u -S "/release/scripts/" -L "E:\\Daly\\Investigation\\" -F "a.txt" -I 10.100.99.1xx -U root -P pass
'''
ABSPATH=None
if __name__ == "__main__":
ABSPATH=os.path.abspath(sys.argv[0])
ABSPATH=os.path.dirname(ABSPATH)+"\\"
#print ABSPATH
work_folder=ABSPATH
#print work_folder
serverfolder=""
localfolder=""
filename=""
unix_ip=""
unix_user=""
unix_password=""
try:
opts,args = getopt.getopt(sys.argv[1:], "hudS:L:F:I:U:P:", ["help", "up", "down", "serverfolder=", "localfolder=", "filename=", "ip=", "user=", "password="])
#print opts
#print args
if not opts:
try:
ftp_up_down().usage()
except:
sys.exit(0)
for opt, arg in opts:
if opt in ("-h", "--help"):
ftp_up_down().usage()
sys.exit(0)
elif opt in ("-S"):
serverfolder = arg
elif opt in ("-L"):
localfolder = arg
elif opt in ("-F"):
filename = arg
elif opt in ("-I"):
unix_ip = arg
elif opt in ("-U"):
unix_user = arg
elif opt in ("-P"):
unix_password = arg
#print opts[0]
print serverfolder, localfolder, filename, unix_ip, unix_user, unix_password
try:
if("-u" in opts[0]):
try:
print serverfolder, localfolder, filename, unix_ip, unix_user, unix_password
ftp_up_down().ftp_up(ServerFolder=serverfolder, LocalLocation=localfolder, FileName=filename, ServerAddr=unix_ip, user=unix_user,password=unix_password)
except:
print ''.join(traceback.format_exception(*sys.exc_info()))
elif("-d" in opts[0]):
try:
#print serverfolder, localfolder, filename, unix_ip, unix_user, unix_password
ftp_up_down().ftp_down(ServerFolder=serverfolder, LocalLocation=localfolder, FileName=filename, ServerAddr=unix_ip, user=unix_user,password=unix_password)
except:
print ''.join(traceback.format_exception(*sys.exc_info()))
except:
print ''.join(traceback.format_exception(*sys.exc_info()))
except getopt.GetoptError:
print "getopt error"
ftp_up_down().usage()
sys.exit(1)

2. ssh

Python ssh需要安装其他模块支持,支持ssh的模块有pexpect(*Nix),paramiko等, 在此主要讲在Windows上支持的paramiko模块。可参看一下代码。

 import paramiko
class CommonUtils(object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
log().paramiko_log_to_file(level="DEBUG")
def ssh_conn(self,host,port,user,password):
'''
@param host: the host name or ip address
@param port: the ssh port number
@param user: the user to login the host
@param password: the user's password
example: ssh_conn("10.xx.xx.xx",22,'xxu1','password')
'''
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host,22,user,password)
return client
except Exception, e:
log().log("{0} Please check the user name and password are correct.".format(str(e)))
return None
def ssh_close(self,conn):
conn.close()
def ssh_exec_querycommand(self,conn,command):
'''
@param conn: the ssh connection which setup with using function ssh_conn
@param command: the command to be executed
'''
stdin, stdout, stderr = conn.exec_command(command)
stdin.flush()
output = []
for line in stdout:
print '###' + line.strip('\n')
output.append(line.strip('\n'))
if stderr != None and len(str(stderr)) == 0:
print 'Error info: ' + stderr.read()
return output
def ssh_exec_intercommand(self,conn,begincommand,promptanswer):
'''
@param conn: the ssh connection which setup with using function ssh_conn
@param begincommand: the command to be executed firstly
@param promptanswer: the command to be executed to answer the question after executed begincommand
'''
channel = conn.invoke_shell()
channel.recv(1024)
time.sleep(1)
channel.send(begincommand + '\n')
time.sleep(1)
question = channel.recv(1024)
#realquestion = (question.split(begincommand))[0:]
realquestion = (question.split('\n'))[1]
log().log("Question pops: {0}".format(realquestion))
time.sleep(1)
channel.send(promptanswer + '\n')
time.sleep(30)
result = channel.recv(1024)
log().log("After input answer: {0}".format(result))
channel.close()
return result
def ssh_exec_command_after_interaction(self,conn,begincommand,promptanswer,command):
'''
@param conn: the ssh connection which setup with using function ssh_conn
@param begincommand: the command to be executed firstly
@param promptanswer: the command to be executed to answer the question after executed begincommand
@param command: the command to be executed after the interaction
'''
channel = conn.invoke_shell()
channel.recv(1024)
time.sleep(1)
channel.send(begincommand + '\n')
time.sleep(1)
question = channel.recv(1024)
realquestion = (question.split(begincommand))[1]
#realquestion = (question.split('\n'))[1]
log().log("Question pops: {0}".format(realquestion))
time.sleep(1)
channel.send(promptanswer + '\n')
time.sleep(1)
result = channel.recv(1024)
log().log("After input answer: {0}".format(result))
channel.send(command + '\n')
time.sleep(3)
cmdresult = channel.recv(1024)
fullcmdresult = (cmdresult.split(command))[0]
realcmdresult = (fullcmdresult.split('\n'))[1:-1]
finalrestult = ''
for i in range(len(realcmdresult)):
finalrestult += ''.join(realcmdresult[i])
log().log("Command result: {0}".format(finalrestult))
channel.close()
return str(finalrestult)

Course4-Python ftp/ssh的更多相关文章

  1. 使用python通过SSH登陆linux并操作

    用的昨天刚接触到的库,在windows下通过paramiko来登录linux系统并执行了几个命令,基本算是初试成功,后面会接着学习的. 代码: >>> import paramiko ...

  2. python通过SSH登陆linux并操作

    使用python通过SSH登陆linux并操作 用的昨天刚接触到的库,在windows下通过paramiko来登录linux系统并执行了几个命令,基本算是初试成功,后面会接着学习的. 代码: > ...

  3. python下ssh的简单实现

    python下的ssh都需要借助第三方模块paramiko来实现,在使用前需要手动安装. 一.python实现ssh (1) linux下的ssh登录 root@ubuntu:~# ssh morra ...

  4. python多线程ssh爆破

    python多线程ssh爆破 Python 0x01.About 爆弱口令时候写的一个python小脚本,主要功能是实现使用字典多线程爆破ssh,支持ip表导入,字典数据导入. 主要使用到的是pyth ...

  5. python实现ssh远程登录

    python实现ssh远程登录 # 测试过程中,比较常用的操作就是将DUT(待测物)接入网络中,然后远程操控对DUT, # 使用SSH远程登陆到主机,然后执行相应的command即可 # python ...

  6. 审计系统---堡垒机python下ssh的使用

    堡垒机python下ssh的使用 [堡垒机更多参考]http://www.cnblogs.com/alex3714/articles/5286889.html [paramiko的Demo实例]htt ...

  7. python ftp操作脚本&常用函数

    需求:快速进行ftp上传 ,下载,查询文件 原来直接在shell下操作: 需要[连接,输用户名,输密码,单文件操作,存在超时限制] 太过于繁琐,容易操作失败 脚本改进: 一句命令,搞定多文件上传,下载 ...

  8. Python 进行 SSH 操作,实现本地与服务器的链接,进行文件的上传和下载

    Python 进行 SSH 操作,实现本地与服务器的链接,进行文件的上传和下载 2018年5月26日 19:03 阅读 375 评论 7 我本地和服务器的连接一直使用的是 Xshell 5,而在与服务 ...

  9. Python Fabric ssh 配置解读

    Python Fabric ssh 配置解读 Fabric 2.4简介: Fabric is a high level Python (2.7, 3.4+) library designed to e ...

  10. python ftp download with progressbar

    i am a new one to learn Python. Try to download by FTP. search basic code from baidu. no one tells h ...

随机推荐

  1. UNIX网络编程——epoll 系列函数简介、与select、poll 的区别

    前面博客<<UNIX环境高级编程--epoll函数使用详解>>有关于epoll函数的讲解. 一.epoll 系列函数简介 #include <sys/epoll.h> ...

  2. Android简易实战教程--第六话《开发一键锁屏应用2·完成》

    转载请注明出处:http://blog.csdn.net/qq_32059827/article/details/51885687点击打开链接 上一篇,初步开发了这个应用,功能都有了(见http:// ...

  3. Cocos2D v3.4.9粒子效果不能显示的原因分析及解决办法

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 在游戏App中为了衬托气氛我们往往使用一些特殊的图形效果,粒子 ...

  4. CONFIGURE ADFS 3.0 WITH SHAREPOINT 2013

     http://blogit.create.pt/miguelmoreno/2014/11/14/configure-adfs-3-0-with-sharepoint-2013/

  5. 解决ActionBar中的item不显示在ActionBar的问题

    今天在用ActionBar,需要增加一个菜单选项,按教程在/res/menu下对应的布局文件中添加了一个item,但是它却是显示在overflow中,而不是直接显示在ActionBar当中的.我的布局 ...

  6. SpriteBuilder实现2D精灵光影明暗反射效果(一)

    其实不用3D建模,用2D的图像就可以模拟3D场景中光照反射的效果. 这里我们不得不提到一个normalMap(法线图)的概念,请各位童鞋自己度娘吧,简单来说它可以使得2D表面生成一定细节程度的光照方向 ...

  7. 【一天一道LeetCode】#106. Construct Binary Tree from Inorder and Postorder Traversall

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源:http ...

  8. 【自制插件】MMD4Maya

    这个是之前MMD4MecanimImport的升级版,把pmx2fbx.exe整合了进来,不再需要Unity和MotionBuilder. 测试maya2015, maya2016可以用.maya20 ...

  9. printf函数压栈解惑

    最近看到一些程序员的笔试题目,经常会考到printf函数的参数压栈问题,总体来讲就是参数从右向左依次压栈,再出栈,但是今天看到一个看似很简单的题目,却一直找不到头绪.题目如下: #include &l ...

  10. Gradle 1.12 翻译——第十七章. 从 Gradle 中调用 Ant

    有关其他已翻译的章节请关注Github上的项目:https://github.com/msdx/gradledoc/tree/1.12,或访问:http://gradledoc.qiniudn.com ...