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. ENVI自带的非监督分类测试情况

    最近写了两个关于遥感图像的简单的非监督分类算法KMEAN和ISODATA,发现结果和ENVI的一直有差异,而且还蛮大的,找了好久也没有找到原因.于是用PS自己绘制了一个简单的图像用于测试.如图1所示, ...

  2. 剑指Offer——网易笔试之解救小易——曼哈顿距离的典型应用

    剑指Offer--网易笔试之解救小易--曼哈顿距离的典型应用 前言 首先介绍一下曼哈顿,曼哈顿是一个极为繁华的街区,高楼林立,街道纵横,从A地点到达B地点没有直线路径,必须绕道,而且至少要经C地点,走 ...

  3. reactor线程阻塞引起故障

    大致线程模型: jstack打印JVM堆栈,可以看到reactor线程阻塞了,导致它对应的前端连接无法使用.阻塞在了oracle驱动rollback动作,这里其实是因为oracle驱动为了保证串行请求 ...

  4. (一一〇)正则表达式的基本使用与RegexKitLite的使用

    正则表达式常常用于匹配关键字,下面先介绍基本语法. [基本语法] ①中括号表示满足其中之一即可,例如[abc],则这个位置可以是a.b.c中任意一个. ②在中括号中,可以通过-连接范围,例如a-z:多 ...

  5. Android的数字选择器NumberPicker-android学习之旅(三十七)

    我想说的话 今天晚上我依然在图书馆写博客,其实此刻我的没心激动而忐忑,因为明天就是足球赛的决赛,我作为主力球员压力很大,因对对方很强大,但是那又怎么样.so what...我不会停止写博客的 Numb ...

  6. 【一天一道LeetCode】#242. Valid Anagram

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

  7. Linux/Android多点触摸协议

    链接点击打开链接 关于Linux多点触摸协议大家可以参考kernel中的文档:https://www.kernel.org/doc/Documentation/input/multi-touch-pr ...

  8. H5学习之旅-H5的元素属性(3)

    1.标签可以拥有属性,为标签提供更多的信息 2.属性以键值对的形式呈现例如:href = "www.baidu.com" 3.常用标签属性 :align对其方式 ,对齐方式,包括上 ...

  9. wing带你玩转自定义view系列(2) 简单模仿qq未读消息去除效果

    上一篇介绍了贝塞尔曲线的简单应用 仿360内存清理效果 这一篇带来一个  两条贝塞尔曲线的应用 : 仿qq未读消息去除效果. 转载请注明出处:http://blog.csdn.net/wingicho ...

  10. How Many Processes Should Be Set For The Receiving Transaction Manager (RTM)

    In this Document   Goal   Solution   References APPLIES TO: Oracle Inventory Management - Version 10 ...