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 ...
随机推荐
- <if test="type == '0' ">没有进去这个判断的问题
在MyBatis的mapp文件中的if判断中是这样写的 <if test="type == '0' "> and so1.id = #{unitcode} </i ...
- Python入门4 —— 输入与输出
一:输入(Input) 1.python3中的input(输入) inp_username=input("请输入您的密码:") # "18" print(inp ...
- Entry小部件:
导入tkinter import Tkinter from Tinter import * import tkinter from tinter import * 实例化Tk类 root=tkinte ...
- 安装php-zbarcode的步骤方法
1 安装ImageMagick依赖 yum install ImageMagick ImageMagick-devel 2 安装zbar拓展 wget -c http://jaist.dl.sourc ...
- C语言-指针深度分析
1.变量回顾 程序中的变量只是—段存储空间的别名,那么是不 是必须通过这个别名才能使用这段存储空间? 2.思考 下面的程序输出什么?为什么? ; int* p = &i; p ...
- 基于Java+HttpClient+TestNG的接口自动化测试框架(八)------ 针对文件的处理
在实际的接口测试中,有时需要根据情况进行文件的上传和下载.在文件数量比较小的时候,我们当然可以直接处理(比如若干个接口都用一个文件).但是,如果我们上传的文件需要使用不同文件夹里不同的文件,而且数量又 ...
- Java Web代码审计流程与漏洞函数
常见框架与组合 常见框架 Struts2 SpringMVC Spring Boot 框架执行流程 View层:视图层 Controller层:表现层 Service层:业务层 Dom层:持久层 常见 ...
- css 页面滚动 多背景固定不动
经常看到一些网站,滚动页面但是背景图不会跟着滚动,好像一直固定在浏览器窗口,感觉挺酷的,哇哦 ~ ~ 原来都是 background-attachment 这位大兄弟的功劳 background-at ...
- CompletableFuture--给future调用增加回调或聚合操作
CompletableFuture--增大内存节省时间.整合多个future调用,来减少时间 例如:第一个future 返回时1s,第二个返回时2s,第三个返回是3s CompletableFut ...
- L2-3 名人堂与代金券
题解 这题的话,每一个人都要占一个排名,即使排名并列了. 对于最后一个排名来说,即使人数超过了指定的k,也要加入. 代码 #include <bits/stdc++.h> using na ...