Course4-Python ftp/ssh
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的更多相关文章
- 使用python通过SSH登陆linux并操作
用的昨天刚接触到的库,在windows下通过paramiko来登录linux系统并执行了几个命令,基本算是初试成功,后面会接着学习的. 代码: >>> import paramiko ...
- python通过SSH登陆linux并操作
使用python通过SSH登陆linux并操作 用的昨天刚接触到的库,在windows下通过paramiko来登录linux系统并执行了几个命令,基本算是初试成功,后面会接着学习的. 代码: > ...
- python下ssh的简单实现
python下的ssh都需要借助第三方模块paramiko来实现,在使用前需要手动安装. 一.python实现ssh (1) linux下的ssh登录 root@ubuntu:~# ssh morra ...
- python多线程ssh爆破
python多线程ssh爆破 Python 0x01.About 爆弱口令时候写的一个python小脚本,主要功能是实现使用字典多线程爆破ssh,支持ip表导入,字典数据导入. 主要使用到的是pyth ...
- python实现ssh远程登录
python实现ssh远程登录 # 测试过程中,比较常用的操作就是将DUT(待测物)接入网络中,然后远程操控对DUT, # 使用SSH远程登陆到主机,然后执行相应的command即可 # python ...
- 审计系统---堡垒机python下ssh的使用
堡垒机python下ssh的使用 [堡垒机更多参考]http://www.cnblogs.com/alex3714/articles/5286889.html [paramiko的Demo实例]htt ...
- python ftp操作脚本&常用函数
需求:快速进行ftp上传 ,下载,查询文件 原来直接在shell下操作: 需要[连接,输用户名,输密码,单文件操作,存在超时限制] 太过于繁琐,容易操作失败 脚本改进: 一句命令,搞定多文件上传,下载 ...
- Python 进行 SSH 操作,实现本地与服务器的链接,进行文件的上传和下载
Python 进行 SSH 操作,实现本地与服务器的链接,进行文件的上传和下载 2018年5月26日 19:03 阅读 375 评论 7 我本地和服务器的连接一直使用的是 Xshell 5,而在与服务 ...
- Python Fabric ssh 配置解读
Python Fabric ssh 配置解读 Fabric 2.4简介: Fabric is a high level Python (2.7, 3.4+) library designed to e ...
- 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 ...
随机推荐
- Android旋转动画
Android旋转动画 核心方法 public void startAnimation(Animation animation) 执行动画,参数可以是各种动画的对象,Animation的多态,也可以是 ...
- windows下实现win32俄罗斯方块练手,编程的几点心得
编程珠玑2阅读笔记: 1.使用c语言性能监视器,完成对代码的调优工作 2.关联数组: 拓扑排序算法,可以用于当存在遮挡的时候决定三维场景的绘制顺序. 3.小型算法中的测试与调试工具 脚手架程序:&l ...
- Sybase - tempdb
前沿:换了新公司,公司使用的Sybase数据库.现在开始学习Sybase数据库了.希望未来的几个月能对Sybase由浅入深的了解和研究. Tempdb的作用 sybase server端内部使用 排序 ...
- Android简易实战教程--第三话《自己实现打电话》
需要一个文本输入框输入号码,需要一个按钮打电话.本质:点击按钮,调用系统打电话功能. xml布局文件代码:: <LinearLayout xmlns:android="http://s ...
- String压缩 解压缩
数据传输时,有时需要将数据压缩和解压缩,本例使用GZIPOutputStream/GZIPInputStream实现. 1.使用ISO-8859-1作为中介编码,可以保证准确还原数据 2.字符编码确定 ...
- HTML超链接之伪类注意事项
今天在复习html相关知识的时候发现了一个很常用,却经常被人们所忽略的知识点.那就是超链接伪类的使用.下面我就直接用代码来说明这一切. 伪类的相关代码 <!DOCTYPE html> &l ...
- Java EE 之 过滤器入门学习与总结(2)
今天就对使用Filter技术能做什么来个小小的归纳.也为了方便今后的复习. 控制浏览器不进行对jsp页面的缓存 //在doFilter方法中添加这样的代码 HttpServletRequest req ...
- java wait和notify及 synchronized sleep 总结
java 中线程我一直弄不清线程锁等 所以写了一些例子验证看法: 在这之前先看下API中wait中的解释: wait:方法来之java.lang.Objetc 方法翻译:在其他线程调用此对象的 not ...
- 定制Maven原型生成项目
1自定义原型 1.1创建原型项目 要定制自己的原型,首先就要创建原型项目来进行定制: mvnarchetype:create -DgroupId=com.cdai.arche -DartifactId ...
- Mybatis接口编程原理分析(二)
在上一篇博客中 Mybatis接口编程原理分析(一)中我们介绍了MapperProxyFactory和MapperProxy,接下来我们要介绍的是MapperMethod MapperMethod:它 ...