paramiko-tools
own dev
# coding=utf-8
import paramiko
import os
import logging
import json
import unittest
from stat import S_ISDIR,S_ISREG
logging.basicConfig(level = logging.ERROR,format = '%(asctime)s - %(levelname)s -->%(funcName)s at line %(lineno)d: \n %(message)s')
log= logging.getLogger() class ParamikoSftp(object): def __init__(self,ip,port,user,pwd):
self.port = port
self.pwd = pwd
self.user = user
self.ip = ip
self.cli=self.sftp_client()
self.para_cli=self.ssh_client()
self.para_sftp=self.para_cli.open_sftp() def sftp_client(self):
self.tp = paramiko.Transport(self.ip, self.port)
self.tp.connect(username=self.user, password=self.pwd)
self.sftp = paramiko.SFTPClient.from_transport(self.tp)
return self.sftp def ssh_client(self):
client = paramiko.SSHClient()
try:
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.ip, self.port, self.user, self.pwd)
if client:
return client
except Exception as e:
log.error(e) # paramiko function
def query_dir(self,dir)->list:
connection = self.para_cli
shell="ls -l %s | awk '{print $9}'" % dir
input, out, err = connection.exec_command(shell)
res, err = out.readlines(), err.read()
if res:
files_list = [i.strip('\n') for i in res if i.strip('\n')]
return files_list
if err:
raise FileExistsError(err.decode("utf-8")) # paramiko function
def callback_stdout(self,shell:str):
connection=self.para_cli
try:
input, out, err = connection.exec_command(shell,get_pty=True)
res, err = out.readlines(), err.read()
if res:
i=''
for j in res:
i =i+j
return i
if err:
return err.decode("utf-8")
except Exception as f:
log.error(f) def touch(self,filepath):
client =self.para_cli
def create_file(filepath):
client.exec_command("touch %s"%filepath)
a=self.exists_file(filepath)
if a:
self.removes(filepath)
create_file(filepath)
info={"msg": "File {} found and have remove it ,success create {}".format(filepath,filepath),"cdde":200,"status":"success"}
log.info(json.dumps(info,indent=4,ensure_ascii=False) ) else:
create_file(filepath) #sftp func
def mkdir(self,dir):
client=self.cli
try:
bool=self.exists_dir(dir)
if bool:
client.rmdir(dir)
client.mkdir(dir)
else:
client.mkdir(dir)
except Exception as e:
log.error("{'msg': 'mkdir %s failed maybe it have exists same name file or dir ,'code':100,'status': 'failed'}"%dir) #sftp func
def removes(self,filepath):
client=self.cli
try:
if self.exists_file(filepath):
client.remove(filepath)
else:
pass
except FileNotFoundError as e:
info={'msg': 'File %s Not Found Error'%filepath, 'retcode':100,'status': 'failed'}
log.error(json.dumps(info,ensure_ascii=False,indent=4),exc_info=False) def list_dir(self,dir):
client=self.cli
try:
res= client.listdir(dir)
return res
except FileNotFoundError:
log.error("{'msg': '%s Not Found Error', 'retcode':100,'status': 'failed'}"%dir) # sftp function
def rm(self,absdir):
def isdirs(filepath, sftp):
return S_ISDIR(sftp.stat(filepath).st_mode)
def subsftp(absdir,sftp):
files = sftp.listdir(absdir)
try:
for file in files:
filepath = os.path.join(absdir, file)
fps = filepath.replace("\\", "/")
if isdirs(fps, sftp):
self.rm(fps)
else:
sftp.remove(fps)
log.info("{'msg': 'remove file %s success,'retcode': 200}" %(fps))
# rmdir empty dir
sftp.rmdir(absdir)
except Exception as e:
log.error(e)
else:
log.info("{'msg': 'finished rm %s del self or its subdir and subfile,'recode':200}" % (absdir))
sftp=self.cli
try:
subsftp(absdir, sftp)
except Exception as e:
log.error(e) # sftp func
def exists_dir(self,dir):
client=self.cli
def isdirs(dir, sftp):
return S_ISDIR(sftp.stat(dir).st_mode)
try:
isdirs(dir,client)
return True
except FileNotFoundError as f:
return False #sftp func
def exists_file(self,filepath):
client=self.para_sftp
try:
client.stat(filepath)
except Exception as e:
return False
else:
log.info("exists %s file "%filepath)
return True
def is_dir(self,dir):
try:
sftp = self.cli
result = S_ISDIR(sftp.stat(dir).st_mode)
except IOError: # no such file
result = False
return result def is_file(self,filepath):
try:
sftp=self.cli
result = S_ISREG(sftp.stat(filepath).st_mode)
except IOError: # no such file
result = False
return result def makedirs(self,remotedir,mode=777):
if self.is_dir(remotedir):
pass elif self.is_file(remotedir):
raise OSError("a file with the same name as the remotedir, "
"'%s', already exists." % remotedir)
else: head, tail = os.path.split(remotedir)
if head and not self.is_dir(head):
self.makedirs(head, mode)
if tail:
self.cli.mkdir(remotedir, mode=mode)
def sftp_close(self):
self.cli.close()
self.para_cli.close()
self.para_sftp.close() class TestSftp(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ip = "192.168.110.151"
port = 22
user = "root"
pwd = "admin"
cls.client =ParamikoSftp(ip, port, user, pwd)
log.info("start selfcheck method of sftp ") @classmethod
def tearDownClass(cls) -> None:
cls.client.sftp_close()
log.info("finish selfcheck method of sftp ") def test_query_dir(self):
"""test listdir"""
files=self.client.query_dir("/usr/local/listdir")
self.assertIn('list.txt',files)
def test_call_backstdout(self):
shell="ls -l /usr/local"
readlines=self.client.callback_stdout(shell)
self.assertIn("redisdb",readlines) def test_exsitdir(self):
a=self.client.exists_dir("/usr/local")
assert a==True def test_exsistfile(self):
b=self.client.exists_file("/usr/local/redisdb/logs/redis.log")
assert b==True def test_touch(self):
"""create file """
path="/usr/local/toutest.txt"
self.client.touch(path)
a=self.client.exists_file(path)
self.assertEqual(a,True)
import time
time.sleep(1)
self.client.removes(path)
def test_remove(self):
"""remove file """
path="/usr/local/tou.txt"
self.client.touch(path)
self.client.removes(path)
a=self.client.exists_file(path)
self.assertEqual(a,False) def test_mkandrm(self):
"""test mkdir exists already and rm dir """
self.client.mkdir("/usr/local/test1")
self.client.rm("/usr/local/test1") def test_makedirs(self):
dir="/usr/local/makedir1"
self.client.makedirs(dir)
r=self.client.exists_dir(dir)
self.assertEqual(r,True)
self.client.rm(dir) def test_is_dir(self):
path="/usr/local"
r=self.client.is_dir(path)
self.assertEqual(r,True)
file = "/usr/local/redisdb/logs/redis.log"
r2=self.client.is_dir(file)
self.assertEqual(r2,False) def test_isfile(self):
file="/usr/local/redisdb/logs/redis.log"
r=self.client.is_file(file)
self.assertEqual(r,True)
a="/usr/local"
b=self.client.is_file(a)
self.assertEqual(b,False) if __name__ == '__main__': unittest.main(verbosity=2)
测试:
[root@hostuser local]# python mutilinux.py
test_call_backstdout (__main__.TestSftp) ... ok
test_exsistfile (__main__.TestSftp) ... ok
test_exsitdir (__main__.TestSftp) ... ok
test_is_dir (__main__.TestSftp) ... ok
test_isfile (__main__.TestSftp) ... ok
test_makedirs (__main__.TestSftp) ... ok
test_mkandrm (__main__.TestSftp)
test mkdir exists already and rm dir ... ok
test_query_dir (__main__.TestSftp)
test listdir ... ok
test_remove (__main__.TestSftp)
remove file ... ok
test_touch (__main__.TestSftp)
create file ... ok
----------------------------------------------------------------------
Ran 10 tests in 1.909s
OK
paramiko-tools的更多相关文章
- python的paramiko源码修改了一下,写了个操作命令的日志审计 bug修改
python的paramiko源码修改了一下,写了个操作命令的日志审计,但是记录的日志中也将backspace删除键记录成^H这个了,于是改了一下代码,用字符串的特性. 字符串具有列表的特性 > ...
- 使用paramiko进行打包操作
使用paramiko执行ssh命令的时候有一个很坑爹的地方:它无法准确的识别你的系统环境变量,所以使用一些命令的时候会发现,直接在系统中执行该命令的时候可以,但是换成paramiko执行的时候会报错说 ...
- Mac OSX 安装Python的paramiko模块经验总结
一.简单介绍 最近需要用Python模拟登录远程服务器并自动执行一些代码,需要安装一个叫paramiko的模块. paramiko官方介绍遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接 ...
- Python之开发自动化管理工具paramiko
一.paramiko模块使用 1)远程执行主机命令获取结果 方法一 import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_ ...
- django 项目发布(centos 6.5 + python 3.5 + django1.9.8 + paramiko 2.0.2 + gunicorn )
环境 os centos 6.5 64bit python 3.5 django 1.9.8 paramiko 2.0.2 gunicorn 19.6.0 安装 centos install pyth ...
- 解决 Could not find com.android.tools.build:gradle 问题
今天拉同事最新的代码,编译时老是报如下错误: Error:Could not find com.android.tools.build:gradle:2.2.0.Searched in the fol ...
- 免费的精品: Productivity Power Tools 动画演示
Productivity Power Tools 是微软官方推出的 Visual Studio 扩展,被用以提高开发人员生产率.它的出现一定程度上弥补和完善了 Visual Studio 自身的不足, ...
- 2.Kali安装VMware tools(详细+异常处理)
dnt@MT:~$ cd /media/cdrom0 进入光驱内 dnt@MT:/media/cdrom0$ ls 查看当前目录下有哪些内容manifest.txt run_upgrader.sh V ...
- 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用
上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...
- paramiko 的使用
paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作 SSHClient 用于远程连接机器执行基本命令,也可以执行shell脚本 基于用户名密码连接: def ssh_connect ...
随机推荐
- .NET知识梳理——4.特性Attribute
1. 特性 1.1 特性Attribute 特性就是一个类,继承自Attribute抽象类(该类无抽象方法.避免实例化),约定俗成用Attribute类结尾,标记时可省略掉Attribu ...
- 二分-G - 4 Values whose Sum is 0
G - 4 Values whose Sum is 0 The SUM problem can be formulated as follows: given four lists A, B, C, ...
- 超简单的OpenGL & WebGL & Three.js介绍_1
专业解释 什么是OpenGL OpenGL(Open Graphics Library即开放图形库或者“开放式图形库”)是用于渲染2D.3D矢量图形的跨语言.跨平台的应用程序编程接口(API). 这个 ...
- centos7 tar.gz zip 解压命令
tar负责打包,gzip负责压缩 tar -c: 建立压缩档案 -x:解压 -t:查看内容 -r:向压缩归档文件末尾追加文件 -u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个, ...
- JMeter CSRFToken认证登陆(正则提取器的使用)
转自:http://blog.csdn.net/lion19930924/article/details/51189210 前几天用JMeter模拟登陆,但是这个网站开启了csrf认证,因此在post ...
- amazon 1
# 跨境电商 Amazon 丰富强大的海外站 开店流程 https://www.cifnews.com/article/48921 注册事项以及二审怎么过 https://www.cifnews.co ...
- sql 单表操作
前戏 --创建表 create table xxx( id int unsigned not null auto_increment primary key, name varchar(20) not ...
- flask入门(二)
接着上文 讲一讲响应 flask调用视图函数后,会将其返回值作为响应的内容.大多数情况下,响应就是一个简单的字符串,作为HTML页面回送客户端.但HTTP协议需要的不仅是作为请求响应的字符串.HTTP ...
- mysql之instr函数
1.用于模糊查询,做为过滤条件 ---------------------------上级的新闻下级可以看到-------------------------SELECT a.pk_cms_nrgl_ ...
- Contos7下安装Redis
第一步:在线下载Redis的安装包 cd /opt/ wget http://download.redis.io/releases/redis-5.0.2.tar.gz `ps:也可自行下载到本地,让 ...