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 ...
随机推荐
- C++记录(二)
1.算术移位和逻辑移位. 逻辑移位是只补0,算术移位是看符号,负数补1,正数补0(讨论的是右移的情况下). 负数左移右边一样补0.如果遇到位运算的相关题目需要对int变量进行左移而且不知道正负,那么先 ...
- ++i、i++、+=、-=的区别
要分清这个区别,先要掌握赋值的顺序,赋值语句是从右往左执行的, 计算的顺序从左至右. 那么++i第一步是把自身i+1后才赋值给自身,即先加后赋值. i++第一步是先把自身赋值给自身,即先赋值后再加减. ...
- 安装vmware tools后仍然不能拖拽文件
运行/usr/bin/vmware-user文件 ./vmware-user
- mysql行级锁 select for update
mysql行级锁 select for update 1.属于行级锁 2.where条件后需要写出明确的索引条件(如果有多个条件,可以建立联合索引) 3.如果其所在的事务提交或者回滚后,或者更新该条数 ...
- 09 部署nginx web服务器(转发uwsgi请求)
1 配置nginx转发 $ whereis nginx $ cd /usr/local/nginx/conf $ vi nginx.conf 注释掉原来的html请求,增加uwsgi请求. locat ...
- EF中的持久化场景
使用EF实现实体持久化(保存)到数据库有两种情况:在线场景和离线场景. 1.在线场景 在线场景中,context是上下文实例,读写都通过一个context. 这种方案适用于连接本地数据库或同一网络上的 ...
- plt/sns draw histgram
当使用如下代码保存使用 plt.savefig 保存生成的图片时,结果打开生成的图片却是一片空白. import matplotlib.pyplot as pltx = np.triu(ged) # ...
- spring(三):BeanDefiniton
- Codeforces Round #598 (Div. 3) B Minimize the Permutation
B. Minimize the Permutation You are given a permutation of length nn. Recall that the permutation is ...
- GoAhead WebServer 架构
https://blog.csdn.net/jungsagacity/article/details/7307012