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的更多相关文章

  1. python的paramiko源码修改了一下,写了个操作命令的日志审计 bug修改

    python的paramiko源码修改了一下,写了个操作命令的日志审计,但是记录的日志中也将backspace删除键记录成^H这个了,于是改了一下代码,用字符串的特性. 字符串具有列表的特性 > ...

  2. 使用paramiko进行打包操作

    使用paramiko执行ssh命令的时候有一个很坑爹的地方:它无法准确的识别你的系统环境变量,所以使用一些命令的时候会发现,直接在系统中执行该命令的时候可以,但是换成paramiko执行的时候会报错说 ...

  3. Mac OSX 安装Python的paramiko模块经验总结

    一.简单介绍 最近需要用Python模拟登录远程服务器并自动执行一些代码,需要安装一个叫paramiko的模块. paramiko官方介绍遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接 ...

  4. Python之开发自动化管理工具paramiko

    一.paramiko模块使用 1)远程执行主机命令获取结果 方法一 import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_ ...

  5. 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 ...

  6. 解决 Could not find com.android.tools.build:gradle 问题

    今天拉同事最新的代码,编译时老是报如下错误: Error:Could not find com.android.tools.build:gradle:2.2.0.Searched in the fol ...

  7. 免费的精品: Productivity Power Tools 动画演示

    Productivity Power Tools 是微软官方推出的 Visual Studio 扩展,被用以提高开发人员生产率.它的出现一定程度上弥补和完善了 Visual Studio 自身的不足, ...

  8. 2.Kali安装VMware tools(详细+异常处理)

    dnt@MT:~$ cd /media/cdrom0 进入光驱内 dnt@MT:/media/cdrom0$ ls 查看当前目录下有哪些内容manifest.txt run_upgrader.sh V ...

  9. 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用

    上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...

  10. paramiko 的使用

    paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作 SSHClient 用于远程连接机器执行基本命令,也可以执行shell脚本 基于用户名密码连接: def ssh_connect ...

随机推荐

  1. Jupyter Notebook快捷键总结

    1. Jupyter Notebook有两种mode Enter:进入edit模式 Esc:进入command模式 2. Command命令快捷键: A:在上方增加一个cell B:在下方增加一个ce ...

  2. DE1_MSEL

    基础的一般实验:01001(现在用的)或10010 马上换linux,做个记录: sd卡启动linux系统时,启动开关0至4位拨至00000

  3. 如何面试QA(面试官角度)

    面试是一对一 或者多对一的沟通,是和候选人 互相交换信息.平等的. 面试的目标是选择和雇佣最适合的人选.是为了完成组织目标.协助人力判断候选人是否合适空缺职位. 面试类型: (1)预判面试(查看简历后 ...

  4. selenium 百度登录

    private String baseUrl="http://www.baidu.com/"; --------- @Test public void testLoginB() t ...

  5. HTML备忘

    a标签事件 a:link {color: #000000} /* 未访问的链接 */ a:visited {color: #d90a81} /* 已访问的链接 */ a:hover {color: # ...

  6. Myeclipse的一些快捷键整理(转)

    1. [ALT+/]    此快捷键为用户编辑的好帮手,能为用户提供内容的辅助,不要为记不全方法和属性名称犯愁,当记不全类.方法和属性的名字时,多体验一下[ALT+/]快捷键带来的好处吧.    2. ...

  7. beego登录退出与检查登录过滤器

    // ShowLogin 登陆显示 func (c *UserController) ShowLogin() { username := c.Ctx.GetCookie("username& ...

  8. js bug

    1 加载模块脚本失败:服务器以非JavaScript MIME类型“text/html”响应. 描述:ES6 import Class时路径出错,少一个 / ,添上即可

  9. 题解【洛谷P1938】 [USACO09NOV]找工就业Job Hunt

    题面 题解 将路径连边\((x, y, d)\) ,将航线连边\((x, y, d - w)\).其中线路是从\(x\)到\(y\),航线的费用为\(w\),\(d\)的含义如题面. 跑一遍\(SPF ...

  10. selenium的定位方法-多元素定位

    在实际工作中,有些时候定位元素使用ID.NAME.CLASS_NMAE.XPATH等方法无法定位到具体元素,会发现元素属性有很多一致的,这个时候使用单元素定位方法无法准确定位到具体元素,例如,百度首页 ...