#!/usr/ftpbin/env python
# -*- coding: utf-8 -*-
# @version : 0.0.1
# @File : RemoteUnix.py
# @Time : 2019/7/4 16:43
# @Site :
# @Software: PyCharm
# @Author : KANGXINWEN
# @Author_email: singbogo@163.com
# @description:
# 远程管理window
# 1、pip install paramiko
# 2、创建SSH对象
# 3、把要连接的机器添加到known_hosts文件中
# 4、连接服务器
#
import paramiko
import time
import sys
from api.filegener.fileoperator.dir import Dir
from api.filegener.fileoperator.filebase import FileBase
from util.logutil.log import logger
class AutomainPlantfSSHClient(object):
def __init__(self, *args):
""" 初始化 """
self._transport = None
self._channel = None
self.setlog()
self.host, self.port, self.author = args[0][0], args[0][1], args[0][2]
self.session(self.host, self.port, self.author)
def setlog(self, log="paramiko_1.log"):
"""设置是否记录log
@log: log文件地址
"""
paramiko.util.log_to_file(log)
def session(self, *args):
"""
args = ['ip','port','user','passwd']
"""
print("conneting to %s:%d"%(args[0], args[1]))
self._transport = paramiko.Transport(args[0], int(args[1])) # 建立一个加密的管道
self._transport.start_client()
# 用户名密码方式
self._transport.auth_password(args[2][0], args[2][1])
# 打开一个通道
self._channel = self._transport.open_session()
self._channel.settimeout(7200)
# 获取一个终端
self._channel.get_pty()
# 激活器
self._channel.invoke_shell()
return self._transport, self._channel
def isconnected(self):
""" is Connection successful """
if self._channel is None:
return False
else:
return True
def close(self):
"""" 关闭连接 """
if self._channel:
self._channel.close()
if self._transport:
self._transport.close()
def send(self, cmd):
""" 发送要执行的命令 """
if self._channel is None or cmd is None:
return None
cmd += '\r'
print(cmd)
return self._channel.send(cmd)
def always_perform(self):
""" 模式: 创建session 等待屏幕输入 发送远程命令 接受结果 等待命令 如果是 'quit', 'bye', 'exit', <ctrl + x> 退出并关闭session"""
prompt = '\ntell me something, and I will repeat it back to you:'
prompt += "\nEnter 'quit' or 'bye' or 'exit' to end the program.\n"
sys.stdout.write(prompt)
response, message = str(), str()
while message not in ('quit', 'bye', 'exit'):
message = input('>>>')
if message not in ('quit', 'bye', 'exit'):
# 发送远程命令
response = self.send(message)
# 处理返回信息
self.dispose(response)
else:
self.close()
break
def dispose(self, object):
""" 处理信息 返回状态判断 字符类型转换 格式化输出 """
# 回显很长的命令可能执行较久,通过循环分批次取回回显
# 如何判断recv已经完成 出现超时等待
if self._channel is None or object is None:
return False
message, ret = str(), str()
while not message.endswith(' '):
time.sleep(0.2)
ret = self._channel.recv(65535)
try:
ret = ret.decode('utf-8')
except:
ret = ret.decode('gbk')
message += ret
print(message)
return message
def upload(self, localpath, remotepath):
"""
new transport to upload
:return:
"""
transport = paramiko.Transport(self.host, self.port)
transport.connect(username=self.author[0], password=self.author[1])
sftp = paramiko.SFTPClient.from_transport(transport)
import os.path
# file
SFTPAttributesobj=list()
try:
if os.path.isfile(localpath):
if FileBase.isExist(localpath):
name = FileBase(localpath).filenamne()
SFTPAttributesobj.append(sftp.put(localpath, remotepath+"//"+str(name)))
elif os.path.isdir(localpath):
if Dir().dirExist(localpath):
for path in localpath:
for root, dirs, files in os.walk(path):
for file in files:
SFTPAttributesobj.append(sftp.put(localpath + "//" + file, remotepath + "//" + file))
# an SFTPAttributes object containing attributes about the given file
# st_size # st_uid # st_gid # st_mode # st_atime # st_mtime
except Exception as e:
logger.error(str(e))
finally:
transport.close()
return SFTPAttributesobj
def remote_fileExist_cmd(self, filename):
"""
remote PC file/Dir is Exist
:return:
"""
return """if [ -d %s ];then echo "(%s存在)"; else echo "(%s不存在)"; fi"""%(filename, filename, filename)
if __name__ == '__main__':
list1 = ["IP", 22, ("user", "passwd")]
automainPlantfSSHClient = AutomainPlantfSSHClient(list1)
# automainPlantfSSHClient.session("IP", 22, "user", "passwd")
# automainPlantfSSHClient.always_perform()
automainPlantfSSHClient.dispose(automainPlantfSSHClient.send("cd /home/weblogic"))
automainPlantfSSHClient.dispose(automainPlantfSSHClient.send(automainPlantfSSHClient.remote_fileExist_cmd("dubbo")))
automainPlantfSSHClient.dispose(automainPlantfSSHClient.send("java -Dwebdriver.ie.driver=F:\document\Source\AutoMation\python\AutoMation_Frame\AutomainPlatformUI\drivers\IEDriverServer.exe -jar F:\document\Source\AutoMation\python\AutoMation_Frame\AutomainPlatformUI\drivers\selenium-server-standalone-3.141.59.jar -role node -hub http://127.0.0.1:4444/grid/register -maxSession 20 -browser 'browserName=internet explorer,version=9,platform=WINDOWS,maxInstances=20' -port 5556"))