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 ...
随机推荐
- linux中查看现在使用的shell是ksh还是bash?以及怎样修改?
查看系统支持的shell: cat /etc/shells 查看现在使用的shell: 修改默认shell: 另外,修改了系统默认shell之后不会立即生效,之后再次登录系统修改的shell才会生 ...
- UNIX网络编程——select函数的并发限制和 poll 函数应用举例
一.用select实现的并发服务器,能达到的并发数,受两方面限制 1.一个进程能打开的最大文件描述符限制.这可以通过调整内核参数.可以通过ulimit -n来调整或者使用setrlimit函数设置, ...
- Sharepoint2013部署ADFS 报new-sptrustedIdentityTokenIssuer:the trust provider certificate already exist
在做sharepoint2013的adfs部署时,根据MSDN的步骤到新建身份验证程序时,powershell中报"ADFS new-sptrustedIdentityTokenIssuer ...
- Objc运行时读取和写入plist文件遇到的问题
下面是本猫保持游戏NPC和物件交互的plist文件: 随着游戏和玩家逐步发生互动,玩家会修改人物和物件的交互的状态.这也是RPG游戏最基本的功能. 在切换每个地图时需要将上一个地图发生的改变存储到pl ...
- 【如何快速的开发一个简单的iOS直播app】(代码篇)
开篇([如何快速的开发一个完整的iOS直播app](原理篇)) 好久没写简书,因为好奇的我跑去学习直播了,今天就分享一下我的感慨. 目前为止直播还是比较热点的技术的,简书,git上有几篇阅读量和含金量 ...
- Android屏幕适配-android学习之旅(五十九)
android屏幕适配
- (七十一)关于UITableView退出崩溃的问题和滚动到底部的方法
[TableView退出崩溃的问题] 最近在使用TableView时偶然发现在TableView中数据较多时,如果在滚动过程中退出TableView到上一界面,会引起程序的崩溃,经过网上查阅和思考我发 ...
- 一致性Hash算法介绍(分布式环境算法)
32的整数环(这个环被称作一致性Hash环),根据节点名称的Hash值(其分布范围同样为0~232)将节点放置在这个Hash 环上.然后根据KEY值计算得到其Hash值(其分布范围也同样为0~232 ...
- java的map
Map是一种把键对象和值对象进行关联的容器,而一个值对象又可以是一个Map,依次类推,这样就可形成一个多级映射. 这里有详细的论述http://www.oracle.com/technetwork/c ...
- Chipmunk僵尸物理对象的出现和解决(二)
如第一篇文章中图片所示,该游戏是一个弹球游戏. 玩法很简单,屏幕底部有一个反弹棒,用来确保小球不掉出屏幕同时反弹小球撞击屏幕上方的砖块. 玩家可以触摸屏幕来左右移动反弹棒. 等等!还不是这么简单,当小 ...