Course4-Python ftp/ssh

时间:2021-08-23 07:04:12

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. 写了一个常规性生成merge 的小脚本

    现在使用数据库来写存储过程,动不动参数就会用到xml ,当然罗,优势也很明显,参数相对固定,而且灵活,如果要修改或者什么的,中间接口层也不需要做变化,只需要修改封装的存储过程以及程序传参就ok了. 随 ...

  2. 数据结构《13》----二叉树 Morris 前序遍历

    三种二叉树的后序遍历的方法: 1. 递归                      O(n) 时间复杂度, O(n) 空间复杂度 2. 迭代(用栈)       O(n) 时间复杂度, O(n) 空间 ...

  3. vsftpd2.3.2安装、配置详解

    一.vsftpd 简介     Vsftpd是一个基于GPL发布的类UNIX系统的ftp服务器软件.其全称是Very Secure FTP Deamon,在安全性.速度和稳定性都有着不俗的表现.在安全 ...

  4. jQuery将字符串转换成json

    _menus = eval('(' + json.data + ')'); _menus = parseJSON('(' + json.data + ')');

  5. 01_自动化构建工具之Maven

    目前技术中存在问题(为什么使用Maven): 一个项目就是一个工程: 缺陷:如果项目太过庞大,就不适合使用package来划分层次,最好是一个模块就是一个工程,利于分工协作. 解决:Maven可以将一 ...

  6. 多线程协作wait、notify、notifyAll方法简介理解使用 多线程中篇(十四)

    在锁与监视器中有对wait和notify以及notifyAll进行了简单介绍 所有对象都有一个与之关联的锁与监视器 wait和notify以及notifyAll之所以是Object的方法就是因为任何一 ...

  7. vue的diff算法

    前言 我的目标是写一个非常详细的关于diff的干货,所以本文有点长.也会用到大量的图片以及代码举例,目的让看这篇文章的朋友一定弄明白diff的边边角角. 先来了解几个点... 1. 当数据发生变化时, ...

  8. Android : 关于HTTPS、TLS/SSL认证以及客户端证书导入方法

    一.HTTPS 简介 HTTPS 全称 HTTP over TLS/SSL(TLS就是SSL的新版本3.1).TLS/SSL是在传输层上层的协议,应用层的下层,作为一个安全层而存在,翻译过来一般叫做传 ...

  9. Ckeditor的JS的加载和取值和赋值方法

    Ckeditor 就是原来的Fckeditor. JS加载: $(function() { CKEDITOR.replace('FContent'); //FContent:这个对应文本域 }); J ...

  10. 【Unix网络编程】chapter6 IO复用:select和poll函数

    chapter6 6.1 概述 I/O复用典型使用在下列网络应用场合. (1):当客户处理多个描述符时,必须使用IO复用 (2):一个客户同时处理多个套接字是可能的,不过不叫少见. (3):如果一个T ...